For me, it was caused before I referred a library (specifically typeORM
, using the ormconfig.js
file, under the entities
key) to the src
folder, instead of the dist
folder...
"entities": [
"src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
],
instead of
"entities": [
"dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
],
You can use embed player with opacity over on a cover photo with a right positioned play icon. After this you can check the activeElement of your document.
Of course I know this is not an optimal solution, but works on mobile devices too.
<div style="position: relative;">
<img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
<iframe width="560" height="315" src="https://www.youtube.com/embed/2qhCjgMKoN4?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
</div>
<script>
setInterval(function(){
if(document.activeElement instanceof HTMLIFrameElement){
document.getElementById('cover').style.opacity=0;
document.getElementById('player').style.opacity=1;
}
} , 50);
</script>
Try it on codepen: https://codepen.io/sarkiroka/pen/OryxGP
You can use the standard JSON object, available in Javascript:
var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);
Here's a pure javascript solution,
<iframe
width="100%"
height="443"
class="yvideo"
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0"
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>
<script>
document.getElementById("myStopClickButton").addEventListener("click", function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}
});
Some might encounter this error either locally or on the server:
syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);
This means that their environment does not support short tags the solution is to use this instead:
<?php echo $jsonTable; ?>
And everything should work fine!
This works to sign the user out of the application, but not Google.
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
Source: https://developers.google.com/identity/sign-in/web/sign-in
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
try my code In JavaScript
var settings = {
"url": "https://myinboxhub.co.in/example",
"method": "GET",
"timeout": 0,
"headers": {},
};
$.ajax(settings).done(function (response) {
console.log(response);
if (response.auth) {
console.log('on success');
}
}).fail(function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 413) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 405) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
});;
In PHP
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
I might be old-school about this, but I still frown on hotlinking. Maybe Google is the exception, but in general, it's really just good manners to host the files on your own server.
Use the following code to get Name and Value of a dynamic object's property.
dynamic d = new { Property1= "Value1", Property2= "Value2"};
var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
var PropertyName=property.Name;
//You get "Property1" as a result
var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null);
//You get "Value1" as a result
// you can use the PropertyName and Value here
}
If you already have node installed, your path variable is set up and you suddenly start getting this error; try updating to the latest version.
This worked for me going from 6.9.2 to 6.10.
I have the same problem, but above some answers might be tricky for me.
I found the other answer maybe solve your question Twitter Bootstrap Js (tabs, popups, dropdown) not working in Drupal
place
jquery.js
beforebootstrap.tab.js
$(document).on('change','.radio-button', function(){
const radio = $(this);
if (radio.is(':checked')) {
console.log(radio)
}
});
Typically, git commit
brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR
environment variable) for you to edit your commit message in. When you save and exit, the commit completes.
You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.
I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.
As iOS does not use Java like Android, your options are quite limited:
1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).
2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.
3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.
The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.
Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.
As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.
Check into this thread,. However you should be careful as it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone. Also it appears as if some manufacturers have had issues with their phones having duplicate numbers thread. Depending on what your trying to do, I probably wouldnt use this as a UID.
You should put the various size images into the followings folder
for more detail visit this link
ldpi
mdpi
hdpi
xhdpi
xxhdpi
and use RelativeLayout or LinearLayout background instead of using ImageView as follwoing example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/your_image">
</RelativeLayout>
size_t lf = strlen(first);
size_t ls = strlen(second);
char *both = (char*) malloc((lf + ls + 2) * sizeof(char));
strcpy(both, first);
both[lf] = ' ';
strcpy(&both[lf+1], second);
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
In my project I did it like this:
@register.simple_tag()
def format_string(string: str, *args: str) -> str:
"""
Adds [args] values to [string]
String format [string]: "Drew %s dad's %s dead."
Function call in template: {% format_string string "Dodd's" "dog's" %}
Result: "Drew Dodd's dad's dog's dead."
"""
return string % args
Here, the string you want concatenate and the args can come from the view, for example.
In template and using your case:
{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}
The nice part is that format_string can be reused for any type of string formatting in templates
An addition to previous answers, to use Request.Params["__EVENTTARGET"]
you have to set the option:
buttonName.UseSubmitBehavior = false;
First, the extensions and libraries that we're going to use:
{-# LANGUAGE RankNTypes, TypeOperators #-}
import Control.Monad (join)
Of these, RankNTypes
is the only one that's absolutely essential to the below. I once wrote an explanation of RankNTypes
that some people seem to have found useful, so I'll refer to that.
Quoting Tom Crockett's excellent answer, we have:
A monad is...
- An endofunctor, T : X -> X
- A natural transformation, µ : T × T -> T, where × means functor composition
- A natural transformation, ? : I -> T, where I is the identity endofunctor on X
...satisfying these laws:
- µ(µ(T × T) × T)) = µ(T × µ(T × T))
- µ(?(T)) = T = µ(T(?))
How do we translate this to Haskell code? Well, let's start with the notion of a natural transformation:
-- | A natural transformations between two 'Functor' instances. Law:
--
-- > fmap f . eta g == eta g . fmap f
--
-- Neat fact: the type system actually guarantees this law.
--
newtype f :-> g =
Natural { eta :: forall x. f x -> g x }
A type of the form f :-> g
is analogous to a function type, but instead of thinking of it as a function between two types (of kind *
), think of it as a morphism between two functors (each of kind * -> *
). Examples:
listToMaybe :: [] :-> Maybe
listToMaybe = Natural go
where go [] = Nothing
go (x:_) = Just x
maybeToList :: Maybe :-> []
maybeToList = Natural go
where go Nothing = []
go (Just x) = [x]
reverse' :: [] :-> []
reverse' = Natural reverse
Basically, in Haskell, natural transformations are functions from some type f x
to another type g x
such that the x
type variable is "inaccessible" to the caller. So for example, sort :: Ord a => [a] -> [a]
cannot be made into a natural transformation, because it's "picky" about which types we may instantiate for a
. One intuitive way I often use to think of this is the following:
Now, with that out of the way, let's tackle the clauses of the definition.
The first clause is "an endofunctor, T : X -> X." Well, every Functor
in Haskell is an endofunctor in what people call "the Hask category," whose objects are Haskell types (of kind *
) and whose morphisms are Haskell functions. This sounds like a complicated statement, but it's actually a very trivial one. All it means is that that a Functor f :: * -> *
gives you the means of constructing a type f a :: *
for any a :: *
and a function fmap f :: f a -> f b
out of any f :: a -> b
, and that these obey the functor laws.
Second clause: the Identity
functor in Haskell (which comes with the Platform, so you can just import it) is defined this way:
newtype Identity a = Identity { runIdentity :: a }
instance Functor Identity where
fmap f (Identity a) = Identity (f a)
So the natural transformation ? : I -> T from Tom Crockett's definition can be written this way for any Monad
instance t
:
return' :: Monad t => Identity :-> t
return' = Natural (return . runIdentity)
Third clause: The composition of two functors in Haskell can be defined this way (which also comes with the Platform):
newtype Compose f g a = Compose { getCompose :: f (g a) }
-- | The composition of two 'Functor's is also a 'Functor'.
instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose (fmap (fmap f) fga)
So the natural transformation µ : T × T -> T from Tom Crockett's definition can be written like this:
join' :: Monad t => Compose t t :-> t
join' = Natural (join . getCompose)
The statement that this is a monoid in the category of endofunctors then means that Compose
(partially applied to just its first two parameters) is associative, and that Identity
is its identity element. I.e., that the following isomorphisms hold:
Compose f (Compose g h) ~= Compose (Compose f g) h
Compose f Identity ~= f
Compose Identity g ~= g
These are very easy to prove because Compose
and Identity
are both defined as newtype
, and the Haskell Reports define the semantics of newtype
as an isomorphism between the type being defined and the type of the argument to the newtype
's data constructor. So for example, let's prove Compose f Identity ~= f
:
Compose f Identity a
~= f (Identity a) -- newtype Compose f g a = Compose (f (g a))
~= f a -- newtype Identity a = Identity a
Q.E.D.
I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version. Then It works in local but not working when I uploaded the files to server. So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence. When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.
@font-face {
font-family: 'Ataturk';
font-style: normal;
font-weight: normal;
src: url('font/ataturk.eot');
src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'),
url('font/ataturk.woff') format('woff');
}
You can see it on my website here: http://www.canotur.com
Apart from following the optimizations mentioned in existing answers (not much helpful, was still painfully slow), doing below did the trick for me.
HP Notebook with 6 GM RAM and i5 processor I have, still android studio was terribly slow. After checking task manager for memory usage, noticed that there is a software called "HP Touchpoint Analytics Client" that was taking more than 1 GB memory. Found that it's a spyware installed by HP in Windows 10 after searching about it in Google.
Uninstalled a bunch of HP software which does nothing and slows down the system. Now, Android studio is considerably fast - Gradle build completes in less than 30 seconds when compared to more than 2 minutes before. Every keystroke would take 5 seconds to respond, now it is real time and performance is comparable with Eclipse.
This might be true for Laptops from other vendors as well like Dell, etc. HP really messed up the user experience with their spyware for Windows 10 users. Uninstall them, it will help Android studio and improves the overall laptop experience as well.
Hope this helps someone. Thanks.
To append key-value pairs to a json string, you can use dict.update: dictA.update(dictB)
.
For your case, this will look like this:
dictA = json.loads(jsonStringA)
dictB = json.loads('{"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}')
dictA.update(dictB)
jsonStringA = json.dumps(dictA)
Note that key collisions will cause values in dictB
overriding dictA
.
Use the getTime
method to get the time in total milliseconds since 1970-01-01, and subtract those:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
You can do something like this:
[10, 20, 30, 40].slice(-1)[0]
console.log([10, 20, 30, 40].slice(-1)[0])
_x000D_
The amount of helper methods that can be added to a language is infinite. I suppose they just haven't considered adding this one.
This is similar to https://stackoverflow.com/users/3396598/kohlbrr answer, but I was trying to get the total size of a single folder and found that the script doesn't count the files in the Root of the folder you are searching. This worked for me.
$startFolder = "C:\Users";
$totalSize = 0;
$colItems = Get-ChildItem $startFolder
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$totalSize = $totalSize + $subFolderItems.sum / 1MB
}
$startFolder + " | " + "{0:N2}" -f ($totalSize) + " MB"
If you commit one file and push your revision, it will not transfer the whole repository, it will push changes.
You can use Coil library to load svg. Just add these lines in build.gradle
// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")
Then Add an extension function
fun AppCompatImageView.loadSvg(url: String) {
val imageLoader = ImageLoader.Builder(this.context)
.componentRegistry { add(SvgDecoder([email protected])) }
.build()
val request = ImageRequest.Builder(this.context)
.crossfade(true)
.crossfade(500)
.data(url)
.target(this)
.build()
imageLoader.enqueue(request)
}
Then call this method in your activity or fragment
your_image_view.loadSvg("your_file_name.svg")
I use Xcode 7 and Swift 2. Last, I had made:
class ViewController: UIViewController{ var time: NSTimer //error this here }
Then I fix: class ViewController: UIViewController {
var time: NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
//self.movetoHome()
time = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(ViewController.movetoHome), userInfo: nil, repeats: false)
//performSegueWithIdentifier("MoveToHome", sender: self)
//presentViewController(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
}
func movetoHome(){
performSegueWithIdentifier("MoveToHome", sender: self)
}
}
The first form is called Javadoc. You use this when you're writing formal APIs for your code, which are generated by the javadoc
tool. For an example, the Java 7 API page uses Javadoc and was generated by that tool.
Some common elements you'd see in Javadoc include:
@param
: this is used to indicate what parameters are being passed to a method, and what value they're expected to have
@return
: this is used to indicate what result the method is going to give back
@throws
: this is used to indicate that a method throws an exception or error in case of certain input
@since
: this is used to indicate the earliest Java version this class or function was available in
As an example, here's Javadoc for the compare
method of Integer
:
/**
* Compares two {@code int} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Integer.valueOf(x).compareTo(Integer.valueOf(y))
* </pre>
*
* @param x the first {@code int} to compare
* @param y the second {@code int} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 1.7
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
The second form is a block (multi-line) comment. You use this if you want to have multiple lines in a comment.
I will say that you'd only want to use the latter form sparingly; that is, you don't want to overburden your code with block comments that don't describe what behaviors the method/complex function is supposed to have.
Since Javadoc is the more descriptive of the two, and you can generate actual documentation as a result of using it, using Javadoc would be more preferable to simple block comments.
If you're using a self hosted site like me, the way to avoid this problem (as described above) is to stipulate on both the host and client side that the wsHttpBinding security mode = NONE.
When creating the binding, both on the client and the host, you can use this code:
Dim binding as System.ServiceModel.WSHttpBinding
binding= New System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None)
or
System.ServiceModel.WSHttpBinding binding
binding = new System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None);
Great reference. Thanks! An addition to it:
If you happen to have a library project included which has declared custom attributes for a custom view, you have to declare your project namespace, not the library one's. Eg:
Given that the library has the package "com.example.library.customview" and the working project has the package "com.example.customview", then:
Will not work (shows the error " error: No resource identifier found for attribute 'newAttr' in package 'com.example.library.customview'" ):
<com.library.CustomView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.library.customview"
android:id="@+id/myView"
app:newAttr="value" />
Will work:
<com.library.CustomView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.customview"
android:id="@+id/myView"
app:newAttr="value" />
fwrite()
is a smidgen faster and file_put_contents()
is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents
writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite
writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.
I've created a working CodePen example demonstrating how to do this.
Relevant HTML:
<section ng-app="app" ng-controller="MainCtrl">
<a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
debug: {{debug.val}}
</section>
Relevant javascript:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.obj = {
val1: 'hello',
val2: 'world'
};
$scope.debug = {
val: ''
};
$scope.doSomething = function(input) {
$scope.debug.val = input;
};
});
class expression can be used for simplicity.
// Foo.js
'use strict';
// export default class Foo {}
module.exports = class Foo {}
-
// main.js
'use strict';
const Foo = require('./Foo.js');
let Bar = new class extends Foo {
constructor() {
super();
this.name = 'bar';
}
}
console.log(Bar.name);
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
If you use jQuery UI's datepicker and moment.js on the same project, you should piggyback off of moment.js's locale data:
// Finnish. you need to include separate locale file for each locale: https://github.com/moment/moment/tree/develop/locale
moment.locale('fi');
// fetch locale data internal structure, so we can shove it inside jQuery UI
var momentLocaleData = moment.localeData();
$.datepicker.regional['user'] = {
monthNames: momentLocaleData._months,
monthNamesShort: momentLocaleData._monthsShort,
dayNames: momentLocaleData._weekdays,
dayNamesShort: momentLocaleData._weekdaysMin,
dayNamesMin: momentLocaleData._weekdaysMin,
firstDay: momentLocaleData._week.dow,
dateFormat: 'yy-mm-dd' // "2016-11-22". date formatting tokens are not easily interchangeable between momentjs and jQuery UI (https://github.com/moment/moment/issues/890)
};
$.datepicker.setDefaults($.datepicker.regional['user']);
If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!
Here I have used jQuery function, it can be done by simple JavaScript also...
<form id="form_data">
<input type="anything" name="anything" />
<input type="anything" name="anything" />
<!-- Save and Reset button -->
<button type="button" id="btn_submit">Save</button>
<button type="reset" id="btn_reset" style="display: none;"></button>
</form>
<script type="text/javascript">
$(function(){
$('#btn_submit').click(function(){
// Do what ever you want
$('#btn_reset').click(); // Clicking reset button
});
});
</script>
The first form, when used with an API that returns Boolean
and compared against Boolean.FALSE, will never throw a NullPointerException
.
The second form, when used with the java.util.Map
interface, also, will never throw a NullPointerException
because it returns a boolean
and not a Boolean
.
If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean
that may be NULL
.
in my case, I must to set path in properties file, in many hours I find the way:
webdriver.gecko.driver="/lib/geckodriver-v0.26.0-win64/geckodriver.exe"
in java code:
private static final Logger log = Logger.getLogger(Login.class.getName());
private FirefoxDriver driver;
private FirefoxProfile firefoxProfile;
private final String BASE_URL = "https://www.myweb.com/";
private static final String RESOURCE_NAME = "main/resources/application.properties"; // could also be a constant
private Properties properties;
public Login() {
init();
}
private void init() {
properties = new Properties();
try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
properties.load(resourceStream);
} catch (IOException e) {
System.err.println("Could not open Config file");
log.log(Level.SEVERE, "Could not open Config file", e);
}
// open incognito tab by default
firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
// geckodriver driver path to run
String gekoDriverPath = properties.getProperty("webdriver.gecko.driver");
log.log(Level.INFO, gekoDriverPath);
System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + gekoDriverPath);
log.log(Level.INFO, System.getProperty("webdriver.gecko.driver"));
System.setProperty("webdriver.gecko.driver", System.getProperty("webdriver.gecko.driver").replace("\"", ""));
if (driver == null) {
driver = new FirefoxDriver();
}
}
If you have Linux machine just install puttygen in your system and use use below command to convert the key
pem to ppk use below command:
puttygen keyname -o keyname.ppk
Below command is use to convert ppk to pem not pem to ppk
puttygen filename.ppk -O private-openssh -o filename.pem
Here is Apple's documentation:
It says there are two things that you must get right:
armv6
to the Architecture build settingsNo
.If this still doesn't help you, double check that you are really changing the architecture build settings for the right build configuration – I wasted half an hour fiddling with the wrong one and wondering why it didn't work...
Select Edit Scheme...
in the Product menu, click the "Archive" scheme in the left list and check the Build Configuration. Change the value if it was not what you expected.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
In your mysql command line: SET explicit_defaults_for_timestamp=1
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
You can use \begin{flalign}
, like the example bellow:
\begin{flalign}
&f(x) = -1.25x^{2} + 1.5x&
\end{flalign}
Just make the property !important
in your css file so that background color doesnot change on mouse over.This worked for me.
Example:
.fbColor {
background-color: #3b5998 !important;
color: white;
}
Character issues like this are difficult to diagnose because information is easily lost through misinterpretation of characters via application bugs, misconfiguration, cut'n'paste, etc.
As I (and apparently others) see it, you've pasted three characters:
codepoint glyph escaped windows-1252 info
=======================================================================
U+00ef ï \u00ef ef, LATIN_1_SUPPLEMENT, LOWERCASE_LETTER
U+00bf ¿ \u00bf bf, LATIN_1_SUPPLEMENT, OTHER_PUNCTUATION
U+00bd ½ \u00bd bd, LATIN_1_SUPPLEMENT, OTHER_NUMBER
To identify the character, download and run the program from this page. Paste your character into the text field and select the glyph mode; paste the report into your question. It'll help people identify the problematic character.
fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.
You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.
Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Of course, it's then up to you to do what you need to do on the client side.
I would be thinking something like this:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
false == 0
and true = !false
i.e. anything that is not zero and can be converted to a boolean is not false
, thus it must be true
.
Some examples to clarify:
if(0) // false
if(1) // true
if(2) // true
if(0 == false) // true
if(0 == true) // false
if(1 == false) // false
if(1 == true) // true
if(2 == false) // false
if(2 == true) // false
cout << false // 0
cout << true // 1
true
evaluates to 1
, but any int
that is not false
(i.e. 0
) evaluates to true
but is not equal to true
since it isn't equal to 1
.
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
I have solved this problem with changing encoding in read.table argument from fileEncoding = "UTF-16" to fileEncoding = "UTF-8".
I had been facing the similar problem in Windows 7 and got the below problems while running the android-studio shortcut from my start programs menu for the first time.
Solution : Run As Administrator
The problem was due to the write permission in Windows C:
drive and the Access is Denied
message is displayed. Running the program as administrator downloads all the necessary components and now I can start Android Studio IDE.
Update:
These permission issues doesn't seem to exist in Android Studio latest versions(checked in 1.3.2 in Windows 10) and works without the "Run as administrator" commands. If you still have the problem with the old/latest versions then it might be your firewall and proxy issues. In that case check out the other answers.
Forgive me if someone already mentioned, but in the days of x86 when memory segmentation was still relevant, you may not get the same results from these two instructions:
LEA AX, DS:[0x1234]
and
LEA AX, CS:[0x1234]
Try this'
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script>
/* START --- scroll till anchor */
(function($) {
$.fn.goTo = function() {
var top_menu_height=$('#div_menu_header').height() + 5 ;
//alert ( 'top_menu_height is:' + top_menu_height );
$('html, body').animate({
scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
}, 500);
return this; // for chaining...
}
})(jQuery);
$(document).ready(function(){
var url = document.URL, idx = url.indexOf("#") ;
var hash = idx != -1 ? url.substring(idx+1) : "";
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var anchor_to_scroll_to = location.hash.replace('#','');
if ( anchor_to_scroll_to != '' ) {
anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
$(anchor_to_scroll_to).goTo();
}
});
});
/* STOP --- scroll till anchror */
keras.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=0,
write_graph=True, write_images=True)
This line creates a Callback Tensorboard object, you should capture that object and give it to the fit
function of your model.
tbCallBack = keras.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=0, write_graph=True, write_images=True)
...
model.fit(...inputs and parameters..., callbacks=[tbCallBack])
This way you gave your callback object to the function. It will be run during the training and will output files that can be used with tensorboard.
If you want to visualize the files created during training, run in your terminal
tensorboard --logdir path_to_current_dir/Graph
Hope this helps !
Alternatively to count columns, count the separators between columns. I find this to be a good balance of brevity and ease to remember. Of course, this won't work if your data include the column separator.
head -n1 myfile.txt | grep -o " " | wc -l
Uses head -n1
to grab the first line of the file.
Uses grep -o
to to count all the spaces, and output each space found on a new line. Uses wc -l
to count the number of lines.
I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.
Be careful of the accepted answer, it fails if the time_point is before the epoch.
This line of code:
std::size_t fractional_seconds = ms.count() % 1000;
will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).
DISCLAIMER: this answer is from Jul 2015 and uses Retrofit and OkHttp from that time.
Check this link for more info on Retrofit v2 and this one for the current OkHttp methods.
Okay, I got it working using Android Developers guide.
Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.
Here's the code that got things working (I've removed the try/catch blocks):
public static RestAdapter createAdapter(Context context) {
// loading CAs from an InputStream
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
Certificate ca;
try {
ca = cf.generateCertificate(cert);
} finally { cert.close(); }
// creating a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// creating a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// creating an SSLSocketFactory that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// creating an OkHttpClient that uses our SSLSocketFactory
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
// creating a RestAdapter that uses this custom client
return new RestAdapter.Builder()
.setEndpoint(UrlRepository.API_BASE)
.setClient(new OkClient(okHttpClient))
.build();
}
To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL)
to my RestAdapter creation commands and I could see it connecting and getting the response from the server.
All it took was my original .crt file saved in main/res/raw
.
The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl
. Generally, it is a .crt or .cert file, while the other is a .key file.
Afaik, the .crt file is your public key and the .key file is your private key.
As I can see, you already have a .cert file, which is the same, so try to use it.
PS: For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:
openssl x509 -outform der -in your-cert.pem -out your-cert.crt
PS²: For those that don't have any file at all, you can use the following command (bash) to extract the public key (aka certificate) from any server:
echo -n | openssl s_client -connect your.server.com:443 | \
sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/my_cert.crt
Just replace the your.server.com
and the port (if it is not standard HTTPS) and choose a valid path for your output file to be created.
You'll want something like this to increase the message size quotas, in the App.config or Web.config file:
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32"
maxArrayLength="200000000"
maxStringContentLength="200000000"/>
</binding>
</basicHttpBinding>
</bindings>
And use the binding name in your endpoint configuration e.g.
...
bindingConfiguration="basicHttp"
...
The justification for the values is simple, they are sufficiently large to accommodate most messages. You can tune that number to fit your needs. The low default value is basically there to prevent DOS type attacks. Making it 20000000 would allow for a distributed DOS attack to be effective, the default size of 64k would require a very large number of clients to overpower most servers these days.
While File.ReadAllLines()
is one of the simplest ways to read a file, it is also one of the slowest.
If you're just wanting to read lines in a file without doing much, according to these benchmarks, the fastest way to read a file is the age old method of:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do minimal amount of work here
}
}
However, if you have to do a lot with each line, then this article concludes that the best way is the following (and it's faster to pre-allocate a string[] if you know how many lines you're going to read) :
AllLines = new string[MAX]; //only allocate memory here
using (StreamReader sr = File.OpenText(fileName))
{
int x = 0;
while (!sr.EndOfStream)
{
AllLines[x] = sr.ReadLine();
x += 1;
}
} //Finished. Close the file
//Now parallel process each line in the file
Parallel.For(0, AllLines.Length, x =>
{
DoYourStuff(AllLines[x]); //do your work here
});
There is already a correct answer from Adam, but you have another option to refactor your code:
if (Age.GetValueOrDefault() == 0)
{
// it's null or 0
}
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
Since Ruby 2.5.0
you can use Hash#transform_keys
or Hash#transform_keys!
.
{'a' => 1, 'b' => 2}.transform_keys(&:to_sym) #=> {:a => 1, :b => 2}
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
I'm partial to C#. I ran the following using linqpad. But it could just as easily be compiled with csc and ran through the called from the command line.
Don't forget to add excel packages to namespace.
void Main()
{
var oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try{
var WB = oExcelApp.ActiveWorkbook;
var WS = (Worksheet)WB.ActiveSheet;
((string)((Range)WS.Cells[1,1]).Value).Dump("Cell Value"); //cel A1 val
oExcelApp.Run("test_macro_name").Dump("macro");
}
finally{
if(oExcelApp != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcelApp);
oExcelApp = null;
}
}
Alright I had some issues getting this to work using a self signed cert for testing so I am going to copy my setup that worked for me. If your not using a self signed cert you probably wont have these issues, hopefully!
To start off depending on your browser Firefox or Chrome you may have different issues and I'll explain in a minute.
First the Setup:
Client
// May need to load the client script from a Absolute Path
<script src="https://www.YOURDOMAIN.com/node/node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var options = {
rememberUpgrade:true,
transports: ['websocket'],
secure:true,
rejectUnauthorized: false
}
var socket = io.connect('https://www.YOURDOMAIN.com:PORT', options);
// Rest of your code here
</script>
Server
var fs = require('fs');
var options = {
key: fs.readFileSync('/path/to/your/file.pem'),
cert: fs.readFileSync('/path/to/your/file.crt'),
};
var origins = 'https://www.YOURDOMAIN.com:*';
var app = require('https').createServer(options,function(req,res){
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', 'https://www.YOURDOMAIN.com:*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
if ( req.method === 'OPTIONS' || req.method === 'GET' ) {
res.writeHead(200);
res.end();
return;
}
});
var io = require('socket.io')(app);
app.listen(PORT);
For development the options used on the client side are ok in production you would want the option:
rejectUnauthorized: false
You would more than likely want set to "true"
Next thing is if its a self signed cert you will need to vist your server in a separate page/tab and accept the cert or import it into your browser.
For Firefox I kept getting the error
MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT
The solution for me was to add the following options and accepting the cert in a different page/tab.
{
rejectUnauthorized: false
}
In Chrome I had to open another page and accept the cert but after that everything worked fine with out having to add any options.
Hope this helps.
References:
I have no affiliation with this program, but if you are looking to open any of this in the finder SimPholders makes it incredibly easy.
please try this flower:
/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');
true
while running:
lenli = len(li)
for i, elem in enumerate(li):
thiselem = elem
nextelem = li[(i+1)%lenli]
Just use ojdb6.jar and will fix all such issues.
For maven based applications:
Download and copy ojdbc6.jar to a directory in your local machine
From the location where you have copied your jar install the ojdbc6.jar in your local .M2 Repo by issuing below command C:\SRK\Softwares\Libraries>mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true
Add the below in your project pom.xml as ojdbc6.jar dependency
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
PS: The issue might be due to uses of @Lob annotation in JPA for storing large objects specifically in oracle db columns. Upgrading to 11.2.0.3 (ojdbc6.jar) can resolve the issue.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
$data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAADICAYAAAAQj4UaAAAcNUlEQVR4nO3dwW4cR37H8d8jzBsMXyACX4Aw7yawPBhIsDqs3kAEcolPGuQinbI6BMneLCRZ57AwJARLW8hhRcU8xA6QoaVsHGC9kVZrIVl7LYkJVootyf8cukcckjNV1T3VU1Xd3w/wBwSSmq4ecrrr3/WvKgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgKhsLNkHdYxTtwYAAABAb9mWZC8lszq+JQkBAAAA0AHblOz5XPIxi9upWwYAAACgV+wdyV4tSD6sTkpGqVsIAAAAoBfsnSWJx3xcS91KAAAAAMWzTcleByQgr5gLAgAAAGAFtiXZ/wUkH7M4TN1iAAAAAEWycb3CVWjyMYvt1C0HAAAAUBz7tEXyYZJNU7ccAAAAQFFsu2XyMYt3U58BAAAAgGLY0YoJyGsmpAMAAAAIYO86EotfSvZ9YBJyM/WZAAAAAMiajT1L7l70JCjz8cWa2z6S7HIdbIoIAAAA5M9uhq1wFVqitbZ2j6rJ7/MT4UlCAAAAgMzZbU9SsVH/3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IrpdHpECVbP1EnI3nQ6nRAEQRAEQRBERrE3JfkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhuv/ATiSIPBj5ipCAAAAAElFTkSuQmCC';
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'images/'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = 'images/'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.
Easy & Simple solution: I solved this problem (NetBeans) by exporting the original project into zip file, deleting the original project directory and importing the project back from the zip file.
If you are using React Router, use this:
<Link to="/files/myfile.pdf" target="_blank" download>Download</Link>
Where /files/myfile.pdf
is inside your public
folder.
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
Shift + Alt + J will help you add author name in existing file.
To add author name automatically,
go to Preferences --> java --> Code Style --> Code Templates
in case you don't find above option in new versions of Eclipse - install it from https://marketplace.eclipse.org/content/jautodoc
[Swift Implementation]
Universal way of loading view from xib:
Example:
let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)
Implementation:
extension Bundle {
static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
return view
}
fatalError("Could not load view with type " + String(describing: type))
}
}
I don't know why but for me text-align:center;
only works with:
text-align: grid;
OR
display: inline-grid;
I checked and no one style is overriding.
My structure:
<ul>
<li>
<a>ElementToCenter</a>
</li>
</ul>
Assuming doc
is your instance of org.w3c.dom.Document
:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
You could use the timeout
setting in the ajax options like this:
$.ajax({
url: "test.html",
timeout: 3000,
error: function(){
//do something
},
success: function(){
//do something
}
});
Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/
Remember that when a timeout occurs, the error
handler is triggered and not the success
handler :)
main()
has it's own thread and stack variables. either allocate memory for 'args' in the heap or make it global:
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
Then of course change the references from args->arg1
to args.arg1
etc..
You should not be repeating the string
part when sending parameters.
int wordLength = wordLengthFunction(word); //you do not put string word here.
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
You have 2 options to fix this...
Remove previous container using that name, with the command docker rm $(docker ps -aq --filter name=myContainerName)
OR
--name registry-v1
to something like --name myAnotherContainerName
You are getting this error because that container name ( i.e registry-v1
) was used by another container in the past...even though that container may have exited i.e (currently not in use).
df.dropna(subset=['columnName1', 'columnName2'])
This uses the function and waits for it to complete.
http://jsfiddle.net/SN2t6/118/
function getMeta(url){
var r = $.Deferred();
$('<img/>').attr('src', url).load(function(){
var s = {w:this.width, h:this.height};
r.resolve(s)
});
return r;
}
getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
alert(test.w + ' ' + test.h);
});
Prepared statement is more secure. It will convert a parameter to the specified type.
For example stmt.setString(1, user);
will convert the user
parameter to a String.
Suppose that the parameter contains a SQL string containing an executable command: using a prepared statement will not allow that.
It adds metacharacter (a.k.a. auto conversion) to that.
This makes it is more safe.
I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
According to Alex McMillan's solution, I have the following adaptation.
My own environment: React 16.8+, next v9+
// add a custom component named Script
// hooks/Script.js
import { useEffect } from 'react'
const useScript = (url, async) => {
useEffect(() => {
const script = document.createElement('script')
script.src = url
script.async = (typeof async === 'undefined' ? true : async )
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [url])
}
export default function Script({ src, async=true}) {
useScript(src, async)
return null // Return null is necessary for the moment.
}
// Use the custom compoennt, just import it and substitute the old lower case <script>
tag with the custom camel case <Script>
tag would suffice.
// index.js
import Script from "../hooks/Script";
<Fragment>
{/* Google Map */}
<div ref={el => this.el = el} className="gmap"></div>
{/* Old html script */}
{/*<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>*/}
{/* new custom Script component */}
<Script src='http://maps.google.com/maps/api/js' async={false} />
</Fragment>
There is a way to perform URL validation in strict accordance to standards in Java without resorting to third-party libraries:
boolean isValidURL(String url) {
try {
new URI(url).parseServerAuthority();
return true;
} catch (URISyntaxException e) {
return false;
}
}
The constructor of URI
checks that url
is a valid URI, and the call to parseServerAuthority
ensures that it is a URL (absolute or relative) and not a URN.
if (File.Exists(fpath))
{
var data = File.ReadLines(fpath);
Console.WriteLine(data.ToArray()[14]);
}
To find a listener on a port, do this:
netstat -tln
You should see a line that looks like this if mysql is indeed listening on that port.
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
Port 3306 is MySql's default port.
To connect, you just have to use whatever client you require, such as the basic mysql client.
mysql -h localhost -u user database
Or a url that is interpreted by your library code.
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
There's another reason that this can be thrown, even if you're not using dynamic/ExpandoObject. If you are doing a loop, like this:
@foreach (var folder in ViewBag.RootFolder.ChildFolders.ToList())
{
@Html.Partial("ContentFolderTreeViewItems", folder)
}
In that case, the "var" instead of the type declaration will throw the same error, despite the fact that RootFolder is of type "Folder. By changing the var to the actual type, the problem goes away.
@foreach (ContentFolder folder in ViewBag.RootFolder.ChildFolders.ToList())
{
@Html.Partial("ContentFolderTreeViewItems", folder)
}
The variable selectedHero
is null
in the template so you cannot bind selectedHero.name
as is. You need to use the elvis operator ?.
for this case:
<input [ngModel]="selectedHero?.name" (ngModelChange)="selectedHero.name = $event" />
The separation of the [(ngModel)]
into [ngModel]
and (ngModelChange)
is also needed because you can't assign to an expression that uses the elvis operator.
I also think you mean to use:
<h2>{{selectedHero?.name}} details!</h2>
instead of:
<h2>{{hero.name}} details!</h2>
You can determine that the connection is lost by making failed XHR requests.
The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.
Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.
Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.
Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping
google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.
What worked for me was upgrading pandas to latest version:
From Command Line do:
conda update pandas
Is not nice to define textbox width without using CSS, be warned ;-)
<input type="text" name="d" value="4" size="4" />
In my case, the problem was JS-CSS-HTML Formatter extension installed after january update. The default indent_char
property is space. I uninstalled it and the weird behavior stops.
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.
Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
use below code, as this is 100% growth rate in case of 0 to any number :
IFERROR((NEW-OLD)/OLD,100%)
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
I think you want the selected item of the spinner when button is clicked..
Try getSelectedItem():
spinner.getSelectedItem()
An update for Windows 10 Ubuntu Application via Subsystem (also works on standard Ubuntu):
You might have problems finding the package. If you do, never fear! PPA is here!
sudo add-apt-repository ppa:boost-latest/ppa
sudo apt-get update
Then run:
sudo apt-get install libboost-all-dev
You can also use Windows PowerShell with the following command:
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
[System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
}
Make sure to check that the source does not exist before calling CreateEventSource, otherwise it will throw an exception.
For more info:
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
For some reasons, @ChintanSoni's answer didn't worked. I tried deleting the build
folder manually but couldn't delete some files since they were being used by some process. Cleaning and re-building the project didn't help so I opened task manager
, selected JAVA(TM) Platform SE binary
and pressed on 'End task`.
Then I tried to run the project once again and it started compiling fine.
Messagebox is for windows only. You have to use Javascript
Alert('dd');
If the anonymous type causes trouble for you, you can create a simple data class:
public class PermissionsAndPages
{
public ObjectPermissions Permissions {get;set}
public Pages Pages {get;set}
}
and then in your query:
select new PermissionsAndPages { Permissions = op, Page = pg };
Then you can pass this around:
return queryResult.SingleOrDefault(); // as PermissionsAndPages
In Swift 5, use in the below:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure)
// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
Singleton.shared().printDate()
}
// default time gap is second, you can reduce it
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// just do it!
}
For printing an array value if you don't have the key value par, then use the below code -
<div>
{my_arr.map(item => <div>{item} </div> )}
</div>
Best practice is to open the source file (with a false visible status if you don't want to be bother) read your data and then we close it.
A working and clean code is avalaible on the link below :
http://vba-useful.blogspot.fr/2013/12/how-do-i-retrieve-data-from-another.html
1.
if(1 == @$manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
2.
if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
3.
if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.
import java.util.Random;
If you want to test it out try something like this.
Random rn = new Random();
for(int i =0; i < 100; i++)
{
int answer = rn.nextInt(10) + 1;
System.out.println(answer);
}
Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).
I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.
<wsdl:service name="serviceMethodName_2">
<wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
<soap:address location="http://new_end_point_adress"/>
</wsdl:port>
</wsdl:service>
This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).
Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:
fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');
The second param is an optional replacer function which you don't need in this case so null
works.
The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.
Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).
Switched to a 200x200 size image, worked perfectly.
https://developers.facebook.com/tools/debug/og/object?q=drift.team
Its very simple. I had implemented using -webkit-appearance: slider-vertical
, It worked in chorme, Firefox, Edge
<input type="range">
input[type=range]{
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
width: 50px;
height: 200px;
padding: 0 24px;
outline: none;
background:transparent;
}
Use this code where str is your JSON string:
NSError *err = nil;
NSArray *arr =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
// do something using dictionary
}
It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:
class array2D {
std::vector<double> data;
size_t columns;
public:
array2D(size_t x, size_t y) : columns(x), data(x*y) {}
double &operator(size_t x, size_t y) {
return data[y*columns+x];
}
};
Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.
In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.
If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:
11 12 13
23 34 56 78
You might want to use a std::vector<std::vector<double> >
instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.
std::vector<std::vector<double> > numbers;
std::string temp;
while (std::getline(infile, temp)) {
std::istringstream buffer(temp);
std::vector<double> line((std::istream_iterator<double>(buffer)),
std::istream_iterator<double>());
numbers.push_back(line);
}
...or, with a modern (C++11) compiler, you can use brackets for line
's initialization:
std::vector<double> line{std::istream_iterator<double>(buffer),
std::istream_iterator<double>()};
Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4
<div id="videoDiv">
<video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
</div>
<!--End videoDiv-->
Not an ideal solution but worked for me.
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
The simplest example I can think of in JavaScript is the setTimeout()
function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs
library to read a file. The fs
module exposes two unique API functions: readFile
and readFileSync
.
The readFile
function is asynchronous while readFileSync
is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile
and readFileSync
instead of readFile
and readFileAsync
. Here is an example of using both functions.
Synchronous:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txt
are read into memory and stored in the variable data
. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
Asynchronous (with callback):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments err
and data
. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err
has a value before you do anything else. If so, stop execution of the callback and log the error.
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch
block.
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch
. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
I wrote a simple test for all the above.
def eq(a, b)
puts "#{[a, '==', b]} : #{a == b}"
puts "#{[a, '===', b]} : #{a === b}"
puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end
eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)
Running npm init -y
makes your package.json
with all the defaults.
You can then change package.json
accordingly
This saves time many a times by preventing pressing enter
on every command in npm init
This is all because you are not in the desired directory. You need to first get into the desired directory. Mine was angular-phonecat directory. So I typed in cd angular-phonecat
and then npm install
.
Just use:
git reset HEAD <filename>
This unstages the file and keeps the changes you did to it, so you can, in turn, change branches if you wanted and git add
those files to another branch instead. All changes are kept.
Using Excel 2010 ? Try
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
If you guys are looking for a solution for Android, you can use the following code to get the epoch seconds from the timestamp string.
public static long timestampToEpochSeconds(String srcTimestamp) {
long epoch = 0;
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Instant instant = Instant.parse(srcTimestamp);
epoch = instant.getEpochSecond();
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse(srcTimestamp);
if (date != null) {
epoch = date.getTime() / 1000;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return epoch;
}
Sample input: 2019-10-15T05:51:31.537979Z
Sample output: 1571128673
You can now use json.net. Just go on Nuget and install it.
And you can do something like this:
public bool Equals(SamplesItem sampleToCompare)
{
string myself = JsonConvert.SerializeObject(this);
string other = JsonConvert.SerializeObject(sampleToCompare);
return myself == other;
}
You could perhaps make a extension method for object if you wanted to get fancier. Please note this only compares the public properties. And if you wanted to ignore a public property when you do the comparison you could use the [JsonIgnore] attribute.
You should not place an using
directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
This is simple, short, and effective. No additional HTML is necessary.
.pvw-title { color: transparent; }
.pvw-title:after {
content: "New Text To Replace Old";
color: black; /* set color to original text color */
margin-left: -30px;
/* margin-left equals length of text we're replacing */
}
I had to do this for replacing link text, other than home, for WooCommerce breadcrumbs
body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"] {
color: transparent;
&:after {
content: "Store";
color: grey;
margin-left: -30px;
}
}
body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"] {
color: transparent;
}
body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"]&:after {
content: "Store";
color: @child-color-grey;
margin-left: -30px;
}
var noHtml = Regex.Replace(inputHTML, @"<[^>]*(>|$)| |‌|»|«", string.Empty).Trim();
I had the same issue and resolved it by adding the /bin
directory location to the PATH Environment Variable.
Search for the file location where Git was installed, mine is C:\Users\(My UserName)\AppData\Local\GitHub
. It may also be C:\Program Files (x86)\Git
Once you have the location of Git you should see a /bin
sub-folder. It may be in a PortableGit folder (mine is
PortableGit_015aa71ef18c047ce8509ffb2f9e4bb0e3e73f13
). Copy this path.
Go to Control Panel > System > System Protection > Advanced > Environment Variables
Choose PATH, click edit and paste the bin path there. If there are already any values in your PATH paste your Git path at the end separated with a semi-colon.
Now you can access Git command from CMD.
There is a good reason to consider using accessors is there is no property inheritance. See next example:
public class TestPropertyOverride {
public static class A {
public int i = 0;
public void add() {
i++;
}
public int getI() {
return i;
}
}
public static class B extends A {
public int i = 2;
@Override
public void add() {
i = i + 2;
}
@Override
public int getI() {
return i;
}
}
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
a.add();
System.out.println(a.i);
System.out.println(a.getI());
}
}
Output:
0
0
4
There is one case, that is not mentioned above:
int res = 1;
while (res != 0) {
res *= 2;
}
System.out.println(res);
will produce:
0
This case was discussed here: Integer overflow produces Zero.
Quite simply as follows:
/**
* @author The Elite Gentleman
*
*/
public enum MyEnum {
ONE("one"), TWO("two")
;
private final String value;
private MyEnum(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return getValue();
}
}
For more info, visit Enum Types from Oracle Java Tutorials. Also, bear in mind that enums have private constructor.
Update, since you've updated your post, I've changed my value from an int
to a String
.
Related: Java String enum.
To check if a lateinit var
were initialised or not use a .isInitialized
on the reference to that property:
if (foo::bar.isInitialized) {
println(foo.bar)
}
This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.
Try Visual Studio ? menu Tools ? Options ? ReSharper, Suspend button and Resume again (no need to close the window). This works in my case.
I was having the same problem running a single-node pseudo-distributed instance. Couldn't figure out how to solve it, but a quick workaround is to manually start a DataNode with
hadoop-x.x.x/bin/hadoop datanode
For me the following worked:
(1) First fetch all changes:
$ git fetch --all
(2) Then reset the master:
$ git reset --hard origin/master
(3) Pull/update:
$ git pull
This is an addition to Josh's answer.
You can also keep the values of other variables while filtering out duplicated rows in data.table
Example:
library(data.table)
#create data table
dt <- data.table(
V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
V3=c(1),
V4=c(2) )
> dt
# V1 V2 V3 V4
# A B 1 2
# A C 1 2
# A D 1 2
# A B 1 2
# B A 1 2
# C D 1 2
# C D 1 2
# E F 1 2
# G G 1 2
# A B 1 2
# set the key to all columns
setkey(dt)
# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] )
# V1 V2 V3 V4
# A B 1 2
# A C 1 2
# A D 1 2
# B A 1 2
# C D 1 2
# E F 1 2
# G G 1 2
Alert: If there are different combinations of values in the other variables, then your result will be
unique combination of V1 and V2
Simple and easy way to detect button event and perform some action
class youCell: UITableViewCell
{
var yourobj : (() -> Void)? = nil
//You can pass any kind data also.
//var user: ((String?) -> Void)? = nil
override func awakeFromNib()
{
super.awakeFromNib()
}
@IBAction func btnAction(sender: UIButton)
{
if let btnAction = self.yourobj
{
btnAction()
// user!("pass string")
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
cell?.selectionStyle = UITableViewCellSelectionStyle.None
cell!. yourobj =
{
//Do whatever you want to do when the button is tapped here
self.view.addSubview(self.someotherView)
}
cell.user = { string in
print(string)
}
return cell
}
You want a .jardesc
file. They do not kick off automatically, but it's within 2 clicks.
Export > Java > JAR file
Next
.jardesc
fileNow, all you have to do is right click on your .jardesc
file and choose Create JAR
and it will export it in the same spot.
The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.
If using the above solution of two <VirtualHost *:80>
blocks with different ServerName
s...
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
</VirtualHost>
... then you must set NameVirtualHost On
as well.
If you don't do this, Apache doesn't allow itself to use the different ServerName
s to distinguish the blocks, so you get this error message:
[warn] _default_ VirtualHost overlap on port 80, the first has precedence
...and either no redirection happens, or you have an infinite redirection loop, depending on which block you put first.
This type is defined in the C header <stdint.h>
which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.
In the meantime, you could probably fake up your own version of the header by adding typedef
s that map Microsoft's custom integer types to the types expected by C. For example:
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */
Hope this helps!
I needed something to just list the calling classes/methods (working on a Magento project).
While debug_backtrace
provides tons of useful information, the amount of information it spewed out for the Magento installation was overwhelming (over 82,000 lines!) Since I was only concerned with the calling function and class, I worked this little solution up:
$callers = debug_backtrace();
foreach( $callers as $call ) {
echo "<br>" . $call['class'] . '->' . $call['function'];
}
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
Before C++20 we need to pass lambda as argument to set constructor
Make comparator as usual boolean function
bool cmp(int a, int b) {
return ...;
}
Then use it, either this way:
std::set<int, decltype(cmp)*> s(cmp);
or this way:
std::set<int, decltype(&cmp)> s(&cmp);
()
operatorstruct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
Take boolean function
bool cmp(int a, int b) {
return ...;
}
And make struct from it using std::integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
Finally, use the struct as comparator
std::set<X, Cmp> set;
String StringBuffer
Immutable Mutable
String s=new String("karthik"); StringBuffer sb=new StringBuffer("karthik")
s.concat("reddy"); sb.append("reddy");
System.out.println(s); System.out.println(sb);
O/P:karthik O/P:karthikreddy
--->once we created a String object ---->once we created a StringBuffer object
we can't perform any changes in the existing we can perform any changes in the existing
object.If we are trying to perform any object.It is nothing but mutablity of
changes with those changes a new object of a StrongBuffer object
will be created.It is nothing but Immutability
of a String object
Use String--->If you require immutabilty
Use StringBuffer---->If you require mutable + threadsafety
Use StringBuilder--->If you require mutable + with out threadsafety
String s=new String("karthik");
--->here 2 objects will be created one is heap and the other is in stringconstantpool(scp) and s is always pointing to heap object
String s="karthik";
--->In this case only one object will be created in scp and s is always pointing to that object only
You can use the start (^
) and end ($
) of line indicators:
^[0-9]{2}$
Some language also have functions that allows you to match against an entire string, where-as you were using a find
function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^
and $
will be redundant.
On Ganymede, check the configuration of the Problem view:
('Configure content') It can be set on 'any element in the same project' and you might currently select an element from the project.
Or it might be set on a working set, and this working set has been modified
Make sure that 'Match any configuration' is selected.
During debug, break on all exceptions thrown. Debug->Exceptions
Check all 'Thrown' exceptions. F5, the code will stop on the offending line.
2018: CSS3
div{
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
This is even shorter. For more information see this: CSS: Centering Things
play services, firebase, gradle plugin latest version combination that worked for me.
try app module build.gradle
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "my package name"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true
publishNonDefault true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
} }
dependencies {
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-vision:15.0.2'
implementation 'com.google.android.gms:play-services-analytics:16.0.1'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-iid:17.0.0'
implementation 'com.google.firebase:firebase-messaging:17.3.0'
implementation 'com.google.firebase:firebase-crash:16.0.1'
}
apply plugin: 'com.google.gms.google-services'
And project level build.gradle like this
buildscript {
repositories {
maven { url 'https://maven.google.com' }
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
classpath 'com.google.gms:google-services:4.1.0'
}
}
You can disable the check (if you're really sure you know what you're doing) by using the --force
option to git push
.
Types are dependent to your initialization:
var IsLoggedIn1 = "true"; //string
var IsLoggedIn2 = 1; //integer
var IsLoggedIn3 = true; //bool
But take a look at this example:
var IsLoggedIn1 = "true"; //string
IsLoggedIn1 = true; //now your variable is a boolean
Your variables' type depends on the assigned value in JavaScript.
realpath <path to the symlink file>
should do the trick.
If you added to your web.config and it still shows message, then you need to close your project and reopen it, now it will exist and @Styles.Render("") and @Scripts.Render() will work fine.
A simple 4on4 pasting function that works-
def paste(background,foreground,pos=(0,0)):
#get position and crop pasting area if needed
x = pos[0]
y = pos[1]
bgWidth = background.shape[0]
bgHeight = background.shape[1]
frWidth = foreground.shape[0]
frHeight = foreground.shape[1]
width = bgWidth-x
height = bgHeight-y
if frWidth<width:
width = frWidth
if frHeight<height:
height = frHeight
# normalize alpha channels from 0-255 to 0-1
alpha_background = background[x:x+width,y:y+height,3] / 255.0
alpha_foreground = foreground[:width,:height,3] / 255.0
# set adjusted colors
for color in range(0, 3):
fr = alpha_foreground * foreground[:width,:height,color]
bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
background[x:x+width,y:y+height,color] = fr+bg
# set adjusted alpha and denormalize back to 0-255
background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
return background
Is 'UTC' a valid timezone identifier on your system?
<?php
if (date_default_timezone_set('UTC')){
echo "UTC is a valid time zone";
}else{
echo "The system doesn't know WTFUTC. Maybe try updating tzinfo with your package manager?";
}
In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:
var query = from e in doc.Elements("whatever")
group e by new { id = e.Key, val = e.Value } into g
select new { id = g.Key.id, val = g.Key.val, count = g.Count() };
You can't download the file directly via ajax.
You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe
and set the URL of the source of that iframe
dynamically. This way you can download the file without refreshing the page.
Here is the code
$.ajax({
url : "yourURL.php",
type : "GET",
success : function(data) {
$("#iframeID").attr('src', 'downloadFileURL');
}
});
You can do like this
var filter = {_x000D_
address: 'England',_x000D_
name: 'Mark'_x000D_
};_x000D_
var users = [{_x000D_
name: 'John',_x000D_
email: '[email protected]',_x000D_
age: 25,_x000D_
address: 'USA'_x000D_
},_x000D_
{_x000D_
name: 'Tom',_x000D_
email: '[email protected]',_x000D_
age: 35,_x000D_
address: 'England'_x000D_
},_x000D_
{_x000D_
name: 'Mark',_x000D_
email: '[email protected]',_x000D_
age: 28,_x000D_
address: 'England'_x000D_
}_x000D_
];_x000D_
_x000D_
_x000D_
users= users.filter(function(item) {_x000D_
for (var key in filter) {_x000D_
if (item[key] === undefined || item[key] != filter[key])_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
});_x000D_
_x000D_
console.log(users)
_x000D_
For PyCharm 5 (or 2016.1), you can:
The title attribute also works well with other html elements, for example a link...
<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>
First make sure that DataTable is not null and than check for the row count
if(dt!=null)
{
if(dt.Rows.Count>0)
{
//do your code
}
}
Make a function which will not return null instead return an empty array you can go through below code to understand.
public static String[] getJavaFileNameList(File inputDir) {
String[] files = inputDir.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isFile() && (name.endsWith("java"));
}
});
return files == null ? new String[0] : files;
}
You can try this line of code:
pdDataFrame = pd.DataFrame([np.nan] * 7)
This will create a pandas dataframe of size 7 with NaN of type float:
if you print pdDataFrame
the output will be:
0
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
Also the output for pdDataFrame.dtypes
is:
0 float64
dtype: object
JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.
NamedParameterJDBCTemplate supports named parameters, you can use them like that:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("name", name);
paramSource.addValue("city", city);
jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern
// filename: MyComponent.js
function MyComponent() {
return <div />;
}
as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here
You can do this conversion with the OpenSSL library
Windows binaries can be found here:
http://www.slproweb.com/products/Win32OpenSSL.html
Once you have the library installed, the command you need to issue is:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
If the week number is in A1
and the year in A2
, you can try:
A1*7+DATE(A2,1,1)
If a function does not return anything, e.g.:
def test():
pass
it has an implicit return value of None
.
Thus, as your pick*
methods do not return anything, e.g.:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
the lines that call them, e.g.:
word = pickEasy()
set word
to None
, so wordInput
in getInput
is None
. This means that:
if guess in wordInput:
is the equivalent of:
if guess in None:
and None
is an instance of NoneType
which does not provide iterator/iteration functionality, so you get that type error.
The fix is to add the return type:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
If you don't mind executing other's code, here's mine:
Note: There is lot of extra code you may want to remove [added for better clarificaiton and demonstration how it works]
Note: Python naming conventions were used for method names and variable names instead of camelCase.
Working procedure:
Code:
import threading
import queue
class SingleThread(threading.Thread):
def __init__(self, name, work_queue, lock, exit_flag, results):
threading.Thread.__init__(self)
self.name = name
self.work_queue = work_queue
self.lock = lock
self.exit_flag = exit_flag
self.results = results
def run(self):
# print("Coming %s with parameters %s", self.name, self.exit_flag)
while not self.exit_flag:
# print(self.exit_flag)
self.lock.acquire()
if not self.work_queue.empty():
work = self.work_queue.get()
module, operation, args, kwargs = work.module, work.operation, work.args, work.kwargs
self.lock.release()
print("Processing : " + operation + " with parameters " + str(args) + " and " + str(kwargs) + " by " + self.name + "\n")
# module = __import__(module_name)
result = str(getattr(module, operation)(*args, **kwargs))
print("Result : " + result + " for operation " + operation + " and input " + str(args) + " " + str(kwargs))
self.results.append(result)
else:
self.lock.release()
# process_work_queue(self.work_queue)
class MultiThread:
def __init__(self, no_of_threads):
self.exit_flag = bool_instance()
self.queue_lock = threading.Lock()
self.threads = []
self.work_queue = queue.Queue()
self.results = []
for index in range(0, no_of_threads):
thread = SingleThread("Thread" + str(index+1), self.work_queue, self.queue_lock, self.exit_flag, self.results)
thread.start()
self.threads.append(thread)
def add_work(self, work):
self.queue_lock.acquire()
self.work_queue._put(work)
self.queue_lock.release()
def destroy(self):
self.exit_flag.value = True
for thread in self.threads:
thread.join()
def get_results(self):
return self.results
class Work:
def __init__(self, module, operation, args, kwargs={}):
self.module = module
self.operation = operation
self.args = args
self.kwargs = kwargs
class SimpleOperations:
def sum(self, *args):
return sum([int(arg) for arg in args])
@staticmethod
def mul(a, b, c=0):
return int(a) * int(b) + int(c)
class bool_instance:
def __init__(self, value=False):
self.value = value
def __setattr__(self, key, value):
if key != "value":
raise AttributeError("Only value can be set!")
if not isinstance(value, bool):
raise AttributeError("Only True/False can be set!")
self.__dict__[key] = value
# super.__setattr__(key, bool(value))
def __bool__(self):
return self.value
if __name__ == "__main__":
multi_thread = MultiThread(5)
multi_thread.add_work(Work(SimpleOperations(), "mul", [2, 3], {"c":4}))
while True:
data_input = input()
if data_input == "":
pass
elif data_input == "break":
break
else:
work = data_input.split()
multi_thread.add_work(Work(SimpleOperations(), work[0], work[1:], {}))
multi_thread.destroy()
print(multi_thread.get_results())
This post is not going to answer to Coppermill, because he have been answered long time ago. My post will be helpful for who will seeking for solution like this. First of all , I have to say " WDuffy's solution is totally correct" and it works fine, but my solution (not actually mine) will be used in other elements and it makes the presentation layer more independent from controller (because your controller depend on "value" which is used for showing label of the button, this feature is important for other languages.).
Here is my solution, give them different names:
<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>
And you must specify the names of buttons as arguments in the action like below:
public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
if (buttonSave!= null)
{
//save is pressed
}
if (buttonProcess!= null)
{
//Process is pressed
}
if (buttonCancel!= null)
{
//Cancel is pressed
}
}
when user submits the page using one of the buttons, only one of the arguments will have value. I guess this will be helpful for others.
Update
This answer is quite old and I actually reconsider my opinion . maybe above solution is good for situation which passing parameter to model's properties. don't bother yourselves and take best solution for your project.
First you have to check login existence using syslogins view:
IF NOT EXISTS
(SELECT name
FROM master.sys.server_principals
WHERE name = 'YourLoginName')
BEGIN
CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END
Then you have to check your database existence:
USE your_dbname
IF NOT EXISTS
(SELECT name
FROM sys.database_principals
WHERE name = 'your_dbname')
BEGIN
CREATE USER [your_dbname] FOR LOGIN [YourLoginName]
END
If you use the ctrlKey
property, you don't need to maintain state.
$(document).keydown(function(event) {
// Ctrl+C or Cmd+C pressed?
if ((event.ctrlKey || event.metaKey) && event.keyCode == 67) {
// Do stuff.
}
// Ctrl+V or Cmd+V pressed?
if ((event.ctrlKey || event.metaKey) && event.keyCode == 86) {
// Do stuff.
}
// Ctrl+X or Cmd+X pressed?
if ((event.ctrlKey || event.metaKey) && event.keyCode == 88) {
// Do stuff.
}
}
String str = "www.anywebsite.com/folder/subfolder/directory";
int index = str.lastIndexOf('/');
String lastString = str.substring(index +1);
Now lastString
has the value "directory"
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests
so PHP code like:
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
will need replace to PHP code
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
//if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
May be some body reply how this options connected with "Curl error: Operation timed out after .."
If you're open to a Perl solution...
perl -lane 'print join " ",@F[1..$#F,0]' file
is a simple solution with an input/output separator of one space, which produces:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
This next one is slightly more complex
perl -F` ` -lane 'print join " ",@F[1..$#F,0]' file
and assumes that the input/output separator is two spaces:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-l
removes newlines before processing, and adds them back in afterwards
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-F
autosplit modifier, in this example splits on ' ' (two spaces)
-e
execute the following perl code
@F
is the array of words in each line, indexed starting with 0
$#F
is the number of words in @F
@F[1..$#F]
is an array slice of element 1 through the last element
@F[1..$#F,0]
is an array slice of element 1 through the last element plus element 0
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Simplest way for me:
from urlextract import URLExtract
from requests import get
url = "sample.com/samplepage/"
req = requests.get(url)
text = req.text
# or if you already have the html source:
# text = "This is html for ex <a href='http://google.com/'>Google</a> <a href='http://yahoo.com/'>Yahoo</a>"
text = text.replace(' ', '').replace('=','')
extractor = URLExtract()
print(extractor.find_urls(text))
output:
['http://google.com/', 'http://yahoo.com/']
With Ubuntu, I had the same problem. I solved it by changing file /dev/kvm
permission to 777:
sudo chmod 777 /dev/kvm
From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:
var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));
alert( dom_nodes.find('input').val() );
var string = '<div><input type="text" value="val" /></div>';
$('<div/>').html(string).contents();
$('<div/>')
is a fake <div>
that does not exist in the DOM$('<div/>').html(string)
appends string
within that fake <div>
as children.contents()
retrieves the children of that fake <div>
as a jQuery object.find()
work then try this:var string = '<div><input type="text" value="val" /></div>',
object = $('<div/>').html(string).contents();
alert( object.find('input').val() );
If you are using VS Code, you can rename the .ts, .html, .css/.scss, .spec.ts
files and the IDE will take care of the imports for you. Therefore there will be no complaints from the files that import files from your component (such as app.module.ts
). However, you will still have to rename the component name everywhere it is being used.
One can use the getmonth and getday methods to get only the date.
Here I attach my solution:
var fullDate = new Date(); console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
adding overflow:visible !important;
to the body element worked for me.
1) Don't use gets
! You're introducing a buffer-overflow vulnerability. Use fgets(..., stdin)
instead.
2) In strToLower
you're returning a char
instead of a char
-array. Either return char*
as Autopulated suggested, or just return void
since you're modifying the input anyway. As a result, just write
strToLower(cString1);
strToLower(cString2);
strcasecmp
(Linux & Mac) or stricmp
(Windows).I haven't done anything with rank, but I discovered this today with row_number().
select item, name, sold, row_number() over(partition by item order by sold) as row from table_name
This will result in some repeating row numbers since in my case each name holds all items. Each item will be ordered by how many were sold.
+--------+------+-----+----+
|glasses |store1| 30 | 1 |
|glasses |store2| 35 | 2 |
|glasses |store3| 40 | 3 |
|shoes |store2| 10 | 1 |
|shoes |store1| 20 | 2 |
|shoes |store3| 22 | 3 |
+--------+------+-----+----+
$("#HowYouKnow").val("GOOGLE");
You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:
var list = ["one", "two", "three", "four"];
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('List Test'),
),
body: new Center(
child: new Column( // Or Row or whatever :)
children: createChildrenTexts(),
),
),
));
}
List<Text> createChildrenTexts() {
/// Method 1
// List<Text> childrenTexts = List<Text>();
// for (String name in list) {
// childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
// }
// return childrenTexts;
/// Method 2
return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
}
I'd suggest using the request module. Downloading a file is as simple as the following code:
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});
v
has 10
element, the index starts from 0
to 9
.
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
I originally used the solution that @Mrchief for years (it works great). But when when I added Swagger to my project for API documentation my end point was NOT showing up.
It took me a while, but this is what I came up with. It works with Swagger, and your API method signatures look cleaner:
In the end you can do:
// GET: /api/values/1,2,3,4
[Route("api/values/{ids}")]
public IHttpActionResult GetIds(int[] ids)
{
return Ok(ids);
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Allow WebApi to Use a Custom Parameter Binding
config.ParameterBindingRules.Add(descriptor => descriptor.ParameterType == typeof(int[]) && descriptor.ActionDescriptor.SupportedHttpMethods.Contains(HttpMethod.Get)
? new CommaDelimitedArrayParameterBinder(descriptor)
: null);
// Allow ApiExplorer to understand this type (Swagger uses ApiExplorer under the hood)
TypeDescriptor.AddAttributes(typeof(int[]), new TypeConverterAttribute(typeof(StringToIntArrayConverter)));
// Any existing Code ..
}
}
Create a new class: CommaDelimitedArrayParameterBinder.cs
public class CommaDelimitedArrayParameterBinder : HttpParameterBinding, IValueProviderParameterBinding
{
public CommaDelimitedArrayParameterBinder(HttpParameterDescriptor desc)
: base(desc)
{
}
/// <summary>
/// Handles Binding (Converts a comma delimited string into an array of integers)
/// </summary>
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
HttpActionContext actionContext,
CancellationToken cancellationToken)
{
var queryString = actionContext.ControllerContext.RouteData.Values[Descriptor.ParameterName] as string;
var ints = queryString?.Split(',').Select(int.Parse).ToArray();
SetValue(actionContext, ints);
return Task.CompletedTask;
}
public IEnumerable<ValueProviderFactory> ValueProviderFactories { get; } = new[] { new QueryStringValueProviderFactory() };
}
Create a new class: StringToIntArrayConverter.cs
public class StringToIntArrayConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
}
Notes:
Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.
protected void Session_Start(Object sender, EventArgs e)
{
SessionStateSection sessionState =
(SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
string sidCookieName = sessionState.CookieName;
if (Request.Cookies[sidCookieName] != null)
{
HttpCookie sidCookie = Response.Cookies[sidCookieName];
sidCookie.Value = Session.SessionID;
sidCookie.HttpOnly = true;
sidCookie.Secure = true;
sidCookie.Path = "/";
}
}
Did you try using the -ArgumentList
parameter:
invoke-command -ComputerName studio -ScriptBlock { param ( $myarg ) ping.exe $myarg } -ArgumentList localhost
http://technet.microsoft.com/en-us/library/dd347578.aspx
An example of invoking a program that is not in the path and has a space in it's folder path:
invoke-command -ComputerName Computer1 -ScriptBlock { param ($myarg) & 'C:\Program Files\program.exe' -something $myarg } -ArgumentList "myArgValue"
If the value of the argument is static you can just provide it in the script block like this:
invoke-command -ComputerName Computer1 -ScriptBlock { & 'C:\Program Files\program.exe' -something "myArgValue" }