As far as I'm aware Ratchet is the best PHP WebSocket solution available at the moment. And since it's open source you can see how the author has built this WebSocket solution using PHP.
Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
Memory mapping has a potential for a huge speed advantage compared to traditional IO. It lets the operating system read the data from the source file as the pages in the memory mapped file are touched. This works by creating faulting pages, which the OS detects and then the OS loads the corresponding data from the file automatically.
This works the same way as the paging mechanism and is usually optimized for high speed I/O by reading data on system page boundaries and sizes (usually 4K) - a size for which most file system caches are optimized to.
Provided your arrays are not huge (see caveat below), you can use the push()
method of the array to which you wish to append values. push()
can take multiple parameters so you can use its apply()
method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat()
of adding elements to the array in place rather than creating a new array.
However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.
var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);
You might want to generalize this into a function:
function pushArray(arr, arr2) {
arr.push.apply(arr, arr2);
}
... or add it to Array
's prototype:
Array.prototype.pushArray = function(arr) {
this.push.apply(this, arr);
};
var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);
... or emulate the original push()
method by allowing multiple parameters using the fact that concat()
, like push()
, allows multiple parameters:
Array.prototype.pushArray = function() {
this.push.apply(this, this.concat.apply([], arguments));
};
var newArray = [];
newArray.pushArray(dataArray1, dataArray2);
Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:
Array.prototype.pushArray = function() {
var toPush = this.concat.apply([], arguments);
for (var i = 0, len = toPush.length; i < len; ++i) {
this.push(toPush[i]);
}
};
I found a very simple solution to, (Pip - Fatal error in launcher:)
1) You must not have multiple environmental variables for the python path.
A) Goto Environmental Variables and delete Python27 in the path if you have Python 3.6.5 installed. Pip is confused by multiple paths!!!
Here's a recursive solution:
function closest(el, selector, stopSelector) {
if(!el || !el.parentElement) return null
else if(stopSelector && el.parentElement.matches(stopSelector)) return null
else if(el.parentElement.matches(selector)) return el.parentElement
else return closest(el.parentElement, selector, stopSelector)
}
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
You use:
public
scope to make that property/method available from anywhere, other classes and instances of the object.
private
scope when you want your property/method to be visible in its own class only.
protected
scope when you want to make your property/method visible in all classes that extend current class including the parent class.
If you don't use any visibility modifier, the property / method will be public.
More: (For comprehensive information)
This is for my comment on Andrey's answer but I cant include code in the comments.
Is you preference activity being called from you main activity? you could place this in the on resume...
@Override
protected void onResume() {
if (!(PreferenceManager.getDefaultSharedPreferences(
getApplicationContext()).getString("listLanguage", "en")
.equals(langPreference))) {
refresh();
}
super.onResume();
}
private void refresh() {
finish();
Intent myIntent = new Intent(Main.this, Main.class);
startActivity(myIntent);
}
$("#list option:selected").each(function() {
alert($(this).text());
});
for multiple selected value in the #list
element.
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Font awesome use SVG icons. So, you can resize it for your requirment.
just use CSS class for that,
.large-icon{
font-size:10em;
//or
font-size:200%;
//or
font-size:50px;
}
I Guess you are trying to center the form both horizontally and vertically with respect to the any container div.
You don't have to make use of bootstrap for it. Just use the popular method (below) to center the form.
.container{
position relative;
}
.form{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
From PHP 7 with null coalescing operator it will be shorter:
$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
Just to be different, changed my answer so that this question doesn't have 5 answers with the same code.
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
var select = $("body").append('<form></form>').children('form')
.append('<input type="hidden" value="" />').children('input[type=hidden]')
.attr('id', 'hiddenValue').end()
.append('<select></select>').children('select')
.attr('id', 'dropdown')
.change(function() {
alert($(this).val());
});
$.each({ one: 1, two: 2, three: 3, four: 4, five: 5 }, function(txt, val) {
select.append('<option value="' + val + '">' + txt + '</option>');
});
});
</script>
</head>
<body></body>
</html>
I wrote a generator to automatically generate icons for your react native app from a single icon file. It generates your assets and it also adds them correctly to your ios and android project:
We revamped our generator to be up to date with the ecosystem standards. You can now use @bam.tech/react-native-make.
You can install it using: yarn add @bam.tech/react-native-make
in the react-native project
To use it react-native set-icon --path <path_to_png> --background <icon_background_color> --platform <android|ios>
And... that's it! Hope it can be useful for others :)
Recommendations:
Here are some improvements over the previous tool:
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf
Edit: as @aix suggested, a better (more fair) way to compare the speed difference:
In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop
In [2]: from math import fabs
In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop
In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop
In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop
In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop
In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop
In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop
In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop
So it seems abs()
only has slight speed advantage over fabs()
for integers. For floats, abs()
and fabs()
demonstrate similar speed.
In addition to what @aix has said, one more thing to consider is the speed difference:
In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop
In [2]: import math
In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop
So abs()
is faster than math.fabs()
.
yes, it accepts the tuple of four arguments, if you have Number of training Images(or whatever)=6000, image size=28x28 and a grayscale image you'll have parameters as (6000,28,28,1)
the last argument is 1 for greyscale and 3 for color images.
The DB_PATH was pointing to different database. Change it in database helper class and my code working.
private static String DB_PATH = "/data/data/com.example.abc";
You can call either string's compareTo method (java.lang.String.compareTo). This feature is well documented on the java documentation site.
Here is a short program that demonstrates it:
class StringCompareExample {
public static void main(String args[]){
String s1 = "Project"; String s2 = "Sunject";
verboseCompare(s1, s2);
verboseCompare(s2, s1);
verboseCompare(s1, s1);
}
public static void verboseCompare(String s1, String s2){
System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");
int comparisonResult = s1.compareTo(s2);
System.out.println("The result of the comparison was " + comparisonResult);
System.out.print("This means that \"" + s1 + "\" ");
if(comparisonResult < 0){
System.out.println("lexicographically precedes \"" + s2 + "\".");
}else if(comparisonResult > 0){
System.out.println("lexicographically follows \"" + s2 + "\".");
}else{
System.out.println("equals \"" + s2 + "\".");
}
System.out.println();
}
}
Here is a live demonstration that shows it works: http://ideone.com/Drikp3
This is a simple way from XML only
spanCount for number of columns
layoutManager for making it grid or linear(Vertical or Horizontal)
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/personListRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Does the column allow null?
Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:
INSERT INTO `database`.`table` (`column`) VALUES (NULL);
The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.
As of Tensorflow version 1.11.0, you need to take this :
init_op = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init_op)
This might be what you are looking for:
yourStream
.filter(/* your criteria */)
.findFirst()
.get();
And better, if there's a possibility of matching no element, in which case get()
will throw a NPE. So use:
yourStream
.filter(/* your criteria */)
.findFirst()
.orElse(null); /* You could also create a default object here */
public static void main(String[] args) {
class Stop {
private final String stationName;
private final int passengerCount;
Stop(final String stationName, final int passengerCount) {
this.stationName = stationName;
this.passengerCount = passengerCount;
}
}
List<Stop> stops = new LinkedList<>();
stops.add(new Stop("Station1", 250));
stops.add(new Stop("Station2", 275));
stops.add(new Stop("Station3", 390));
stops.add(new Stop("Station2", 210));
stops.add(new Stop("Station1", 190));
Stop firstStopAtStation1 = stops.stream()
.filter(e -> e.stationName.equals("Station1"))
.findFirst()
.orElse(null);
System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}
Output is:
At the first stop at Station1 there were 250 passengers in the train.
a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']
# if you care about order
a == b # True
a == c # False
# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True
By casting a
, b
and c
as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.
In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
You need to knock your console into raw mode. There is no built-in platform-independent way of getting there. jCurses might be interesting, though.
On a Unix system, this might work:
String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"};
Runtime.getRuntime().exec(cmd).waitFor();
Each HTML
element has an innerHTML
property that defines both the HTML
code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML
after some user interaction, you can make much more interactive pages.
However, using innerHTML
requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById
function, which works on all browsers.
After you have that set up you can now manipulate the text of an element. To start off, let's try changing the text inside a bold tag.
JavaScript
Code:
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
This answer is from here
Persistence Context is an environment or cache where entity instances(which are capable of holding data and thereby having the ability to be persisted in a database) are managed by Entity Manager.It syncs the entity with database.All objects having @Entity annotation are capable of being persisted. @Entity is nothing but a class which helps us create objects in order to communicate with the database.And the way the objects communicate is using methods.And who supplies those methods is the Entity Manager.
. argument of 0
is interpreted as infinite
. in order to drag the highGUI windows, you need to continually call the cv::waitKey()
function. eg for static images:
cv::imshow("winname", img);
while(cv::waitKey(1) != 27); // 27 = ascii value of ESC
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end
... somewhere else in another class ...
- (void) someMethod
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
rsync
include exclude pattern examples:
"*" means everything
"dir1" transfers empty directory [dir1]
"dir*" transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*" transfers files whose names start with [file]
"dir**" transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***" same as above
"dir1/*" does nothing
"dir1/**" does nothing
"dir1/***" transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...
And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir"
(its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.
I just had this problem too. I closed and opened VS2015 and it "fixed" the issue...
Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->
I achieved it by placing the image tag before the li's:
HTML
<img src="https://www.pinclipart.com/picdir/big/1-17498_plain-right-white-arrow-clip-art-at-clipart.png" class="listImage">
CSS
.listImage{
float:left;
margin:2px;
width:25px
}
.li{
margin-left:29px;
}
update: 31 Oct 2018, Still usable on laravel 5.7 https://laravel.com/docs/5.7/migrations#modifying-columns
To make some change to existing db, you can modify column type by using change()
in migration.
This is what you could do
Schema::table('orders', function ($table) {
$table->string('category_id')->change();
});
please note you need to add doctrine/dbal dependency to composer.json for more information you can find it here http://laravel.com/docs/5.1/migrations#modifying-columns
I found that skipping the quotation marks "" around the file and location name displayed the image... I am doing this on MacBook....
Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function:
def mklist(*args):
result = None
for element in reversed(args):
result = (element, result)
return result
To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.
Either run basicConfig
with stream=sys.stdout
as the argument prior to setting up any other handlers or logging any messages, or manually add a StreamHandler
that pushes messages to stdout to the root logger (or any other logger you want, for that matter).
Do it like this :
<div id="footer">
<ul>
<li><a href="/1.html">Link 1</a></li>
<li><a href="/2.html">Link 2</a></li>
<li><a href="/3.html">Link 3</a></li>
<li><a href="/4.html">Link 4</a></li>
<li><a href="/5.html">Link 5</a></li>
</ul>
</div>
And the CSS:
#footer {
background-color:#ccc;
height:39px;
line-height:36px;
margin:0 auto;
text-align:center;
width:950px;
}
#footer ul li {
display:inline;
font-family:Arial,sans-serif;
font-size:1em;
padding:0 2px;
text-decoration:none;
}
If you intend on your application being available on a large range of devices, you should place your application icon into the different res/drawable...
folders provided. In each of these folders, you should include a 48dp sized icon:
drawable-ldpi
(120 dpi, Low density screen) - 36px x 36pxdrawable-mdpi
(160 dpi, Medium density screen) - 48px x 48pxdrawable-hdpi
(240 dpi, High density screen) - 72px x 72pxdrawable-xhdpi
(320 dpi, Extra-high density screen) - 96px x 96pxdrawable-xxhdpi
(480 dpi, Extra-extra-high density screen) - 144px x 144pxdrawable-xxxhdpi
(640 dpi, Extra-extra-extra-high density screen) - 192px x 192pxYou may then define the icon in your AndroidManifest.xml
file as such:
<application android:icon="@drawable/icon_name" android:label="@string/app_name" >
....
</application>
Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.
Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.
The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
template: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
return htmlText;
}
compile: function(element, attrs)
{
//do whatever else is necessary
}
}
})
I've found that the above solution will not work if you have to deal with control characters like 02
(STX) or 03
(ETX), anything under 10
will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii
function just like in @Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii
function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted. Hope this helps someone else!
while not condition1 or not condition2 or val == -1:
But there was nothing wrong with your original of using an if inside of a while True.
This is the extension I use for calculating multiline UILabel heights, it's an adjusted snippet from a previous stack overflow post:
extension UILabel {
func estimatedHeight(forWidth: CGFloat, text: String, ofSize: CGFloat) -> CGFloat {
let size = CGSize(width: forWidth, height: CGFloat(MAXFLOAT))
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: ofSize)]
let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
return ceil(rectangleHeight)
}
}
Solved issue using below steps :
DocumentRoot "dir_name"
ServerName <server_IP>
<Directory "dir_name">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
<Directory "dir_name">
AllowOverride None
# Allow open access:
Require all granted
2) change folder permission sudo chmod -R 777 "dir_name"
Similar to other answers, this error can be experienced when there are no sites configured to use SSL.
I had the error when I upgraded from Debian Wheezy to Debian Jessie. The new version of Apache requires a site configuration file ending in .conf
. Because my configuration file didn't, it was being ignored, and there were no others configured to serve SSL connections.
It did not worked for me until i created:
#created cc string
cc = ""[email protected];
#added cc to header
msg['Cc'] = cc
and than added cc in recipient [list] like:
s.sendmail(me, [you,cc], msg.as_string())
exit is a system call used to finish a running process from which it is called. The parameter to exit is used to inform the parent process about the status of child process. So, exit(0) can be used (and often used) to indicate successful execution of a process and exit(1) to flag an error. reference link
Ctrl + F11 invokes a dialog with all alphanumeric keys on the keyboard. Selecting one empty will add the current line to bookmarks and mark the line with selected key.
Shift + F11 invokes a list of bookmarks. Pressing a key takes to associated bookmark.
You want to specify a custom tooltip template in your chart options, like this :
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
// String - Template string for multiple tooltips
multiTooltipTemplate: "<%= value + ' %' %>",
This way you can add a '%' sign after your values if that's what you want.
Here's a jsfiddle to illustrate this.
Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.
This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.
Note that Your datasets should only contain numeric values. (No % signs or other stuff there).
One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:
public class TokenTree : Dictionary<string, string>
{
public IDictionary<string, string> SubPairs;
}
This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).
And yup you got the concept of the constructor right :)
The APK Scanner can be show the information of APK file on PC.
also, can be pull an apk file from the android device.
And can be link to other tools.(JADX-GUI, JD-GUI...)
Vue 3 has breaking changes in directives, all of <Vue3 methods were changed/updated. If you wonder, how to do it in Vue 3
, Here's the snippet. For information please go through this link
<div v-click-outside="methodToInvoke"></div>
click-outside.js
export default {
beforeMount: function (el, binding, vnode) {
binding.event = function (event) {
if (!(el === event.target || el.contains(event.target))) {
if (binding.value instanceof Function) {
binding.value(event)
}
}
}
document.body.addEventListener('click', binding.event)
},
unmounted: function (el, binding, vnode) {
document.body.removeEventListener('click', binding.event)
}
}
and In main.js
add the following
// Directives
import ClickOutside from './click-outside'
createApp(App)
.directive('click-outside', ClickOutside)
.use(IfAnyModules)
.mount('#app')
Here is a simple example. I suppose it will be easy to understand:
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;
public Graph() {
f.setTitle("Simple Drawing");
f.setSize(300, 300);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
jp = new GPanel();
f.add(jp);
f.setVisible(true);
}
public static void main(String[] args) {
Graph g1 = new Graph();
g1.setVisible(true);
}
class GPanel extends JPanel {
public GPanel() {
f.setPreferredSize(new Dimension(300, 300));
}
@Override
public void paintComponent(Graphics g) {
//rectangle originates at 10,10 and ends at 240,240
g.drawRect(10, 10, 240, 240);
//filled Rectangle with rounded corners.
g.fillRoundRect(50, 50, 100, 100, 80, 80);
}
}
}
And the output looks like this:
add the onclick attribute
<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>
To get the cursor to change use css's cursor rule.
div[onclick] {
cursor: pointer;
}
The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.
Strange enough, my problem was coming from PHP.
A REST API call was failing, and it was breaking the loading of the libraries afterwards. Since failure was from the REST call, it was not giving me a php compile error.
Keep this as an option also, if loading jquery seems ok.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
Why so many long drawn out methods to accomplish something so simple? It takes less than a minute to download and install the extension from Microsoft. The page says that it will bind it to ALT+D by default, but for me it bound it to CTRL+D automatically in Visual Studio Community 2015 without any changes.
Here's the link to download the extension from Microsoft.com.
For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:
<div class="wrap">
<div>
<span>One</span>
<span>Two</span>
</div>
<div>Three</div>
</div>
and use space-between
:
.wrap {
display: flex;
background: #ccc;
justify-content: space-between;
}
This way you can group multiple items to the right(or just one).
I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.
You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.
<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsSubjects" runat="server"
SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
liststr=""
for item in list
do
liststr=$item,$liststr
done
LEN=`expr length $liststr`
LEN=`expr $LEN - 1`
liststr=${liststr:0:$LEN}
This takes care of the extra comma at the end also. I am no bash expert. Just my 2c, since this is more elementary and understandable
Underscores look ugly in package names. For what is worth, in case of names compound of three or more words I use initials (for example: com.company.app.ingresoegresofijo (ingreso/egreso fijo) -> com.company.app.iefijo
) and then document the package purpose in package-info.java
.
You can use Math.pow instead:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#pow%28double,%20double%29
I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient
Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))
Hope it helps! Cheers.
typeof(IMyInterface).IsAssignableFrom(someclass.GetType());
or
typeof(IMyInterface).IsAssignableFrom(typeof(MyType));
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..
listviewdemo.xml
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
listviewcontent.xml
- note that TextView
- android:id="@+id/txtLstItem"
<LinearLayout
android:id="@+id/listviewcontentlayout"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/txtLstItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:shadowColor="@android:color/black"
android:shadowRadius="5"
android:textColor="@android:color/white" />
</LinearLayout>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
</LinearLayout>
ListViewActivity.java
- Note that view.findViewById(R.id.txtLstItem)
-
as we setting the value to TextView
by setText()
method we getting text from TextView
by View
object returned by onItemClick
method. OnItemClick()
returns the current view.
TextView v=(TextView) view.findViewById(R.id.txtLstItem);
Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
Using this simple logic we can get other values like CheckBox
, RadioButton
, ImageView
etc.
ListView List = (ListView) findViewById(R.id.listview);
cursor = cr.query(CONTENT_URI,projection,null,null,null);
adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
cursor.moveToFirst();
// Let activity manage the cursor
startManagingCursor(cursor);
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
// TODO Auto-generated method stub
TextView v = (TextView) view.findViewById(R.id.txtLstItem);
Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
}
}
);
For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html
Then you should edit your mysqld.cnf
file, for instance :
vim /etc/mysql/mysql.conf.d/mysqld.cnf
Then, add in the [mysqld] part, the following :
plugin-load-add=validate_password.so
validate_password_policy=LOW
Basically, if you edit your default, it will looks like :
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW
Then, you can restart:
systemctl restart mysql
If you forget the plugin-load-add=validate_password.so
part, you will it an error at restart.
Enjoy !
The correct answer should be 2nCn/(n+1) for unlabelled nodes and if the nodes are labelled then (2nCn)*n!/(n+1).
On my pc I need to do the following:
@echo off
start C:\"Program Files (x86)\VirtualDJ\virtualdj_pro.exe"
start C:\toolbetech\TBETECH\"Your Toolbar.exe"
exit
I consider state to be for view only information and data that should persist beyond the view state is better stored as props. URL params are useful when you want to be able to link to a page or share the URL deep in to the app but otherwise clutter the address bar.
Take a look at Redux-Persist (if you're using redux) https://github.com/rt2zz/redux-persist
I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
Replace userEnteredValue with (big surprise) the value that the user entered :)
In a nutshell, Forking is perhaps the same as "cloning under your GitHub ID/profile". A fork is anytime better than a clone, with a few exceptions, obviously. The forked repository is always being monitored/compared with the original repository unlike a cloned repository. That enables you to track the changes, initiate pull requests and also manually sync the changes made in the original repository with your forked one.
In Typescript 3.5+:
interface TypographyProps {
variant: string
fontSize: number
}
type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">
You can change your approach slightly - use Console.ReadKey()
to stop your app, but do your work in a background thread:
static void Main(string[] args)
{
var myWorker = new MyWorker();
myWorker.DoStuff();
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
}
In the myWorker.DoStuff()
function you would then invoke another function on a background thread (using Action<>()
or Func<>()
is an easy way to do it), then immediately return.
This worked for me:
@Override
public void onBindViewHolder(PlacesListViewAdapter.ViewHolder holder, int position) {
----
----
----
// Set setOnClickListener(holder);
}
@Override
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
----
----
----
@Override
public void onClick(View view) {
// Use to get the item clicked getAdapterPosition()
}
}
Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.
If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.
For example, to get a decimal value with a trailing "%" and no space between the value and the "%":
myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });
More complete example:
using System.Globalization;
...
decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)
Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)
Models:
namespace Project.Models
{
public class EmployeeReferral : Person
{
public int EmployeeReferralId { get; set; }
//Company District
//List
[Required(ErrorMessage = "Required.")]
[Display(Name = "Employee District:")]
public int? DistrictId { get; set; }
public virtual District District { get; set; }
}
namespace Project.Models
{
public class District
{
public int? DistrictId { get; set; }
[Display(Name = "Employee District:")]
public string DistrictName { get; set; }
}
}
EmployeeReferral Controller:
namespace Project.Controllers
{
public class EmployeeReferralController : Controller
{
private ProjDbContext db = new ProjDbContext();
//
// GET: /EmployeeReferral/
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
ViewBag.Districts = db.Districts;
return View();
}
View:
<td>
<div class="editor-label">
@Html.LabelFor(model => model.DistrictId, "District")
</div>
</td>
<td>
<div class="editor-field">
@*@Html.DropDownList("DistrictId", "----Select ---")*@
@Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---")
@Html.ValidationMessageFor(model => model.DistrictId)
</div>
</td>
Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
public class DuplicatesWithOutCollection {
public static void main(String[] args) {
int[] arr = new int[] { 2, 3, 4, 6, 6, 8, 10, 10, 10, 11, 12, 12 };
boolean flag = false;
int k = 1;
while (k == 1) {
arr = removeDuplicate(arr);
flag = checkDuplicate(arr, flag);
if (flag) {
k = 1;
} else {
k = 0;
}
}
}
private static boolean checkDuplicate(int[] arr, boolean flag) {
int i = 0;
while (i < arr.length - 1) {
if (arr[i] == arr[i + 1]) {
flag = true;
} else {
flag = false;
}
i++;
}
return flag;
}
private static int[] removeDuplicate(int[] arr) {
int i = 0, j = 0;
int[] temp = new int[arr.length];
while (i < arr.length - 1) {
if (arr[i] == arr[i + 1]) {
temp[j] = arr[i + 1];
i = i + 2;
} else {
temp[j] = arr[i];
i = i + 1;
if (i == arr.length - 1) {
temp[j + 1] = arr[i + 1];
break;
}
}
j++;
}
System.out.println();
return temp;
}
}
open build.gradle file. just add a space or press enter. then sync project. it works...
A simple js solution to set modal height proportional to body's height :
$(document).ready(function () {
$('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});
body's height has to be 100% :
html, body {
height: 100%;
min-height: 100%;
}
I set modal body height to 80% of body, this can be of course customized.
Hope it helps.
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.
Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy
object (the proxy) implements the copy-on-write technique by:
Value
object (the subject);ValueProxy
object sharing the same subject attribute as the original ValueProxy
object;Value
object with the new state and the rebinding of the subject attribute to this new immutable Value
object.import abc
class BaseValue(abc.ABC):
@abc.abstractmethod
def read(self):
raise NotImplementedError
@abc.abstractmethod
def write(self, data):
raise NotImplementedError
class Value(BaseValue):
def __init__(self, data):
self.data = data
def read(self):
return self.data
def write(self, data):
pass
class ValueProxy(BaseValue):
def __init__(self, subject):
self.subject = subject
def read(self):
return self.subject.read()
def write(self, data):
self.subject = Value(data)
def clone(self):
return ValueProxy(self.subject)
v1 = ValueProxy(Value('foo'))
v2 = v1.clone() # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar') # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject
Another option is to use the readonly attribute.
<select readonly="readonly">
....
</select>
With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.
Edit:
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:
When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls
This should fix it...
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
in.next(); // -->important
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
I ran into a similar issue when building a custom pagination for a site I am working on.
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method @Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
Inside archive-episodes.php:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
Do you know if the renew button only appeared when the profile expired? I've a profile that will expire soon, but no "renew" button is shown at the moment.
Just read elsewhere that apparently this is the case.
I am surprised not to see the following pattern here, which actually looks very simple.
// shout.ts
class ShoutSingleton {
helloWorld() { return 'hi'; }
}
export let Shout = new ShoutSingleton();
Usage
import { Shout } from './shout';
Shout.helloWorld();
Lodash has a "map" function that works just like jQuerys:
var myArr = [{ name: "john", age:23 },_x000D_
{ name: "john", age:43 },_x000D_
{ name: "jimi", age:10 },_x000D_
{ name: "bobi", age:67 }];_x000D_
_x000D_
var johns = _.map(myArr, function(o) {_x000D_
if (o.name == "john") return o;_x000D_
});_x000D_
_x000D_
// Remove undefines from the array_x000D_
johns = _.without(johns, undefined)
_x000D_
pyenv
is a 3rd party version manager which is super commonly used (18k stars, 1.6k forks) and exactly what I looked for when I came to this question.
Install pyenv
.
$ pyenv install --list
Available versions:
2.1.3
[...]
3.8.1
3.9-dev
activepython-2.7.14
activepython-3.5.4
activepython-3.6.0
anaconda-1.4.0
[... a lot more; including anaconda, miniconda, activepython, ironpython, pypy, stackless, ....]
$ pyenv install 3.8.1
Downloading Python-3.8.1.tar.xz...
-> https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tar.xz
Installing Python-3.8.1...
Installed Python-3.8.1 to /home/moose/.pyenv/versions/3.8.1
$ pyenv versions
* system (set by /home/moose/.pyenv/version)
2.7.16
3.5.7
3.6.9
3.7.4
3.8-dev
$ python --version
Python 2.7.17
$ pip --version
pip 19.3.1 from /home/moose/.local/lib/python3.6/site-packages/pip (python 3.6)
$ mkdir pyenv-experiment && echo "3.8.1" > "pyenv-experiment/.python-version"
$ cd pyenv-experiment
$ python --version
Python 3.8.1
$ pip --version
pip 19.2.3 from /home/moose/.pyenv/versions/3.8.1/lib/python3.8/site-packages/pip (python 3.8)
Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/
There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python
It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv
for example.
I am surprised the code answer is not posted already, it's a one liner.
You could just {{ categeory_id | getVariations }}
It's a one-liner:
$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));
Collections are a resource so /appointments is fine as the resource.
Collections also typically offer filters via the querystring which is essentially what users=id1,id2... is.
So,
/appointments?users=id1,id2
is fine as a filtered RESTful resource.
You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.
The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.
Yes, Since C++11:
struct B2 {
B2(int = 13, int = 42);
};
struct D2 : B2 {
using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()
// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};
For additional information see http://en.cppreference.com/w/cpp/language/using_declaration
cpdf will do the job from the command-line. It isn't python, though (afaik):
cpdf -add-text "Line of text" input.pdf -o output .pdf
As pprakash mentions above, copying the table.frm files AND the ibdata1 file was what worked for me.
In short:
After that, all was well. (Don't forget to backup if you have success!)
Try this:
export CURLNAME="john:@31&3*J"
curl -d -u "${CURLNAME}" https://www.example.com
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
projectDetailsController.controller('ProjectDetailsCtrl', function ($scope, $routeParams, $http) {
$http.get('data/projects.json').success(function(data) {
$scope.projects = data;
console.log(data);
for(var i = 0; i < data.length; i++) {
$scope.project = data[i];
if($scope.project.name === $routeParams.projectName) {
console.log('project-details',$scope.project);
return $scope.project;
}
}
});
});
Not sure if it's really good, but this was helpful for me.. I needed to use $scope to make it work properly.
This might be super late, but this is for people that might stumble on this problem and might want to use external package for parsing date string.
I've tried looking for a libraries and I found this one:
https://github.com/araddon/dateparse
Example from the README:
package main
import (
"flag"
"fmt"
"time"
"github.com/apcera/termtables"
"github.com/araddon/dateparse"
)
var examples = []string{
"May 8, 2009 5:57:51 PM",
"Mon Jan 2 15:04:05 2006",
"Mon Jan 2 15:04:05 MST 2006",
"Mon Jan 02 15:04:05 -0700 2006",
"Monday, 02-Jan-06 15:04:05 MST",
"Mon, 02 Jan 2006 15:04:05 MST",
"Tue, 11 Jul 2017 16:28:13 +0200 (CEST)",
"Mon, 02 Jan 2006 15:04:05 -0700",
"Thu, 4 Jan 2018 17:53:36 +0000",
"Mon Aug 10 15:44:11 UTC+0100 2015",
"Fri Jul 03 2015 18:04:07 GMT+0100 (GMT Daylight Time)",
"12 Feb 2006, 19:17",
"12 Feb 2006 19:17",
"03 February 2013",
"2013-Feb-03",
// mm/dd/yy
"3/31/2014",
"03/31/2014",
"08/21/71",
"8/1/71",
"4/8/2014 22:05",
"04/08/2014 22:05",
"4/8/14 22:05",
"04/2/2014 03:00:51",
"8/8/1965 12:00:00 AM",
"8/8/1965 01:00:01 PM",
"8/8/1965 01:00 PM",
"8/8/1965 1:00 PM",
"8/8/1965 12:00 AM",
"4/02/2014 03:00:51",
"03/19/2012 10:11:59",
"03/19/2012 10:11:59.3186369",
// yyyy/mm/dd
"2014/3/31",
"2014/03/31",
"2014/4/8 22:05",
"2014/04/08 22:05",
"2014/04/2 03:00:51",
"2014/4/02 03:00:51",
"2012/03/19 10:11:59",
"2012/03/19 10:11:59.3186369",
// Chinese
"2014?04?08?",
// yyyy-mm-ddThh
"2006-01-02T15:04:05+0000",
"2009-08-12T22:15:09-07:00",
"2009-08-12T22:15:09",
"2009-08-12T22:15:09Z",
// yyyy-mm-dd hh:mm:ss
"2014-04-26 17:24:37.3186369",
"2012-08-03 18:31:59.257000000",
"2014-04-26 17:24:37.123",
"2013-04-01 22:43",
"2013-04-01 22:43:22",
"2014-12-16 06:20:00 UTC",
"2014-12-16 06:20:00 GMT",
"2014-04-26 05:24:37 PM",
"2014-04-26 13:13:43 +0800",
"2014-04-26 13:13:44 +09:00",
"2012-08-03 18:31:59.257000000 +0000 UTC",
"2015-09-30 18:48:56.35272715 +0000 UTC",
"2015-02-18 00:12:00 +0000 GMT",
"2015-02-18 00:12:00 +0000 UTC",
"2017-07-19 03:21:51+00:00",
"2014-04-26",
"2014-04",
"2014",
"2014-05-11 08:20:13,787",
// mm.dd.yy
"3.31.2014",
"03.31.2014",
"08.21.71",
// yyyymmdd and similar
"20140601",
// unix seconds, ms
"1332151919",
"1384216367189",
}
var (
timezone = ""
)
func main() {
flag.StringVar(&timezone, "timezone", "UTC", "Timezone aka `America/Los_Angeles` formatted time-zone")
flag.Parse()
if timezone != "" {
// NOTE: This is very, very important to understand
// time-parsing in go
loc, err := time.LoadLocation(timezone)
if err != nil {
panic(err.Error())
}
time.Local = loc
}
table := termtables.CreateTable()
table.AddHeaders("Input", "Parsed, and Output as %v")
for _, dateExample := range examples {
t, err := dateparse.ParseLocal(dateExample)
if err != nil {
panic(err.Error())
}
table.AddRow(dateExample, fmt.Sprintf("%v", t))
}
fmt.Println(table.Render())
}
First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.
For example, this command will dump the database and run it through gzip and the data will finally land in three.gz
mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 one.gz
-rw-r--r-- 1 uname grp 1246 Mar 9 00:37 three.gz
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 two.gz
My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)
This is an example of recompressing files:
mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 1246 Mar 9 00:44 one.gz
-rw-r--r-- 1 uname grp 1306 Mar 9 00:44 three.gz
-rw-r--r-- 1 uname grp 1276 Mar 9 00:44 two.gz
This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html
It was a limitation of the technology at the time it was created. My answer copied over from Programmers.SE:
From one of the original HTML drafts:
NOTE: In the initial design for forms, multi-line text fields were supported by the Input element with TYPE=TEXT. Unfortunately, this causes problems for fields with long text values. SGML's default (Reference Quantity Set) limits the length of attribute literals to only 240 characters. The HTML 2.0 SGML declaration increases the limit to 1024 characters.
It's not a cut and paste. The CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:
SELECT * FROM [Purchasing].[Vendor] WHERE
CASE
WHEN @url IS null OR @url = '' OR @url = 'ALL'
THEN PurchasingWebServiceURL LIKE '%'
WHEN @url = 'blank'
THEN PurchasingWebServiceURL = ''
WHEN @url = 'fail'
THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
ELSE PurchasingWebServiceURL = '%' + @url + '%'
END
I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since @url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?
I highly recommend this video which illustrates the recursion for this problem in a very understandable way.
The key is to understand the repeating pattern in the solution. The problem can be divided into three main sub-problems. Assuming you have n disks that they are placed at rod A. The target rod is C, and you have B as an intermediate.
Main problem; move n disks from rod A to rod C by using rod B.
Sub-problems 1 and 3 are actually solved within the same problem division you see above. Lets take sub problem 1.
Sub-problem 1; move n-1 disks from rod A to rod B by using rod C.
We solve the sub-problem in the same way we solve the main-problem. Our base case will be when the number of disks are equal to 1 then we move it from one rod to target one, that's it.
Writing down these steps will help tremendously.
I known this is old, but I found a easier solution and it works on ie10, firefox and chrome:
<div id="wrapper">
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
</div>
This is the css:
#wrapper {display:table;}
#one {display:table-footer-group;}
#three {display:table-header-group;}
And the result:
"Three"
"Two"
"One"
I found it here.
Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:
echo '<p>' . $unit1 . "</p>\n";
PS: One clarification, single quotes strings do accept two escape sequences:
\'
when you want to use single quote inside single quoted strings\\
when you want to use backslash literallyFor me, created an empty bootstrap.css.map together with bootstrap.css and the error stopped.
Dim M As Range
Set M = Selection
If application.CountIf(M, "<>0") < 2 Then
MsgBox "Nothing selected, please select first BOM or Next BOM"
Else
'Your code here
End If
From experience I just learned you could do:
If Selection.Rows.Count < 2
Then End If`
Clarification to be provided a bit later (right now I'm working)
change your query to like.
$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");
However, MySQL is deprecated. You should instead use MySQLi or PDO
pgrep
can get you all of the child PIDs of a parent process. As mentioned earlier $$
is the current scripts PID. So, if you want a script that cleans up after itself, this should do the trick:
trap 'kill $( pgrep -P $$ | tr "\n" " " )' SIGINT SIGTERM EXIT
One of the reason may be improper date/time of your PC.
In Ubuntu PC to check the date and time using:
date
Example, One of the ways to update date and time is:
date -s "23 MAR 2017 17:06:00"
There is no explicitly defined limit. The amount of available address space forms a practical limit.
(Taken from this site). See the docs on Numeric Types where you'll see that Long integers have unlimited precision
. In Python 2, Integers will automatically switch to longs when they grow beyond their limit:
>>> import sys
>>> type(sys.maxsize)
<type 'int'>
>>> type(sys.maxsize+1)
<type 'long'>
for integers we have
The maximum value of an int can be found in Python 2.x with sys.maxint
. It was removed in Python 3, but sys.maxsize
can often be used instead. From the changelog:
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
and, for anyone interested in the difference (Python 2.x):
sys.maxint The largest positive integer supported by Python’s regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 — the asymmetry results from the use of 2’s complement binary arithmetic.
sys.maxsize The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
and for completeness, here's the Python 3 version:
sys.maxsize An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2^31 - 1 on a 32-bit platform and 2^63 - 1 on a 64-bit platform.
There's float("inf")
and float("-inf")
. These can be compared to other numeric types:
>>> import sys
>>> float("inf") > sys.maxsize
True
If you want to find versions prior to .NET 4.5, use code for a console application. Like this:
using System;
using System.Security.Permissions;
using Microsoft.Win32;
namespace findNetVersion
{
class Program
{
static void Main(string[] args)
{
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
{
foreach (string versionKeyName in ndpKey.GetSubKeyNames())
{
if (versionKeyName.StartsWith("v"))
{
RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
string name = (string)versionKey.GetValue("Version", "");
string sp = versionKey.GetValue("SP", "").ToString();
string install = versionKey.GetValue("Install", "").ToString();
if (install == "") //no install info, must be later version
Console.WriteLine(versionKeyName + " " + name);
else
{
if (sp != "" && install == "1")
{
Console.WriteLine(versionKeyName + " " + name + " SP" + sp);
}
}
if (name != "")
{
continue;
}
foreach (string subKeyName in versionKey.GetSubKeyNames())
{
RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
name = (string)subKey.GetValue("Version", "");
if (name != "")
sp = subKey.GetValue("SP", "").ToString();
install = subKey.GetValue("Install", "").ToString();
if (install == "") //no install info, ust be later
Console.WriteLine(versionKeyName + " " + name);
else
{
if (sp != "" && install == "1")
{
Console.WriteLine(" " + subKeyName + " " + name + " SP" + sp);
}
else if (install == "1")
{
Console.WriteLine(" " + subKeyName + " " + name);
}
}
}
}
}
}
}
}
}
Otherwise you can find .NET 4.5 or later by querying like this:
private static void Get45or451FromRegistry()
{
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
{
int releaseKey = (int)ndpKey.GetValue("Release");
{
if (releaseKey == 378389)
Console.WriteLine("The .NET Framework version 4.5 is installed");
if (releaseKey == 378758)
Console.WriteLine("The .NET Framework version 4.5.1 is installed");
}
}
}
Then the console result will tell you which versions are installed and available for use with your deployments. This code come in handy, too because you have them as saved solutions for anytime you want to check it in the future.
Simple and dynamic way.
This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.
handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });
From the @LearnRPG answer but with 1.0:
// send to current request socket client
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.sockets.emit('message', "this is a test"); //still works
//or
io.emit('message', 'this is a test');
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
// docs says "simply use to or in when broadcasting or emitting"
io.in('game').emit('message', 'cool game');
// sending to individual socketid, socketid is like a room
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
To answer @Crashalot comment, socketid
comes from:
var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })
The token has to be placed in an Authorization header according to the following format:
Authorization: Bearer [Token_Value]
import urllib2
import json
def get_auth_token():
"""
get an auth token
"""
req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
token_string=json_obj["token"].encode("ascii","ignore")
return token_string
def get_response_json_object(url, auth_token):
"""
returns json object with info
"""
auth_token=get_auth_token()
req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
return json_obj
add compile 'org.jsoup:jsoup:1.10.2'
to dependencies in APP LEVEL build.gradle
&
Just add below code and you are good to go.
private class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... voids) {
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + SplashActivity.this.getPackageName() + "&hl=it")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (!currentVersion.equalsIgnoreCase(onlineVersion)) {
//show dialog
new AlertDialog.Builder(context)
.setTitle("Updated app available!")
.setMessage("Want to update app?")
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
Toast.makeText(getApplicationContext(), "App is in BETA version cannot update", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
})
.setNegativeButton("Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
new MyAsyncTask().execute();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
It could be that you don't have privileges to some of the files. From an administrator account, try "sudo rsync -av " Alternately, enable the root account and sign in as root. That should allow you to completely hose your system and brute force your rsync! ;-) I'm not sure if the above mentioned --extended-attributes will help, but I threw it in too, just for good measure.
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
This should work, try;
Add a System Reference.
using System.Diagnostics;
Then use this code to run your command in a hiden CMD Window.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();
Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit()
.
For example:
admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()
user = User.query.get(5)
user.name = 'New Name'
db.session.commit()
Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.
from https://galaxyinternet.us/google-chrome-redirects-localhost-to-https-fix/
None of the option fixes worked for me, for fixing https://localhost:3000
, this did.
click and hold Reload
Button and select Empty Cache and Hard Reload
, this seems to only be an option on localhost
public static ResultSet getResult(Connection connection, List values) {
try {
String queryString = "Select * from table_name where column_name in";
StringBuilder parameterBuilder = new StringBuilder();
parameterBuilder.append(" (");
for (int i = 0; i < values.size(); i++) {
parameterBuilder.append("?");
if (values.size() > i + 1) {
parameterBuilder.append(",");
}
}
parameterBuilder.append(")");
PreparedStatement statement = connection.prepareStatement(queryString + parameterBuilder);
for (int i = 1; i < values.size() + 1; i++) {
statement.setInt(i, (int) values.get(i - 1));
}
return statement.executeQuery();
} catch (Exception d) {
return null;
}
}
Pattern based configs are scheduled for 2.0.0 release of ESLint. For now, however, you will have to create two separate tasks (as mentioned in the comments). One for tests and one for the rest of the code and run both of them, while providing different .eslintrc files.
P.S. There's a jest environment coming in the next release of ESLint, it will register all of the necessary globals.
The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:
When you iterate over it with for i in ar:
the values of i will be 2, 4 and 6. So, when you try to access ar[i]
for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.
If you intend to use indexes anyhow, try using for index, value in enumerate(ar):
, then theSum = theSum + ar[index]
should work just fine.
This is very easy.
In terms of pattern interpretation, there's no difference between the following forms:
/pattern/
new RegExp("pattern")
If you want to replace a literal string using the replace
method, I think you can just pass a string instead of a regexp to replace
.
Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:
function reEscape(s) {
return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}
// ...
var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);
Is it also possible to access the management port in a similar way, e.g.:
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomServerPort;
@LocalManagementPort
int randomManagementPort;
You also can do like this:
default: &default
adapter: mysql2
encoding: utf8
username: root
password:
host: 127.0.0.1
port: 3306
development:
<<: *default
database: development_db_name
test:
<<: *default
database: test_db_name
production:
<<: *default
database: production_db_name
//img[@title='Modify'][i]
is short for
/descendant-or-self::node()/img[@title='Modify'][i]
hence is returning the i'th node under the same parent node.
You want
/descendant-or-self::img[@title='Modify'][i]
The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.
The question asked is just a type conversion question and here its conversion from int
data type to float
data type and for that you can do it by the function :
float()
And for more details you can visit this page.
There are plenty of descriptive answers here so I'm not going to repeat what has already been said. What I would like to add is the following code demonstrating all the permutations I can think of. The code is quite long due to the number of combinations. Feel free to drop it into MSTest and see the output for yourself (the output is included at the bottom).
This evidence supports Jon Skeet's answer.
Code:
[TestMethod]
public void StringEqualsMethodVsOperator()
{
string s1 = new StringBuilder("string").ToString();
string s2 = new StringBuilder("string").ToString();
Debug.WriteLine("string a = \"string\";");
Debug.WriteLine("string b = \"string\";");
TryAllStringComparisons(s1, s2);
s1 = null;
s2 = null;
Debug.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", 20)));
Debug.WriteLine(string.Empty);
Debug.WriteLine("string a = null;");
Debug.WriteLine("string b = null;");
TryAllStringComparisons(s1, s2);
}
private void TryAllStringComparisons(string s1, string s2)
{
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- string.Equals --");
Debug.WriteLine(string.Empty);
Try((a, b) => string.Equals(a, b), s1, s2);
Try((a, b) => string.Equals((object)a, b), s1, s2);
Try((a, b) => string.Equals(a, (object)b), s1, s2);
Try((a, b) => string.Equals((object)a, (object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- object.Equals --");
Debug.WriteLine(string.Empty);
Try((a, b) => object.Equals(a, b), s1, s2);
Try((a, b) => object.Equals((object)a, b), s1, s2);
Try((a, b) => object.Equals(a, (object)b), s1, s2);
Try((a, b) => object.Equals((object)a, (object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- a.Equals(b) --");
Debug.WriteLine(string.Empty);
Try((a, b) => a.Equals(b), s1, s2);
Try((a, b) => a.Equals((object)b), s1, s2);
Try((a, b) => ((object)a).Equals(b), s1, s2);
Try((a, b) => ((object)a).Equals((object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- a == b --");
Debug.WriteLine(string.Empty);
Try((a, b) => a == b, s1, s2);
#pragma warning disable 252
Try((a, b) => (object)a == b, s1, s2);
#pragma warning restore 252
#pragma warning disable 253
Try((a, b) => a == (object)b, s1, s2);
#pragma warning restore 253
Try((a, b) => (object)a == (object)b, s1, s2);
}
public void Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, T1 in1, T2 in2)
{
T3 out1;
Try(tryFunc, e => { }, in1, in2, out out1);
}
public bool Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, Action<Exception> catchFunc, T1 in1, T2 in2, out T3 out1)
{
bool success = true;
out1 = default(T3);
try
{
out1 = tryFunc.Compile()(in1, in2);
Debug.WriteLine("{0}: {1}", tryFunc.Body.ToString(), out1);
}
catch (Exception ex)
{
Debug.WriteLine("{0}: {1} - {2}", tryFunc.Body.ToString(), ex.GetType().ToString(), ex.Message);
success = false;
catchFunc(ex);
}
return success;
}
Output:
string a = "string";
string b = "string";
-- string.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- object.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- a.Equals(b) --
a.Equals(b): True
a.Equals(Convert(b)): True
Convert(a).Equals(b): True
Convert(a).Equals(Convert(b)): True
-- a == b --
(a == b): True
(Convert(a) == b): False
(a == Convert(b)): False
(Convert(a) == Convert(b)): False
--------------------
string a = null;
string b = null;
-- string.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- object.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- a.Equals(b) --
a.Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
a.Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
-- a == b --
(a == b): True
(Convert(a) == b): True
(a == Convert(b)): True
(Convert(a) == Convert(b)): True
This is the problem that is occurring,
if the JAR file was loaded from "C:\java\apps\appli.jar", and your manifest file has the Class-Path: reference "lib/other.jar", the class loader will look in "C:\java\apps\lib\" for "other.jar". It won't look at the JAR file entry "lib/other.jar".
Solution:-
[ EDIT = 3rd option generates a folder in addition to the jar, 2nd option ("Package required libraries into generated JAR") can also be used as you have the jar. ]
open the terminal,give the proper path to your jar and run it using this command java -jar abc.jar
Now what will happen is the class loader will look in the correct folder for the referenced JARS since now they are present in the same folder that contains your app JAR..There is no "java.lang.NoClassDefFoundError" exception thrown now.
This worked for me... Hope it works for you too!!!
Here is an example of some SVG code I used to get three lines of vertical text into a table column heading. Other angles are possible with a bit of tweaking. I believe most browsers support SVG these days.
<svg height="150" width="40">
<text font-weight="bold" x="-150" y="10" transform="rotate(-90 0 0)">Jane Doe</text>
<text x="-150" y="25" transform="rotate(-90 0 0)">0/0 0/0</text>
<text x="-150" y="40" transform="rotate(-90 0 0)">2015-06-06</text>
Sorry, your browser does not support inline SVG.
</svg>
DateTime values should be inserted as if they are strings surrounded by single quotes:
'20100301'
SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat
and to use generalized format:
Set DateFormat MDY --indicates the general format is Month Day Year
Insert Table( DateTImeCol )
Values( '2011-03-12' )
By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD
instead of YYYY-DD-MM
.
SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD
e.g. 20110312
.
If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP
. For example:
Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )
In your script, this part:
document.getElementById('Noite')
must be returning null
and you are also attempting to set the display
property to an invalid value. There are a couple of possible reasons for this first part to be null
.
You are running the script too early before the document has been loaded and thus the Noite
item can't be found.
There is no Noite
item in your HTML.
I should point out that your use of document.write()
in this case code probably signifies a problem. If the document has already loaded, then a new document.write()
will clear the old content and start a new fresh document so no Noite
item would be found.
If your document has not yet been loaded and thus you're doing document.write()
inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite
item.
The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:
document.getElementById('Noite').style.display='block';
And, make sure that there are no document.write()
statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).
In addition, setting the display
property to "display"
doesn't make sense to me. The valid options for that are "block"
, "inline"
, "none"
, "table"
, etc... I'm not aware of any option named "display"
for that style property. See here for valid options for teh display
property.
You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.
P.S. I should point out that your lack of braces for your if
statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.
I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:
var
declarations to your variables (a good habit to always use).if
statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.if
statement so it absolutely clear which statements are part of the if/else
and which are not.</dd>
tag you were inserting.style.display = '';
to style.display = 'block';
.The code:
<div id="Night" style="display: none;">
<img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
<img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
document.write(" Você não<br> devia<br> estar<br>dormindo?");
} else if (hr <= 11) {
document.write("Bom dia!");
} else if (hr == 12) {
document.write(" Vamos<br> almoçar?");
} else if (hr <= 17) {
document.write("Boa Tarde");
} else if (hr <= 19) {
document.write(" Bom final<br> de tarde!");
} else if (hr == 20) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
document.write(" Boa Noite");
} else if (hr == 23) {
document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>
This works well for coping entire records.
UPDATE your_table
SET new_field = sourse_field
If you would like to stay in spring boot space just set the pom packaging to jar
<packaging>jar</packaging>
and add the spring-boot-maven-plugin to you build properties in the pom.xml file:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
then a simple mvn package command will create a complete executable jar file.
See the very good spring reference doc for more details (doing it gradle style also) spring reference doc
<select id="itemDescFormId" name="itemDescFormId" size="1" ng-model="prop" ng-change="update()">
<option value="">English(EN)</option>
<option value="23">Corsican(CO)</option>
<option value="43">French(FR)</option>
<option value="16">German(GR)</option>
Just add option with empty value. It will work.
I had this same problem in Chrome where my scripts were like:
<script src="./scripts/jquery-1.12.3.min.js"></script>
<script src="./scripts/ol-3.15.1/ol.js" />
<script>
...
$(document).ready(function() {
...
});
...
</script>
When I changed to:
<script src="./scripts/jquery-1.12.3.min.js"></script>
<script src="./scripts/ol-3.15.1/ol.js"></script>
$(document).ready was called.
These lines in your makefile,
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h
and this line in your .cpp file,
#include "StdCUtil/split.h"
are in conflict.
With your makefile in your source directory and with that -I
option you should be using #include "split.h"
in your source file, and your dependency should be ../StdCUtil/split.h
.
Another option:
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/.. # Ugly!
DEPS = $(INC_DIR)/split.h
With this your #include
directive would remain as #include "StdCUtil/split.h"
.
Yet another option is to place your makefile in the parent directory:
root
|____Makefile
|
|___Core
| |____DBC.cpp
| |____Lock.cpp
| |____Trace.cpp
|
|___StdCUtil
|___split.h
With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core
and StdCUtil
directories. Object
, for example. With this, your makefile becomes:
INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.
DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.
all: $(OBJS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CC) $(CFLAGS) -c $< -o $@
$(OBJ_DIR)/Trace.o: $(DEPS)
When all else fails, try quitting your IDE. I had many cases in which PyCharm was causing this. As soon as I quit PyCharm, I was able to finally install my packages from the command line. Alternatively, you can also install through PyCharm itself in Settings -> Project: xxx -> Project Interpreter -> +.
assign is what you are looking for.
assign("x", 5)
x
[1] 5
but buyer beware.
See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)
The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the other program in the same Window
start "" /B cmd
%SendKeys% "echo off{ENTER}"
set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"
set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"
set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"
%SendKeys% "exit{ENTER}"
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
For example:
LEFT ARROW {LEFT}
RIGHT ARROW {RIGHT}
For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs
Not with pure CSS. The closest equivalent is this:
.class1, .class2 {
some stuff
}
.class2 {
some more stuff
}
I experienced the same issue, however in my case it was due to the Configuration settings in IntelliJ IDEA.
Even though the project SDK (File -> Project Structure) was set to Java 11, the JRE in the Run/Debug Configurations (Run -> Edit Configurations) was set to Java 8. After changing that to Java 11, it worked like a charm.
I want to add a "late" answer, because I struggled with change
, keyup
and search
today, and maybe what I found in the end may be useful for others too.
Basically, I have a search-as-type panel, and I just wanted to react properly to the press of the little X (under Chrome and Opera, FF does not implement it), and clear a content pane as a result.
I had this code:
$(some-input).keyup(function() {
// update panel
}
$(some-input).change(function() {
// update panel
}
$(some-input).on("search", function() {
// update panel
}
(They are separate because I wanted to check when and under which circumstances each was called).
It turns out that Chrome and Firefox react differently.
In particular, Firefox treats change
as "every change to the input", while Chrome treats it as "when focus is lost AND the content is changed".
So, on Chrome the "update panel" function was called once, on FF twice for every keystroke (one in keyup
, one in change
)
Additionally, clearing the field with the small X (which is not present under FF) fired the search
event under Chrome: no keyup
, no change
.
The conclusion? Use input
instead:
$(some-input).on("input", function() {
// update panel
}
It works with the same behaviour under all the browsers I tested, reacting at every change in the input content (copy-paste with the mouse, autocompletion and "X" included).
While using replace
seems to solve the problem, I would like to propose an alternative. Problem with mix of numeric and some string values in the column not to have strings replaced with np.nan, but to make whole column proper. I would bet that original column most likely is of an object type
Name: y, dtype: object
What you really need is to make it a numeric column (it will have proper type and would be quite faster), with all non-numeric values replaced by NaN.
Thus, good conversion code would be
pd.to_numeric(df['y'], errors='coerce')
Specify errors='coerce'
to force strings that can't be parsed to a numeric value to become NaN. Column type would be
Name: y, dtype: float64
Add a css reset to the top of your website style sheet, different browsers render some default margin and padding and perhaps external style sheets do something you are not aware of too, a css reset will just initialize a fresh palette so to speak:
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, caption {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
UPDATE: Use the Universal Selector Instead:
@Frank mentioned that you can use the Universal Selector: *
instead of listing all the elements, and this selector looks like it is cross browser compatible in all major browsers:
* {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
You can add colors array in high chart graph for changing the color of graph. You can re-arrange these colors and you can also specify your own colors.
$('#container').highcharts({
colors: ['#2f7ed8','#910000','#8bbc21','#1aadce'],
chart: {
type: 'column'
},
title: {
text: 'Stacked column chart'
},
Not much, really. You need a Makefile
in the current directory.
While you're in Vim, type :make
to invoke a shell and build your program. Don't worry when the output scrolls by; just press Enter when it's finished to return to Vim.
Back within Vim, you have the following commands at your disposal:
:cl
lists the errors, warnings, and other messages.:cc
displays the current error/warning message at the bottom of the screen and jumps to the offending line in your code.:cc n
jumps to the n
th message.:cn
advances to the next message.:cp
jumps to the previous message.There are more; if you're interested, type :help :cc
from within Vim.
if(typeof value === 'object' && value.constructor === Object)
{
console.log("This is an object");
}
If you are using iscroll.js on webkit browser or mobile browser, you could try:
$('#pageWrapper>div:last-child').css('top', "0px");
It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe
. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.
I ended up creating the ODBC connection directly under HKLM\Software\ODBC
. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.
After creating the entry (by hand), I fired up my windows service and everything was happy.
Use this code (taken from css-tricks) that will work on all browser
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;
/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
You could try this:
DECLARE @List VARCHAR(MAX)
SELECT @List = '1,2,3,4,5,6,7,8'
EXEC(
'DELETE
FROM TABLE
WHERE ID NOT IN (' + @List + ')'
)
You can control with a change event if the input is within your range, if it is not in the range you assign 0.
<md-input-container>
<input type="number"
maxlength="3"
min="0"
max="100"
required
mdInput
placeholder="Charge"
[(ngModel)]="rateInput"
(change)= "rateInput < 0 ? rateInput = 0 : rateInput; rateInput > 100 ? rateInput = 0 : rateIntput;"
name="rateInput">
<md-error>Required field</md-error>
</md-input-container>
Selecting all the text you wish to format and pressing CtrlK, CtrlF shortcut applies the indenting and space formatting.
As specified in the Formatting pane (of the language being used) in the Text Editor section of the Options dialog.
See VS Shortcuts for more.
Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.
Go to where your R program is installed. This is referred to as R_Home
in the literature. Once you find it, go to the /etc subdirectory.
C:\R\R-2.10.1\etc
Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:
# my custom library path
.libPaths("C:/R/library")
(The comment added to keep track of what I did to the file.)
In R, typing the .libPaths()
function yields the first target at C:/R/Library
NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.
Post deleting and adding your new profile, you can verify if the profile is active and been take by your project by running below command.
grep -i "yourproject" *.mobileprovision
No need to rename or delete the whole folder:
(%AppData%\..\Local\Microsoft\VisualStudio\11.0\ComponentModelCache)
Just rename or delete the Microsoft.VisualStudio.Default.cache
file inside the above location.
An efficient way to loop over an Array is the built-in array method .map()
For a 1-dimensional array it would look like this:
function HandleOneElement( Cuby ) {
Cuby.dimension
Cuby.position_x
...
}
cubes.map(HandleOneElement) ; // the map function will pass each element
for 2-dimensional array:
cubes.map( function( cubeRow ) { cubeRow.map( HandleOneElement ) } )
for an n-dimensional array of any form:
Function.prototype.ArrayFunction = function(param) {
if (param instanceof Array) {
return param.map( Function.prototype.ArrayFunction, this ) ;
}
else return (this)(param) ;
}
HandleOneElement.ArrayFunction(cubes) ;
Use .onclick
(all lowercase). Like so:
document.getElementById("foo").onclick = function () {
alert('foo'); // do your stuff
return false; // <-- to suppress the default link behaviour
};
Actually, you'll probably find yourself way better off using some good library (I recommend jQuery for several reasons) to get you up and running, and writing clean javascript.
Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.
Assuming you have well formed html, you could also maybe try an XSL transform.
Here's an example:
using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml.Xsl;
class Html2TextExample
{
public static string Html2Text(XDocument source)
{
var writer = new StringWriter();
Html2Text(source, writer);
return writer.ToString();
}
public static void Html2Text(XDocument source, TextWriter output)
{
Transformer.Transform(source.CreateReader(), null, output);
}
public static XslCompiledTransform _transformer;
public static XslCompiledTransform Transformer
{
get
{
if (_transformer == null)
{
_transformer = new XslCompiledTransform();
var xsl = XDocument.Parse(@"<?xml version='1.0'?><xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" exclude-result-prefixes=""xsl""><xsl:output method=""html"" indent=""yes"" version=""4.0"" omit-xml-declaration=""yes"" encoding=""UTF-8"" /><xsl:template match=""/""><xsl:value-of select=""."" /></xsl:template></xsl:stylesheet>");
_transformer.Load(xsl.CreateNavigator());
}
return _transformer;
}
}
static void Main(string[] args)
{
var html = XDocument.Parse("<html><body><div>Hello world!</div></body></html>");
var text = Html2Text(html);
Console.WriteLine(text);
}
}
assume series s
s = pd.Series(np.arange(100))
Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]
s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 89.1
dtype: float64
OR
s.quantile(np.linspace(.1, 1, 9, 0), 'lower')
0.1 9
0.2 19
0.3 29
0.4 39
0.5 49
0.6 59
0.7 69
0.8 79
0.9 89
dtype: int32
I'm answering only the part of the question about zbar
installation.
I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:
Install it with pip install zbar-0.10-cp27-none-win_amd64.whl
If Python reports an ImportError: DLL load failed: The specified module could not be found.
when doing import zbar
, then you will just need to install the Visual C++ Redistributable Packages for VS 2013 (I spent a lot of time here, trying to recompile unsuccessfully...)
Required too: libzbar64-0.dll must be in a folder which is in the PATH. In my case I copied it to "C:\Python27\libzbar64-0.dll" (which is in the PATH). If it still does not work, add this:
import os
os.environ['PATH'] += ';C:\\Python27'
import zbar
PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.
PS2: I just tested pyzbar with pip install pyzbar
and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.
.container
has a max width pixel value, whereas .container-fluid
is max-width 100%.
.container-fluid
continuously resizes as you change the width of your window/browser by any amount.
.container
resizes in chunks at several certain widths, controlled by media queries (technically we can say it’s “fixed width”
because pixels values are specified, but if you stop there, people may get the
impression that it can’t change size – i.e. not responsive.)
Other answers describe the purposes. Here are the characters each function will actually convert:
control = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F'
+ '\x10\x11\x12\x13\x14\X15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F'
+ '\x7F'
encodeURI (control + ' "%<>[\\]^`{|}' )
encodeURIComponent(control + ' "%<>[\\]^`{|}' + '#$&,:;=?' + '+/@' )
escape (control + ' "%<>[\\]^`{|}' + '#$&,:;=?' + "!'()~")
All characters above are converted to percent-hexadecimal codes. Space to %20
, percent to %25
, etc. The characters below pass through unchanged.
Here are the characters the functions will NOT convert:
pass_thru = '*-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
encodeURI (pass_thru + '#$&,:;=?' + '+/@' + "!'()~")
encodeURIComponent(pass_thru + "!'()~")
escape (pass_thru + '+/@' )
Something like this works for me, you can then call the function, and it will dispatch itself onto a new thread.
from thread import start_new_thread
def dowork(asynchronous=True):
if asynchronous:
args = (False)
start_new_thread(dowork,args) #Call itself on a new thread.
else:
while True:
#do something...
time.sleep(60) #sleep for a minute
return
01. Open the page for which you want to get the information.
02. Clear the address bar [where you type the address of the sites]:
and type or copy/paste from below:
javascript:alert(document.lastModified)
03. Press Enter or Go button.
They are just \r\n and \n
are variants.
\r\n
is used in windows
\n
is used in mac and linux
Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:
conda install pyqt=4
This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example
conda install pyqt=4.11
would install the latest (or last) release of version 4.11.
Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.
The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).
You need to actually include the header (using a #include
directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.
Do you really want to blacklist specific characters or rather whitelist the allowed charachters?
I assume that you actually want the latter. This is pretty simple (add any additional symbols to whitelist into the [\-]
group):
^(?:\p{L}\p{M}*|[\-])*$
Edit: Optimized the pattern with the input from the comments
A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.
Subject example (with RxJS 5 API):
const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));
Console output will be empty
BehaviorSubject example:
const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));
Console output: 1
In addition:
BehaviorSubject
should be created with an initial value: new Rx.BehaviorSubject(1)
ReplaySubject
if you want the subject to hold more than one valueMost programming languages aren't built on-top of existing programming languages. C++ is built on-top of C, and furthermore it's an object-oriented programming language built from a procedural programming language, and for that reason there are C++ expressions like extern "C"
which provide backwards compatibility with C.
Let's look at the following example:
#include <stdio.h>
// Two functions are defined with the same name
// but have different parameters
void printMe(int a) {
printf("int: %i\n", a);
}
void printMe(char a) {
printf("char: %c\n", a);
}
int main() {
printMe("a");
printMe(1);
return 0;
}
A C compiler will not compile the above example, because the same function printMe
is defined twice (even though they have different parameters int a
vs char a
).
gcc -o printMe printMe.c && ./printMe;
1 error. PrintMe is defined more than once.
A C++ compiler will compile the above example. It does not care that printMe
is defined twice.
g++ -o printMe printMe.c && ./printMe;
This is because a C++ compiler implicitly renames (mangles) functions based on their parameters. In C, this feature was not supported. However, when C++ was built over C, the language was designed to be object-oriented, and needed to support the ability to create different classes with methods (functions) of the same name, and to override methods (method overriding) based on different parameters.
extern "C"
says "don't mangle C function names"However, imagine we have a legacy C file named "parent.c" that include
s function names from other legacy C files, "parent.h", "child.h", etc. If the legacy "parent.c" file is run through a C++ compiler, then the function names will be mangled, and they will no longer match the function names specified in "parent.h", "child.h", etc - so the function names in those external files would also need to be mangled. Mangling function names across a complex C program, those with lots of dependencies, can lead to broken code; so it might be convenient to provide a keyword which can tell the C++ compiler not to mangle a function name.
The extern "C"
keyword tells a C++ compiler not to mangle (rename) C function names.
For example:
extern "C" void printMe(int a);
$gcc -o program program.c -l <library_to_resolve_program.c's_unresolved_symbols>
A good description of why the placement of -l dl matters
But there's also a pretty succinct explanation in the docs From $man gcc
-llibrary -l library Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)
It makes a difference where in the command you write this option; the
linker searches and processes libraries and object files in the order
they are specified. Thus, foo.o -lz bar.o searches library z after
file foo.o but before bar.o. If bar.o refers to functions in z,
those functions may not be loaded.
Try
<iframe src="url" style="border:none;"></iframe>
This will remove the border of your frame.
In servers, you may like to send RST
instead of FIN
when disconnecting misbehaving clients. That skips FIN-WAIT
followed by TIME-WAIT
socket states in the server, which prevents from depleting server resources, and, hence, protects from this kind of denial-of-service attack.
In case if you hate Inner classes, by taking the advantage of functional interface you can write less code in Java 8 with a lambda expression.
JsonDeserializer<Date> dateJsonDeserializer =
(json, typeOfT, context) -> json == null ? null : new Date(json.getAsLong());
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,dateJsonDeserializer).create();
You are looking for map_keys, with it you can write things like
BOOST_FOREACH(const key_t key, the_map | boost::adaptors::map_keys)
{
// do something with key
}
Actual error
follow bellow two simple steps to fix.
Step 1:- update "Intel x86 Emulator Accelerator (HAXM installer)" Ref. bellow img
Step2:-
After installing the installer, you have to run it to install it on your system. Open the directory where your Android SDK is located. Go inside the extras\Intel\Hardware_Accelerated_Execution_Manager directory and you should see the intelhaxm-android.exe file.
If you got the error "This computer meets requirements for HAXM, but VT-x is not turned on..." during installation try to turn it on in your BIOS and check your antivirus software settings also. (Check this stackoverflow post). Thats it! its working for me.
I realise this is an old post but this might benefit somebody who, like me, has come to this page from a google search and is at their wits end.
None of the other answers given here worked for me and I had already given up hope, but today I was searching for a solution to another similar problem with divs, which I found answered multiple times on SO. The accepted answer worked for my div, and I had the sudden notion to try it for my previous textbox issue - and it worked! The solution:
add box-sizing: border-box
to the style of the textbox.
To add this to all multi-line textboxes using CSS, add the following to your style sheet:
textarea
{
box-sizing: border-box;
}
Thanks to thirtydot for the solution at
and
Content of div is longer then div itself when width is set to 100%?
One super easy thing to do is to think asynchronously when accessing the data you want for the page. Whether reading from a web service, file, data base or something else, use the async model as much as possible. While it won't necessarily help any one page be faster it will help your server perform better overall.
USE [DATABASE]
DECLARE @USERNAME VARCHAR(500)
DECLARE @STRSQL NVARCHAR(MAX)
SET @USERNAME='[USERNAME] '
SET @STRSQL=''
select @STRSQL+=CHAR(13)+'GRANT EXECUTE ON ['+ s.name+'].['+obj.name+'] TO'+@USERNAME+';'
from
sys.all_objects as obj
inner join
sys.schemas s ON obj.schema_id = s.schema_id
where obj.type in ('P','V','FK')
AND s.NAME NOT IN ('SYS','INFORMATION_SCHEMA')
EXEC SP_EXECUTESQL @STRSQL