Use the source
command to import other scripts:
#!/bin/bash
source /REFERENCE/TO/CONFIG.FILE
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
Note that the result of dereferencing an std::map::iterator is an std::pair. The values of first
and second
are not functions, they are variables.
Change:
iter->first()
to
iter->first
Ditto with iter->second
.
git reset --hard HEAD^
Use the above command to revert merge changes.
If you are developing a command line interface, I suggest you to take a look at click
which is very nice:
import click
import time
for filename in range(3):
with click.progressbar(range(100), fill_char='=', empty_char=' ') as bar:
for user in bar:
time.sleep(0.01)
Here the output you get:
$ python test.py
[====================================] 100%
[====================================] 100%
[========= ] 27%
PHP has a built-in function implode to assign array values to string. Use it like this:
$str = implode(",", $array);
Assuming you have access to servlet as below
http://localhost:8080/myapp/download?id=7
I need to create a servlet and register it to web.xml
web.xml
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
DownloadServlet.java
public class DownloadServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String fileName = "";
String fileType = "";
// Find this file id in database to get file name, and file type
// You must tell the browser the file type you are going to send
// for example application/pdf, text/plain, text/html, image/jpg
response.setContentType(fileType);
// Make sure to show the download dialog
response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");
// Assume file name is retrieved from database
// For example D:\\file\\test.pdf
File my_file = new File(fileName);
// This should send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
}
I made adb working on Android 4.4.2 with GT-N8010 (Samsung tablet) after setting device in authorized mode once upgraded adb to SDK version.
~/local/opt/Android/Sdk/platform-tools/adb
Android Debug Bridge version 1.0.32
While It did not work using :
adb version
Android Debug Bridge version 1.0.31
Shiped in Ubuntu LTS version :
apt-cache show android-tools-adb | grep Version
Version: 4.2.2+git20130218-3ubuntu23
This link may help then
Many others have failed to point out the real issue:
An operation on only integers casts the result of the operation to an integer.
This necessarily means that floating point results, that could be displayed as an integer, will be truncated (lop off the decimal part).
What is casting (typecasting / type conversion) you ask?
It varies on the implementation of the language, but Wikipedia has a fairly comprehensive view, and it does talk about coercion as well, which is a pivotal piece of information in answering your question.
Try this
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />
if you want 0 or 1 "description" elements, Or
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
if you want 0 to infinity number of "description" elements.
BottomNavigationView
uses colorPrimary from the theme applied for the selected tab and it uses android:textColorSecondary
for the inactive tab icon tint.
So you can create a style with the prefered primary color and set it as a theme to your BottomNavigationView
in an xml layout file.
styles.xml:
<style name="BottomNavigationTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/active_tab_color</item>
<item name="android:textColorSecondary">@color/inactive_tab_color</item>
</style>
your_layout.xml:
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:theme="@style/BottomNavigationTheme"
app:menu="@menu/navigation" />
I wrote a tiny function for this purpose. Feel free to repurpose,
def is_json_key_present(json, key):
try:
buf = json[key]
except KeyError:
return False
return True
In addition to @tadman's answer I removed the wrappers in /usr/local/bin
as well as the file /etc/profile.d/rvm
.
The wrappers include:
erb
gem
irb
rake
rdoc
ri
ruby
testrb
This opens Textmate editor in when you want to edit your commits. Requires textmate command line tools to be installed.
git config --global core.editor "mate -w"
You can also use SUM + IF
which is shorter than SUM + CASE
:
SELECT
count(id)
, SUM(IF(kind=1, 1, 0)) AS countKindOne
, SUM(CASE WHEN kind=2 THEN 1 ELSE 0 END) AS countKindTwo
strace is available from Cygwin in the cygwin package. You can download it from a Cygwin mirror, for example:
http://mirrors.sonic.net/cygwin/x86_64/release/cygwin/cygwin-2.0.2-1.tar.xz
# | | | |
# +-----------+----------+ +--+--+
# | |
# mirror version
strace is one of the few Cygwin programs that does not rely on the Cygwin DLL,
so you should be able to just copy strace.exe
to where you want and use it.
Consistency is what everyone strongly suggest, the rest is upto you as long as it works.
For beginners its easy to get carried away and we name whatever we want at that time. This make sense at that point but a headache later.
foo
foobar
or foo_bar
is great.
We name our table straight forward as much as possible and only use underscore if they are two different words. studentregistration
to student_registration
like @Zbyszek says, having a simple id
is more than enough for the auto-increment. The simplier the better. Why do you need foo_id
? We had the same problem early on, we named all our columns with the table prefix. like foo_id
, foo_name
, foo_age
. We dropped the tablename now and kept only the col as short as possible.
Since we are using just an id for PK we will be using foo_bar_fk
(tablename is unique, folowed by the unique PK, followed by the _fk
) as foreign key. We don't add id
to the col name because it is said that the name 'id' is always the PK of the given table. So we have just the tablename and the _fk
at the end.
For constrains we remove all underscores and join with camelCase (tablename + Colname + Fk) foobarUsernameFk
(for username_fk col). It's just a way we are following. We keep a documentation for every names structures.
When keeping the col name short, we should also keep an eye on the RESTRICTED names.
+------------------------------------+
| foobar |
+------------------------------------+
| id (PK for the current table) |
| username_fk (PK of username table) |
| location (other column) |
| tel (other column) |
+------------------------------------+
resultString = subjectString.replaceAll("[^.\\d]", "");
will remove all characters except digits and the dot from your string.
To make it locale-aware, you might want to use getDecimalSeparator()
from java.text.DecimalFormatSymbols
. I don't know Java, but it might look like this:
sep = getDecimalSeparator()
resultString = subjectString.replaceAll("[^"+sep+"\\d]", "");
Little script I have for that. A modification of it helped to filter out some other non-printable characters in cross-platform legacy files.
#!/usr/bin/perl
# run this as
# convert_dos2unix.pl < input_file > output_file
undef $/;
$_ = <>;
s/\r//ge;
print;
No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.
Valid base64 characters are below.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));
private SpannableString spannableString(String text, int start, int end) {
SpannableString spannableString = new SpannableString(text);
ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
Output:
You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
I think it is fine because I've seen many people doing this way.
If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.
myApp.directive('clickme', function() {
return function(scope, element, attrs) {
var clickingCallback = function() {
alert('clicked!')
};
element.bind('click', clickingCallback);
}
});
I believe this will surely help you.
javadoc -d C:/javadoc/test com.mypackage
Here is a very awesome code to find sqrt and even faster than original sqrt function.
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f375a86 - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x=1/x;
return x;
}
Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:
USE master ;
GO
ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO
Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.
If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:
SELECT
name, database_id, is_broker_enabled
FROM sys.databases
Create the scheduled task and set the action to:
Program/Script: Powershell.exe
Arguments: -File "C:\Users\MyUser\Documents\ThisisMyFile.ps1"
You do not need to select the columns separately in order to use them in your CONCAT. Simply remove them, and your query will become:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
The widely accepted answer by Adam Hopkinson is not a fully automated method of creating a page! It requires a user to manually create a page in the back-end of WordPress (in the wp-admin dash). The problem with that is, a good plugin should have a fully automated setup. It should not require clients to manually create pages.
Also, some of the other widely accepted answers here involve creating a static page outside of WordPress, which then include only some of the WordPress functionality to achieve the themed header and footer. While that method may work in some cases, this can make integrating these pages with WordPress very difficult without having all its functionality included.
I think the best, fully automated, approach would be to create a page using wp_insert_post
and have it reside in the database. An example and a great discussion about that, and how to prevent accidental deletion of the page by a user, can be found here: wordpress-automatically-creating-page
Frankly, I'm surprised this approach hasn't already been mentioned as an answer to this popular question (it has been posted for 7 years).
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
From the link above, GROUP_CONCAT
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
I was making the same mistakes then I realized that I have created my virtual environment as root user. It was write protected, so please check whether your virtual environment is write protected. make a new venv and try again
In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:
on button click, first open the database, fetch the data and close the data base like this
public class cytaty extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galeria);
Button bLosuj = (Button) findViewById(R.id.button1);
bLosuj.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myDatabaseHelper = new DatabaseHelper(cytaty.this);
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getYourData(); //this is the method to query
myDatabaseHelper.close();
// set text to your TextView
}
});
}
}
and your getYourData()
in database class would be like this
public String[] getAppCategoryDetail() {
final String TABLE_NAME = "name of table";
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return data;
}
What is the synchronized keyword?
Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
Synchronized blocks or methods prevents thread interference and make sure that data is consistent. At any point of time, only one thread can access a synchronized block or method (critical section) by acquiring a lock. Other thread(s) will wait for release of lock to access critical section.
When are methods synchronized?
Methods are synchronized when you add synchronized
to method definition or declaration. You can also synchronize a particular block of code with-in a method.
What does it mean pro grammatically and logically?
It means that only one thread can access critical section by acquiring a lock. Unless this thread release this lock, all other thread(s) will have to wait to acquire a lock. They don't have access to enter critical section with out acquiring lock.
This can't be done with a magic. It's programmer responsibility to identify critical section(s) in application and guard it accordingly. Java provides a framework to guard your application, but where and what all sections to be guarded is the responsibility of programmer.
More details from java documentation page
Intrinsic Locks and Synchronization:
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.
Making methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave.
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.
This guarantees that changes to the state of the object are visible to all threads.
Look for other alternatives to synchronization in :
void replaceAll(std::string & data, const std::string &toSearch, const std::string &replaceStr)
{
// Get the first occurrence
size_t pos = data.find(toSearch);
// Repeat till end is reached
while( pos != std::string::npos)
{
// Replace this occurrence of Sub String
data.replace(pos, toSearch.size(), replaceStr);
// Get the next occurrence from the current position
pos =data.find(toSearch, pos + replaceStr.size());
}
}
More CPP utilities: https://github.com/Heyshubham/CPP-Utitlities/blob/master/src/MEString.cpp#L60
It seems all the answers assume high level languages and mainly C/C++.
But the question is tagged "assembly" and in all assemblers I know (for 8bit, 16bit, 32bit and 64bit CPUs), the definitions are much more clear:
byte = 8 bits
word = 2 bytes
dword = 4 bytes = 2Words (dword means "double word")
qword = 8 bytes = 2Dwords = 4Words ("quadruple word")
Thanks for the replies, it works!
And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats
), and on UnicodeDecodeError
I try the next format:
from __future__ import with_statement
import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector
targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()
def get_encoding_type(current_file):
detector.reset()
for line in file(current_file):
detector.feed(line)
if detector.done: break
detector.close()
return detector.result['encoding']
def convertFileBestGuess(filename):
sourceFormats = ['ascii', 'iso-8859-1']
for format in sourceFormats:
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
def convertFileWithDetection(fileName):
print("Converting '" + fileName + "'...")
format=get_encoding_type(fileName)
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
print("Error: failed to convert '" + fileName + "'.")
def writeConversion(file):
with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
for line in file:
targetFile.write(line)
# Off topic: get the file list and call convertFile on each file
# ...
(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)
If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ; then put your logic like
Scanner input = new Scanner (System.in);
System.out.println("Enter number to reverse ");
int org = input.nextInt();
int getReminder;
int r = 0;
int count = 0;
while (org !=0){
getReminder = org%10;
r = 10 * r + getReminder;
org = org/10;
}
System.out.println(r);
}
You should simply apply the following transformation to your input data array.
input_data = input_data.reshape((-1, image_side1, image_side2, channels))
If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1
is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1
in you function.
Var1 = 1
Var2 = 0
def function():
global Var1
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
DATABASE
MongoDB states a nice example:
To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:
use myDB
use myNewDB
Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases
COLLECTIONS
Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.
Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"
>No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
firstname). This one is up for debate according to a few people
around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
readability of your collection name by adding underscores or
camelCasing your collection name is probably too long or should use
periods as appropriate which is the standard for collection
categorization.Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.
Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html
For collections I'm following these suggested patterns until I find official MongoDB documentation.
All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V
, z
, O
, X
, x
, Z
.
Here's they are, for parsing, according to rules from the documentation :
Symbol Meaning Presentation Examples
------ ------- ------------ -------
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
But how about formatting?
Here's a sample for a date (assuming ZonedDateTime
) that show these patters behavior for different formatting patters:
// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}
// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]
// Rules:
// printInPattern(dt, "V"); // exception!
printInPattern(dt, "VV"); // America/Los_Angeles
// printInPattern(dt, "VVV"); // exception!
// printInPattern(dt, "VVVV"); // exception!
printInPattern(dt, "z"); // PST
printInPattern(dt, "zz"); // PST
printInPattern(dt, "zzz"); // PST
printInPattern(dt, "zzzz"); // Pacific Standard Time
printInPattern(dt, "O"); // GMT-8
// printInPattern(dt, "OO"); // exception!
// printInPattern(dt, "OO0"); // exception!
printInPattern(dt, "OOOO"); // GMT-08:00
printInPattern(dt, "X"); // -08
printInPattern(dt, "XX"); // -0800
printInPattern(dt, "XXX"); // -08:00
printInPattern(dt, "XXXX"); // -0800
printInPattern(dt, "XXXXX"); // -08:00
printInPattern(dt, "x"); // -08
printInPattern(dt, "xx"); // -0800
printInPattern(dt, "xxx"); // -08:00
printInPattern(dt, "xxxx"); // -0800
printInPattern(dt, "xxxxx"); // -08:00
printInPattern(dt, "Z"); // -0800
printInPattern(dt, "ZZ"); // -0800
printInPattern(dt, "ZZZ"); // -0800
printInPattern(dt, "ZZZZ"); // GMT-08:00
printInPattern(dt, "ZZZZZ"); // -08:00
In the case of positive offset the +
sign character is used everywhere(where there is -
now) and never omitted.
This well works for new java.time
types. If you're about to use these for java.util.Date
or java.util.Calendar
- not all going to work as those types are broken(and so marked as deprecated, please don't use them)
I'm Tried this and it's working with me :
SELECT CONVERT(date, yourDate ,104)
This is my version of a bash script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).
#!/bin/bash
# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables
DB="$1"
CHARSET="$2"
COLL="$3"
[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"
echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql
echo "USE $DB; SHOW TABLES;" | mysql -s | (
while read TABLE; do
echo $DB.$TABLE
echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
done
)
Easiest and flexible way: JSnippet DEMO
Function style:
function truncString(str, max, add){
add = add || '...';
return (typeof str === 'string' && str.length > max ? str.substring(0,max)+add : str);
};
Prototype:
String.prototype.truncString = function(max, add){
add = add || '...';
return (this.length > max ? this.substring(0,max)+add : this);
};
Usage:
str = "testing with some string see console output";
//By prototype:
console.log( str.truncString(15,'...') );
//By function call:
console.log( truncString(str,15,'...') );
I would check:
The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.
I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.
IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.
If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.
If your markup is bound to a controller, directive or anything else with a $scope:
console.log($scope.movie);
In this case oldDTE is null, so when you try to access oldDTE.Value the InvalidOperationException is thrown since there is no value. In your example you can simply do:
this.MyDateTime = newDT.MyDateTime;
This is arguably not the best way for most circumstances, but it's not been mentioned yet so perhaps it will help someone.
Bind mount host volume
Host folder FOOBAR is mounted in container /volume/FOOBAR
Modify your container's startup script to find GID of the volume you're interested in
$ TARGET_GID=$(stat -c "%g" /volume/FOOBAR)
Ensure your user belongs to a group with this GID (you may have to create a new group). For this example I'll pretend my software runs as the nobody
user when inside the container, so I want to ensure nobody
belongs to a group with a group id equal to TARGET_GID
EXISTS=$(cat /etc/group | grep $TARGET_GID | wc -l)
# Create new group using target GID and add nobody user
if [ $EXISTS == "0" ]; then
groupadd -g $TARGET_GID tempgroup
usermod -a -G tempgroup nobody
else
# GID exists, find group name and add
GROUP=$(getent group $TARGET_GID | cut -d: -f1)
usermod -a -G $GROUP nobody
fi
I like this because I can easily modify group permissions on my host volumes and know that those updated permissions apply inside the docker container. This happens without any permission or ownership modifications to my host folders/files, which makes me happy.
I don't like this because it assumes there's no danger in adding yourself to an arbitrary groups inside the container that happen to be using a GID you want. It cannot be used with a USER
clause in a Dockerfile (unless that user has root privileges I suppose). Also, it screams hack job ;-)
If you want to be hardcore you can obviously extend this in many ways - e.g. search for all groups on any subfiles, multiple volumes, etc.
We can break both a $(selector).each()
loop and a $.each()
loop at a particular iteration by making the callback function return false
. Returning non-false
is the same as a continue statement in a for
loop; it will skip immediately to the next iteration.
return false; // this is equivalent of 'break' for jQuery loop
return; // this is equivalent of 'continue' for jQuery loop
Note that $(selector).each()
and $.each()
are different functions.
References:
int rows = 5;
int cols = 10;
int[] multD = new int[rows * cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int index = r * cols + c;
multD[index] = index * 2;
}
}
Enjoy!
jsonIssues = [...jsonIssues,{ID:'3',Name:'name 3',Notes:'NOTES 3'}]
I tested this code based on all the comments above. Seems to work flawlessly. Comments?
Sub ResetImmediate()
Debug.Print String(5, "*") & " Hi there mom. " & String(5, "*") & vbTab & "Smile"
Application.VBE.Windows("Immediate").SetFocus
Application.SendKeys "^g ^a {DEL} {HOME}"
DoEvents
Debug.Print "Bye Mom!"
End Sub
Previously used the Debug.Print String(200, chr(10))
which takes advantage of the Buffer overflow limit of 200 lines. Didn't like this method much but it works.
Its better to use StringBuilder
instead of String
because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.
One of your conditions is failing. Check the value of mime-type for your files.
Try using application/pdf, not text/pdf. Refer to Proper MIME media type for PDF files
To Get TEXT
attributes added from admin to front end on product listing page.
Thanks Anita Mourya
I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.
METHOD 1
on list.phtml
<?php $i=0; foreach ($_productCollection as $_product): ?>
FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH
<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>
<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>
METHOD 2
Mage/Catalog/Block/Product/List.phtml
OVER RIDE and set in 'local folder'
i.e. Copy From
Mage/Catalog/Block/Product/List.phtml
and PASTE TO
app/code/local/Mage/Catalog/Block/Product/List.phtml
change the function by adding 2 lines shown in bold below.
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$layer = Mage::getSingleton('catalog/layer');
/* @var $layer Mage_Catalog_Model_Layer */
if ($this->getShowRootCategory()) {
$this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
}
// if this is a product view page
if (Mage::registry('product')) {
// get collection of categories this product is associated with
$categories = Mage::registry('product')->getCategoryCollection()
->setPage(1, 1)
->load();
// if the product is associated with any category
if ($categories->count()) {
// show products from this category
$this->setCategoryId(current($categories->getIterator()));
}
}
$origCategory = null;
if ($this->getCategoryId()) {
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
if ($category->getId()) {
$origCategory = $layer->getCurrentCategory();
$layer->setCurrentCategory($category);
}
}
$this->_productCollection = $layer->getProductCollection();
$this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
if ($origCategory) {
$layer->setCurrentCategory($origCategory);
}
}
**//CMI-PK added na_author to filter on product listing page//
$this->_productCollection->addAttributeToSelect('na_author');**
return $this->_productCollection;
}
and you will be happy to see it....!!
I have personally found some errors in when using unix_timestamp based date converstions from dd-MMM-yyyy format to yyyy-mm-dd, using spark 1.6, but this may extend into recent versions. Below I explain a way to solve the problem using java.time that should work in all versions of spark:
I've seen errors when doing:
from_unixtime(unix_timestamp(StockMarketClosingDate, 'dd-MMM-yyyy'), 'yyyy-MM-dd') as FormattedDate
Below is code to illustrate the error, and my solution to fix it. First I read in stock market data, in a common standard file format:
import sys.process._
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType, DateType}
import sqlContext.implicits._
val EODSchema = StructType(Array(
StructField("Symbol" , StringType, true), //$1
StructField("Date" , StringType, true), //$2
StructField("Open" , StringType, true), //$3
StructField("High" , StringType, true), //$4
StructField("Low" , StringType, true), //$5
StructField("Close" , StringType, true), //$6
StructField("Volume" , StringType, true) //$7
))
val textFileName = "/user/feeds/eoddata/INDEX/INDEX_19*.csv"
// below is code to read using later versions of spark
//val eoddata = spark.read.format("csv").option("sep", ",").schema(EODSchema).option("header", "true").load(textFileName)
// here is code to read using 1.6, via, "com.databricks:spark-csv_2.10:1.2.0"
val eoddata = sqlContext.read
.format("com.databricks.spark.csv")
.option("header", "true") // Use first line of all files as header
.option("delimiter", ",") //.option("dateFormat", "dd-MMM-yyyy") failed to work
.schema(EODSchema)
.load(textFileName)
eoddata.registerTempTable("eoddata")
And here is the date conversions having issues:
%sql
-- notice there are errors around the turn of the year
Select
e.Date as StringDate
, cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date) as ProperDate
, e.Close
from eoddata e
where e.Symbol = 'SPX.IDX'
order by cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date)
limit 1000
A chart made in zeppelin shows spikes, which are errors.
and here is the check that shows the date conversion errors:
// shows the unix_timestamp conversion approach can create errors
val result = sqlContext.sql("""
Select errors.* from
(
Select
t.*
, substring(t.OriginalStringDate, 8, 11) as String_Year_yyyy
, substring(t.ConvertedCloseDate, 0, 4) as Converted_Date_Year_yyyy
from
( Select
Symbol
, cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date) as ConvertedCloseDate
, e.Date as OriginalStringDate
, Close
from eoddata e
where e.Symbol = 'SPX.IDX'
) t
) errors
where String_Year_yyyy <> Converted_Date_Year_yyyy
""")
//df.withColumn("tx_date", to_date(unix_timestamp($"date", "M/dd/yyyy").cast("timestamp")))
result.registerTempTable("SPX")
result.cache()
result.show(100)
result: org.apache.spark.sql.DataFrame = [Symbol: string, ConvertedCloseDate: date, OriginalStringDate: string, Close: string, String_Year_yyyy: string, Converted_Date_Year_yyyy: string]
res53: result.type = [Symbol: string, ConvertedCloseDate: date, OriginalStringDate: string, Close: string, String_Year_yyyy: string, Converted_Date_Year_yyyy: string]
+-------+------------------+------------------+-------+----------------+------------------------+
| Symbol|ConvertedCloseDate|OriginalStringDate| Close|String_Year_yyyy|Converted_Date_Year_yyyy|
+-------+------------------+------------------+-------+----------------+------------------------+
|SPX.IDX| 1997-12-30| 30-Dec-1996| 753.85| 1996| 1997|
|SPX.IDX| 1997-12-31| 31-Dec-1996| 740.74| 1996| 1997|
|SPX.IDX| 1998-12-29| 29-Dec-1997| 953.36| 1997| 1998|
|SPX.IDX| 1998-12-30| 30-Dec-1997| 970.84| 1997| 1998|
|SPX.IDX| 1998-12-31| 31-Dec-1997| 970.43| 1997| 1998|
|SPX.IDX| 1998-01-01| 01-Jan-1999|1229.23| 1999| 1998|
+-------+------------------+------------------+-------+----------------+------------------------+
FINISHED
After this result, I switched to java.time conversions with a UDF like this, which worked for me:
// now we will create a UDF that uses the very nice java.time library to properly convert the silly stockmarket dates
// start by importing the specific java.time libraries that superceded the joda.time ones
import java.time.LocalDate
import java.time.format.DateTimeFormatter
// now define a specific data conversion function we want
def fromEODDate (YourStringDate: String): String = {
val formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy")
var retDate = LocalDate.parse(YourStringDate, formatter)
// this should return a proper yyyy-MM-dd date from the silly dd-MMM-yyyy formats
// now we format this true local date with a formatter to the desired yyyy-MM-dd format
val retStringDate = retDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
return(retStringDate)
}
Now I register it as a function for use in sql:
sqlContext.udf.register("fromEODDate", fromEODDate(_:String))
and check the results, and rerun test:
val results = sqlContext.sql("""
Select
e.Symbol as Symbol
, e.Date as OrigStringDate
, Cast(fromEODDate(e.Date) as Date) as ConvertedDate
, e.Open
, e.High
, e.Low
, e.Close
from eoddata e
order by Cast(fromEODDate(e.Date) as Date)
""")
results.printSchema()
results.cache()
results.registerTempTable("results")
results.show(10)
results: org.apache.spark.sql.DataFrame = [Symbol: string, OrigStringDate: string, ConvertedDate: date, Open: string, High: string, Low: string, Close: string]
root
|-- Symbol: string (nullable = true)
|-- OrigStringDate: string (nullable = true)
|-- ConvertedDate: date (nullable = true)
|-- Open: string (nullable = true)
|-- High: string (nullable = true)
|-- Low: string (nullable = true)
|-- Close: string (nullable = true)
res79: results.type = [Symbol: string, OrigStringDate: string, ConvertedDate: date, Open: string, High: string, Low: string, Close: string]
+--------+--------------+-------------+-------+-------+-------+-------+
| Symbol|OrigStringDate|ConvertedDate| Open| High| Low| Close|
+--------+--------------+-------------+-------+-------+-------+-------+
|ADVA.IDX| 01-Jan-1996| 1996-01-01| 364| 364| 364| 364|
|ADVN.IDX| 01-Jan-1996| 1996-01-01| 1527| 1527| 1527| 1527|
|ADVQ.IDX| 01-Jan-1996| 1996-01-01| 1283| 1283| 1283| 1283|
|BANK.IDX| 01-Jan-1996| 1996-01-01|1009.41|1009.41|1009.41|1009.41|
| BKX.IDX| 01-Jan-1996| 1996-01-01| 39.39| 39.39| 39.39| 39.39|
|COMP.IDX| 01-Jan-1996| 1996-01-01|1052.13|1052.13|1052.13|1052.13|
| CPR.IDX| 01-Jan-1996| 1996-01-01| 1.261| 1.261| 1.261| 1.261|
|DECA.IDX| 01-Jan-1996| 1996-01-01| 205| 205| 205| 205|
|DECN.IDX| 01-Jan-1996| 1996-01-01| 825| 825| 825| 825|
|DECQ.IDX| 01-Jan-1996| 1996-01-01| 754| 754| 754| 754|
+--------+--------------+-------------+-------+-------+-------+-------+
only showing top 10 rows
which looks ok, and I rerun my chart, to see if there are errors/spikes:
As you can see, no more spikes or errors. I now use a UDF as I've shown to apply my date format transformations to a standard yyyy-MM-dd format, and have not had spurious errors since. :-)
There is contextlib.redirect_stdout() function in Python 3.4:
import io
from contextlib import redirect_stdout
with io.StringIO() as buf, redirect_stdout(buf):
print('redirected')
output = buf.getvalue()
Here's code example that shows how to implement it on older Python versions.
Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.
Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:
I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
If you just want to get the path to a certain action, use UrlHelper
:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper
:
string url = this.Url.Action("About", "Home", null);
The difference is primarily in deployment. Web forward and reverse proxies all have the same underlying features. They accept requests for HTTP requests in various formats and provide a response, usually by accessing the origin or contact server.
Fully featured servers usually have access control, caching, and some link-mapping features.
A forward proxy is a proxy that is accessed by configuring the client machine. The client needs protocol support for proxy features (redirection, proxy authentication, etc.). The proxy is transparent to the user experience, but not to the application.
A reverse proxy is a proxy that is deployed as a web server and behaves like a web server, with the exception that instead of locally composing the content from programs and disk, it forwards the request to an origin server. From the client perspective it is a web server, so the user experience is completely transparent.
In fact, a single proxy instance can run as a forward and reverse proxy at the same time for different client populations.
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
Removing container by force worked for me.
docker rm -f <id_of_the_dead_container>
Notes:
Be aware that this command might throw this error
Error response from daemon: Driver devicemapper failed to remove root filesystem <id_of_the_dead_container>: Device is Busy
The mount of your's dead container device mapper should be removed despite this message. That is, you will no longer access this path:
/var/lib/docker/devicemapper/mnt/<id_of_the_dead_container>
add a textbox and scrollbar
in VB
Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
If e.OldValue > e.NewValue Then
Textbox1.Text = (Textbox1.Text + 1)
Else
Textbox1.Text = (Textbox1.Text - 1)
End If
End Sub
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
There is no built-in function. You could write one
CREATE FUNCTION is_numeric( p_str IN VARCHAR2 )
RETURN NUMBER
IS
l_num NUMBER;
BEGIN
l_num := to_number( p_str );
RETURN 1;
EXCEPTION
WHEN value_error
THEN
RETURN 0;
END;
and/or
CREATE FUNCTION my_to_number( p_str IN VARCHAR2 )
RETURN NUMBER
IS
l_num NUMBER;
BEGIN
l_num := to_number( p_str );
RETURN l_num;
EXCEPTION
WHEN value_error
THEN
RETURN NULL;
END;
You can then do
IF( is_numeric( str ) = 1 AND
my_to_number( str ) >= 1000 AND
my_to_number( str ) <= 7000 )
If you happen to be using Oracle 12.2 or later, there are enhancements to the to_number
function that you could leverage
IF( to_number( str default null on conversion error ) >= 1000 AND
to_number( str default null on conversion error ) <= 7000 )
No, they don't exist.
I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.
EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.
Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:
white-space: pre-wrap
is what worked for me for <span>
and <div>
.
If you're in Google Chrome, try installing this add-on:
Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel
and then just add controls to it
for ( int i = 0; i < COUNT; i++ ) {
Label lblTitle = new Label();
lblTitle.Text = i+"Your Text";
youlayOut.Controls.Add( lblTitle, 0, i );
TextBox txtValue = new TextBox();
youlayOut.Controls.Add( txtValue, 2, i );
}
//Just in case is not supported or not included by your framework
//***************************************************
Array.prototype.some = function(fn, thisObj) {
var scope = thisObj || window;
for ( var i=0, j=this.length; i < j; ++i ) {
if ( fn.call(scope, this[i], i, this) ) {
return true;
}
}
return false;
};
//****************************************************
function isSet (object, string) {
if (!object) return false;
var childs = string.split('.');
if (childs.length > 0 ) {
return !childs.some(function (item) {
if (item in object) {
object = object[item];
return false;
} else return true;
});
} else if (string in object) {
return true;
} else return false;
}
var object = {
data: {
item: {
sub_item: {
bla: {
here : {
iam: true
}
}
}
}
}
};
console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'x')); // false
console.log(isSet(object,'data.sub_item')); // false
console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'data.item.sub_item.bla.here.iam')); // true
I came across with the same issue. But I believe , handling null in the sql is not a good option. such things should be handled in java program for better performance. secondly , rs.getString("column") != NULL is also not a good option as you are comparing string's reference not value. better to use .equals() method while checking null or isEmpty() method. Again, with this you can use null check, that is fine.
There are a few things interacting here:
docker run your_image arg1 arg2
will replace the value of CMD
with arg1 arg2
. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash
to run a bash shell in the container.
When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh
, you can now run the container with additional args that will be passed as args to file.sh
.
Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&
), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh"
, which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2"
as the command being launched inside your container, not so good. See the table here for more on how these two options interact
The shell -c
option only takes a single argument. Everything after that would get passed as $1
, $2
, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2"
would work, but /bin/sh -c "file.sh" "arg1" "arg2"
would not since file.sh
would be called with no args.
Putting that all together, the common design is:
FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]
And you then run that with:
docker run your_image arg1 arg2
There's a fair bit more detail on this at:
Put the identity
element before the authentication
element
mylist=["ABA", "CAA", "ADA"]
results=[]
for item in mylist:
buffer=[]
for char in item:
if char not in buffer:
buffer.append(char)
results.append("".join(buffer))
print(results)
output
ABA
CAA
ADA
['AB', 'CA', 'AD']
Use:
pip install --install-option="--prefix=$PREFIX_PATH" package_name
You might also want to use --ignore-installed
to force all dependencies to be reinstalled using this new prefix. You can use --install-option
to multiple times to add any of the options you can use with python setup.py install
(--prefix
is probably what you want, but there are a bunch more options you could use).
Javier covered Notifications and current limitations.
My suggestion: window.postMessage
while we wait for the handicapped browser to catch up, else Worker.postMessage()
to still be operating with Web Workers.
These can be the fallback option with dialog box message display handler, for when a Notification feature test fails or permission is denied.
Notification has-feature and denied-permission check:
if (!("Notification" in window) || (Notification.permission === "denied") ) {
// use (window||Worker).postMessage() fallback ...
}
Using the default instance (i.e., MSSQLSERVER, use the DOT (.))
<add name="CONNECTION_STRING_NAME" connectionString="Data Source=.;Initial Catalog=DATABASE_NAME;Integrated Security=True;" />
For IE browsers, the "VBScript solution" works.
But as mentioned by @purefusion at Bypass Printdialog in IE9, Use Print() rather than window.print()
Use the .css()
jQuery manipulators, or better yet just call .show()
/.hide()
on the image once you've obtained a handle to it (e.g. $('#img' + id)
).
BTW, you should not write javascript handlers with the "javascript:" prefix.
You could use with open("path") as file:
so that it automatically closes, else if it's open in another process you can maybe try
as in Tims example you should use except IOError to not ignore any other problem with your code :)
try:
with open("path", "r") as file: # or just open
# Code here
except IOError:
# raise error or print
Another scenario where this occurs is when you have a base class and one or more subclasses, where at least one of the subclasses introduce extra properties:
class Folder {
[key]
public string Id { get; set; }
public string Name { get; set; }
}
// Adds no props, but comes from a different view in the db to Folder:
class SomeKindOfFolder: Folder {
}
// Adds some props, but comes from a different view in the db to Folder:
class AnotherKindOfFolder: Folder {
public string FolderAttributes { get; set; }
}
If these are mapped in the DbContext
like below, the "'Invalid column name 'Discriminator'" error occurs when any type based on Folder
base type is accessed:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Folder>().ToTable("All_Folders");
modelBuilder.Entity<SomeKindOfFolder>().ToTable("Some_Kind_Of_Folders");
modelBuilder.Entity<AnotherKindOfFolder>().ToTable("Another_Kind_Of_Folders");
}
I found that to fix the issue, we extract the props of Folder
to a base class (which is not mapped in OnModelCreating()
) like so - OnModelCreating
should be unchanged:
class FolderBase {
[key]
public string Id { get; set; }
public string Name { get; set; }
}
class Folder: FolderBase {
}
class SomeKindOfFolder: FolderBase {
}
class AnotherKindOfFolder: FolderBase {
public string FolderAttributes { get; set; }
}
This eliminates the issue, but I don't know why!
Be aware that when you do press your <leader>
key you have only 1000ms (by default) to enter the command following it.
This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader>
key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.
If you add set showcmd
to your vimrc
then you will see your <leader>
key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.
The length of the timeout can also be set in your vimrc
, see :help timeoutlen
for more information.
The best example which i know.
public abstract class DisposableType: IDisposable
{
bool disposed = false;
~DisposableType()
{
if (!disposed)
{
disposed = true;
Dispose(false);
}
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
Dispose(true);
GC.SuppressFinalize(this);
}
}
public void Close()
{
Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// managed objects
}
// unmanaged objects and resources
}
}
<location path="ControllerName/ActionName">
<system.web>
<httpRuntime executionTimeout="1000"/>
</system.web>
</location>
Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.
Use of sort
can result in warning message. See github discussion.
So you might wanna use sort_values
, docs here
Then your code can look like this:
df = df.sort_values(by=['c1','c2'], ascending=[False,True])
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
It's the implementations that doesn't support multi-threading. Currently Google Gears is providing a way to use some form of concurrency by executing external processes but that's about it.
The new browser Google is supposed to release today (Google Chrome) executes some code in parallel by separating it in process.
The core language, of course can have the same support as, say Java, but support for something like Erlang's concurrency is nowhere near the horizon.
This concise example demonstrates common way how to create custom tooltip in d3.
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
.append("div")_x000D_
.attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
.append("svg")_x000D_
.attr("width", w)_x000D_
.attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
.data(dataset)_x000D_
.enter()_x000D_
.append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
return (i * 50) + 25;_x000D_
})_x000D_
.attr("cy", h / 2)_x000D_
.attr("r", function(d) {_x000D_
return d;_x000D_
})_x000D_
_x000D_
// we define "mouseover" handler, here we change tooltip_x000D_
// visibility to "visible" and add appropriate test_x000D_
_x000D_
.on("mouseover", function(d) {_x000D_
return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
})_x000D_
_x000D_
// we move tooltip during of "mousemove"_x000D_
_x000D_
.on("mousemove", function() {_x000D_
return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
.style("left", event.pageX + "px");_x000D_
})_x000D_
_x000D_
// we hide our tooltip on "mouseout"_x000D_
_x000D_
.on("mouseout", function() {_x000D_
return tooltip.style("visibility", "hidden");_x000D_
});
_x000D_
.tooltip {_x000D_
position: absolute;_x000D_
z-index: 10;_x000D_
visibility: hidden;_x000D_
background-color: lightblue;_x000D_
text-align: center;_x000D_
padding: 4px;_x000D_
border-radius: 4px;_x000D_
font-weight: bold;_x000D_
color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.
private void AggiornaContatore()
{
if(this.lblCounter.InvokeRequired)
{
this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});
}
else
{
this.lblCounter.Text = this.index.ToString(); ;
}
}
Please go through this chapter and more from this book to get a clear picture about threading:
http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications
>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1
There are many ways to copy Dict object, I simply use
dict_1 = {
'a':1,
'b':2
}
dict_2 = {}
dict_2.update(dict_1)
I think it's better to use the Microsoft.VisualBasic.FileIO.TextFieldParser Class if you're working with comma separated values text files.
touch ~/.gitignore
Example
# these work
*.gz
*.tmproj
*.7z
# these won't as they are folders
.vscode/
build/
# but you can do this
.vscode/*
build/*
git config --get core.excludesfile
git config --global core.excludesfile '~/.gitignore'
Voila!!
In my case the problem was happening because the class I created had a namespace that interfered with existing classes. The new class A had namespace zz.yy.xx (by mistake). References to objects in another namespace yy.xx were not compiling in class A or other classes whose namespace was zz.
I changed the namespace of class A to yy.xx , which it should have been, and it started working.
// Convert BigDecimal number To String by using below method //
public static String RemoveTrailingZeros(BigDecimal tempDecimal)
{
tempDecimal = tempDecimal.stripTrailingZeros();
String tempString = tempDecimal.toPlainString();
return tempString;
}
// Recall RemoveTrailingZeros
BigDecimal output = new BigDecimal(0);
String str = RemoveTrailingZeros(output);
Have you tried setting
li {list-style-type: none;}
According to Need an unordered list without any bullets, you need to add this style to the li elements.
Well, there are two types of wait: explicit and implicit wait. The idea of explicit wait is
WebDriverWait.until(condition-that-finds-the-element);
The concept of implicit wait is
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
You can get difference in details here.
In such situations I'd prefer using explicit wait (fluentWait
in particular):
public WebElement fluentWait(final By locator) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
});
return foo;
};
fluentWait
function returns your found web element.
From the documentation on fluentWait
:
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
Details you can get here
Usage of fluentWait
in your case be the following:
WebElement textbox = fluentWait(By.id("textbox"));
This approach IMHO better as you do not know exactly how much time to wait and in polling interval you can set arbitrary timevalue which element presence will be verified through . Regards.
You can try this
var str = 'hello world !!';
str = str.replace(/\s+/g, '-');
It will even replace multiple spaces with single '-'.
AND
between ORDER BY
and LIMIT
=
between ORDER BY
, LIMIT
keywords and conditionSo you query will look like:
SELECT post_datetime
FROM post
WHERE type = 'published'
ORDER BY post_datetime DESC
LIMIT 3
One more option is WinRun4J. There is an Eclipse Plugin for WinRun4J that allows you to export your application as a single executable with necessary jars/classes embedded.
(full disclosure: I work on this project)
It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.
Kotlin Version:
fun buttonEffect(button: View) {
button.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
v.invalidate()
}
MotionEvent.ACTION_UP -> {
v.background.clearColorFilter()
v.invalidate()
}
}
false
}
}
Java Version:
public static void buttonEffect(View button){
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
Assuming that the ID column in myTable
is not declared as a NUMBER (which seems like an odd choice and likely to be problematic), you can write a function that tries to convert the (presumably VARCHAR2) ID to a number, catches the exception, and returns a 'Y' or an 'N'. Something like
CREATE OR REPLACE FUNCTION is_number( p_str IN VARCHAR2 )
RETURN VARCHAR2 DETERMINISTIC PARALLEL_ENABLE
IS
l_num NUMBER;
BEGIN
l_num := to_number( p_str );
RETURN 'Y';
EXCEPTION
WHEN value_error THEN
RETURN 'N';
END is_number;
You can then embed that call in a query, i.e.
SELECT (CASE WHEN is_number( myTable.id ) = 'Y' AND myTable.id > 0
THEN 'Number > 0'
ELSE 'Something else'
END) some_alias
FROM myTable
Note that although PL/SQL has a boolean data type, SQL does not. So while you can declare a function that returns a boolean, you cannot use such a function in a SQL query.
Notice that instance methods are also attributes (of the class) and that you could set them at the class or instance level if you really wanted to be a badass. Or that you may set a class variable (which is also an attribute of the class), where handy readonly properties won't work neatly out of the box. What I'm trying to say is that the "readonly attribute" problem is in fact more general than it's usually perceived to be. Fortunately there are conventional expectations at work that are so strong as to blind us wrt these other cases (after all, almost everything is an attribute of some sort in python).
Building upon these expectations I think the most general and lightweight approach is to adopt the convention that "public" (no leading underscore) attributes are readonly except when explicitly documented as writeable. This subsumes the usual expectation that methods won't be patched and class variables indicating instance defaults are better let alone. If you feel really paranoid about some special attribute, use a readonly descriptor as a last resource measure.
The only way is to modify the file src/http/ngx_http_header_filter_module.c . I changed nginx on line 48 to a different string.
What you can do in the nginx config file is to set server_tokens to off. This will prevent nginx from printing the version number.
To check things out, try curl -I http://vurbu.com/ | grep Server
It should return
Server: Hai
Simply, after you clone the repo you need to cd (change your current directory) to the new cloned folder
git clone https://[email protected]/Repo_Name.git
cd Repo_Name
You can simply check on client side using grecaptcha.getResponse() method
var rcres = grecaptcha.getResponse();
if(rcres.length){
grecaptcha.reset();
showHideMsg("Form Submitted!","success");
}else{
showHideMsg("Please verify reCAPTCHA","error");
}
First check that the extension is properly loaded in phpinfo();
(something like sqlsrv
should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.
you got some top answers above. This is just another version of that.
var dictFun = {
FunOne: function(string) {
console.log("first function");
},
FuncTwo: function(string) {
console.log("second function");
},
FuncThree: function(string) {
console.log("third function");
}
}
Use the HAVING clause and GROUP By the fields that make the row unique
The below will find
all users that have more than one payment per day with the same account number
SELECT
user_id ,
COUNT(*) count
FROM
PAYMENT
GROUP BY
account,
user_id ,
date
HAVING
COUNT(*) > 1
Update If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY
SELECT
user_id,
account_no ,
date,
COUNT(*)
FROM
(SELECT DISTINCT
user_id,
account_no ,
zip,
date
FROM
payment
)
payment
GROUP BY
user_id,
account_no ,
date
HAVING COUNT(*) > 1
If you read the jquery docs, there are numerous reasons for something to not be considered visible/hidden:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
http://api.jquery.com/visible-selector/
Here's a small jsfiddle example with one visible and one hidden element:
If you are using fastexml jackson, you can use the following:
com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)
If you are using codehaus jackson, you can use the following:
org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);
There is also another way if you define one pointcut for many advices it can be helpful:
@Pointcut("execution(@com.stackoverflow.MyAnnotation * *(..))")
protected void myPointcut() {
}
@AfterThrowing(pointcut = "myPointcut() && args(someId,..)", throwing = "e")
public void afterThrowingException(JoinPoint joinPoint, Exception e, Integer someId) {
System.out.println(someId.toString());
}
@AfterReturning(pointcut = "myPointcut() && args(someId,..)")
public void afterSuccessfulReturn(JoinPoint joinPoint, Integer someId) {
System.out.println(someId.toString());
}
If you want
Try copying the following script into a new batch file (e.g. timecmd.bat):
@echo off
@setlocal
set start=%time%
:: Runs your command
cmd /c %*
set end=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100
set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
if 1%ms% lss 100 set ms=0%ms%
:: Mission accomplished
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)
Usage
If you put timecmd.bat in a directory in your path, you can call it from anywhere like this:
timecmd [your command]
E.g.
C:\>timecmd pause
Press any key to continue . . .
command took 0:0:1.18
If you want to do output redirection, you can quote the command like this:
timecmd "dir c:\windows /s > nul"
This should handle commands that run from before- to after-midnight, but the output will be wrong if your command runs for 24 hours or more.
I fixed the same problem on Google Chrome with the following:
Choose Customize and control Google Chrome (the button in the top right corner).
Choose Settings.
Go to Extensions.
Unmark all the extensions there. (They should show as Enable instead of Enabled.)
I've done it before, I just used:
down.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
Per documentation:
public void setOnLongClickListener (View.OnLongClickListener l)
Since: API Level 1 Register a callback to be invoked when this view is clicked and held. If this view is not long clickable, it becomes long clickable.
Notice that it requires to return a boolean, this should work.
I don't believe any of these answers actually work for clearing the APC cache from the command line. As Frank Farmer commented above, the CLI runs in a process separate from Apache.
My solution for clearing from the command line was to write a script that copies an APC clearing script to the web
directory and accesses it and then deletes it. The script is restricted to being accessed from the localhost.
apc_clear.php
This is the file that the script copies to the web directory, accesses, and deletes.
<?php
if (in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')))
{
apc_clear_cache();
apc_clear_cache('user');
apc_clear_cache('opcode');
echo json_encode(array('success' => true));
}
else
{
die('SUPER TOP SECRET');
}
Cache clearing script
This script copies apc_clear.php to the web directory, accesses it, then deletes it. This is based off of a Symfony task. In the Symfony version, calls are made to the Symfony form of copy and unlink, which handle errors. You may want to add checks that they succeed.
copy($apcPaths['data'], $apcPaths['web']); //'data' is a non web accessable directory
$url = 'http://localhost/apc_clear.php'; //use domain name as necessary
$result = json_decode(file_get_contents($url));
if (isset($result['success']) && $result['success'])
{
//handle success
}
else
{
//handle failure
}
unlink($apcPaths['web']);
I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.
Just hit the same issue and in my case the problem was related to BOM
(byte order mark) at the beginning of the file.
json.tool
would refuse to process even empty file (just curly braces) until i removed the UTF BOM mark.
What I have done is:
set nobomb
)This resolved the problem with json.tool. Hope this helps!
If you're getting your timestamps from System.currentTimeMillis()
, then your time variables should be longs.
Just paste this into your line of codes:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.
assert type(A) is type(""), "requires a string"
While other answers here work, I notice you asked for a div with content. So here's my version with extra content. JSFiddle link at the bottom.
JavaScript (with comments):
// Creating a div element
var divElement = document.createElement("Div");
divElement.id = "divID";
// Styling it
divElement.style.textAlign = "center";
divElement.style.fontWeight = "bold";
divElement.style.fontSize = "smaller";
divElement.style.paddingTop = "15px";
// Adding a paragraph to it
var paragraph = document.createElement("P");
var text = document.createTextNode("Another paragraph, yay! This one will be styled different from the rest since we styled the DIV we specifically created.");
paragraph.appendChild(text);
divElement.appendChild(paragraph);
// Adding a button, cause why not!
var button = document.createElement("Button");
var textForButton = document.createTextNode("Release the alert");
button.appendChild(textForButton);
button.addEventListener("click", function(){
alert("Hi!");
});
divElement.appendChild(button);
// Appending the div element to body
document.getElementsByTagName("body")[0].appendChild(divElement);
HTML:
<body>
<h1>Title</h1>
<p>This is a paragraph. Well, kind of.</p>
</body>
CSS:
h1 { color: #333333; font-family: 'Bitter', serif; font-size: 50px; font-weight: normal; line-height: 54px; margin: 0 0 54px; }
p { color: #333333; font-family: Georgia, serif; font-size: 18px; line-height: 28px; margin: 0 0 28px; }
Note: CSS lines borrowed from Ratal Tomal
Use ? work well, you can check on pythex. Remember to add the parameters *args and **kwargs in the definition of the view methods
url('project_config/(?P<product>\w+)?(/(?P<project_id>\w+/)?)?', tool.views.ProjectConfig, name='project_config')
Install sshpass using, apt-get install sshpass
then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.
#!/bin/bash
SCRIPT="cd Desktop; pwd; echo -e 'PASSWORD' | sudo -S apt-get install vlc"
HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123")
USERNAMES=("username1" "username2" "username3")
PASSWORDS=("password1" "password2" "password3")
for i in ${!HOSTS[*]} ; do
echo ${HOSTS[i]}
SCR=${SCRIPT/PASSWORD/${PASSWORDS[i]}}
sshpass -p ${PASSWORDS[i]} ssh -l ${USERNAMES[i]} ${HOSTS[i]} "${SCR}"
done
For me, this problem was solved by uninstalling the latest version of node and replacing it with the LTS version.
$ ( cd /; umask 0; setsid your_script.sh </dev/null &>/dev/null & ) &
IIS version 8.5 +
To enable Event Tracing for Windows for your website/application
Custom Views > ServerRoles > Web Server
Windows Logs > System
Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).
var offset = $('#whatever').offset();
offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));
You could do this with an INSTEAD OF INSERT
trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:
CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
FROM Person P, inserted I
WHERE P.SSN = I.SSN))
INSERT INTO Person
SELECT SSN,Name,Address,Birthdate
FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
INSERT INTO PersonDuplicates
SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
FROM EmployeeTable E, inserted
WHERE E.SSN = inserted.SSN))
INSERT INTO EmployeeTable
SELECT EmployeeID,SSN, Department, Salary
FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
UPDATE EmployeeTable
SET EmployeeID = I.EmployeeID,
Department = I.Department,
Salary = I.Salary
FROM EmployeeTable E, inserted I
WHERE E.SSN = I.SSN
END
You are looking for --build-arg
and the ARG
instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg
to the Dockerfile
and then build with docker build --build-arg arg=2.3 .
.
I was needed to solve absolutely the same task. I have divided visually the table using different background colors for different parts. Googling the Internet I've found this page https://support.microsoft.com/kb/2815384. Unfortunately it doesn't solve the issue because ColorIndex refers to some unpredictable value, so if some cells have nuances of one color (for example different values of brightness of the color), the suggested function counts them. The solution below is my fix:
Function CountBgColor(range As range, criteria As range) As Long
Dim cell As range
Dim color As Long
color = criteria.Interior.color
For Each cell In range
If cell.Interior.color = color Then
CountBgColor = CountBgColor + 1
End If
Next cell
End Function
The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
Try with simple c++ code in VC++.
#include <windows.h>
#include <iostream>
#pragma comment(lib, "winmm.lib")
int main(int argc, char* argv[])
{
std::cout<<"Sound playing... enjoy....!!!";
PlaySound("C:\\temp\\sound_test.wav", NULL, SND_FILENAME); //SND_FILENAME or SND_LOOP
return 0;
}
I had this but unlike the OP I couldn't see any output before the TCPDF error message.
Turns out there was a UTF8 BOM (byte-order-mark) at the very start of my script, before the <?php tag so before I had any chance to call ob_start(). And there was also a UTF8 BOM before the TCPDF error message.
An example with for loop (I prefer List Comprehensions).
a, b = '[br]', '<br />'
for i, v in enumerate(words):
if a in v:
words[i] = v.replace(a, b)
print(words)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']
Try the -i
flag (or --ignore-errors
). The documentation seems to suggest a more robust way to achieve this, by the way:
To ignore errors in a command line, write a
-
at the beginning of the line's text (after the initial tab). The-
is discarded before the command is passed to the shell for execution.For example,
clean: -rm -f *.o
This causes
rm
to continue even if it is unable to remove a file.
All examples are with rm
, but are applicable to any other command you need to ignore errors from (i.e. mkdir
).
IE6 Internet Explorer 6
Percent only works for the width of an element, but height:100%;
does not work without the correct code.
CSS
html, body { height:100%; }
Then using a percentage works properly, and dynamically updates on window resize.
<img src="image.jpg" style="height:80%;">
You do not need a width attribute, the width scales proportionately as the browser window size is changed.
And this little gem, is in case the image is scaled up, it will not look (overly) blocky (it interpolates).
img { -ms-interpolation-mode: bicubic; }
Props go to this source: Ultimate IE6 Cheatsheet: How To Fix 25+ Internet Explorer 6 Bugs
$("#myid li").click(function() {
alert(this.id); // id of clicked li by directly accessing DOMElement property
alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
alert($(this).html()); // gets innerHTML of clicked li
alert($(this).text()); // gets text contents of clicked li
});
If you are talking about replacing the ID with something:
$("#myid li").click(function() {
this.id = 'newId';
// longer method using .attr()
$(this).attr('id', 'newId');
});
Demo here. And to be fair, you should have first tried reading the documentation:
Making these 2 communicate
=IF(OR(AND(MID(K27,6,1)="N",(MID(K27,6,1)="C"),(MID(K27,6,1)="H"),(MID(K27,6,1)="I"),(MID(K27,6,1)="B"),(MID(K27,6,1)="F"),(MID(K27,6,1)="L"),(MID(K27,6,1)="M"),(MID(K27,6,1)="P"),(MID(K27,6,1)="R"),(MID(K27,6,1)="P"),ISTEXT(G27)="61"),AND(RIGHT(K27,2)=G27)),"Good","Review")
=IF(AND(RIGHT(K27,2)=G27),"Good","Review")
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
You could try
httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");
Im assuming your talking about video here, in which case you may also need to worry about pixel aspect ratio of the source video. For example.
PAL DV comes in a resolution of 720x576. Which would look like its 4:3. Now depending on the Pixel aspect ratio (PAR) the screen ratio can be either 4:3 or 16:9.
For more info have a look here http://en.wikipedia.org/wiki/Pixel_aspect_ratio
You can get Square pixel Aspect Ratio, and a lot of web video is that, but you may want to watch out of the other cases.
Hope this helps
Mark
Use str.join
:
In [27]: mylist = ['10', '12', '14']
In [28]: print '\n'.join(mylist)
10
12
14
JavaScript does not have associative arrays. It has objects.
The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.
var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';
It looks like you have an associative array because an Array
is also an Object
- however you're not actually adding things into the array at all; you're setting fields on the object.
Now that that is cleared up, here is a working solution to your example:
var text = '{ name = oscar }'
var dict = new Object();
// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');
// Split into key and value
var kvp = cleaned.split('=');
// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.
You need to install ENU\x64\SQLEXPRWT_x64_ENU.exe which is Express with Tools (RTM release. SP1 release can be found here).
As the page states
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express) This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
So install this and use the management studio included with it.
As for me, chaining set
methods is the cleanest way
const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");
The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.
If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.
Conceptually, the simplest regular expressions are literal characters. The pattern N
matches the character 'N'.
Regular expressions next to each other match sequences. For example, the pattern Nick
matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.
If you've ever used grep
on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re
in grep
refers to regular expressions.)
Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick
. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c]
matches either 'a' or 'b' or 'c'.
The pattern .
is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...]
.
Think of character classes as menus: pick just one.
Using .
can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]
. Digits are a frequent match target, so you could instead use the shortcut \d
. Others are \s
(whitespace) and \w
(word characters: alphanumerics or underscore).
The uppercased variants are their complements, so \S
matches any non-whitespace character, for example.
From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c
matches 'abc' or 'ac' because the ?
quantifier makes the subpattern it modifies optional. Other quantifiers are
*
(zero or more times)+
(one or more times){n}
(exactly n times){n,}
(at least n times){n,m}
(at least n times but no more than m times)Putting some of these blocks together, the pattern [Nn]*ick
matches all of
The first match demonstrates an important lesson: *
always succeeds! Any pattern can match zero times.
A few other useful examples:
[0-9]+
(and its equivalent \d+
) matches any non-negative integer\d{4}-\d{2}-\d{2}
matches dates formatted like 2019-01-01A quantifier modifies the pattern to its immediate left. You might expect 0abc+0
to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c
. This means 0abc+0
matches '0abc0', '0abcc0', '0abccc0', and so on.
To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0
. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr
.
Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick
. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |
, e.g., (Nick|nick)
.
For another example, you could equivalently write [a-c]
as a|b|c
, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.
Although some characters match themselves, others have special meanings. The pattern \d+
doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+
. A backslash removes the special meaning from the following character.
Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.
For example, say the input is
"Hello," she said, "How are you?"
You might expect ".+"
to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.
To switch from greedy to what you might think of as cautious, add an extra ?
to the quantifier. Now you understand how \((.+?)\)
, the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.
If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.
(As to your confusion, I don't know of any regular-expression dialect where ((.+?))
would do the same thing. I suspect something got lost in transmission somewhere along the way.)
Use the special pattern ^
to match only at the beginning of your input and $
to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.
Say you want to match comments of the form
-- This is a comment --
you'd write ^--\s+(.+)\s+--$
.
Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.
†: The statement above that .
matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n"
, but in practice you rarely expect a pattern such as .+
to cross a newline boundary. Perl regexes have a /s
switch and Java Pattern.DOTALL
, for example, to make .
match any character at all. For languages that don't have such a feature, you can use something like [\s\S]
to match "any whitespace or any non-whitespace", in other words anything.
if (!"success".equals(statusCheck))
Don't do it, if you can avoid it. As Devon Sans points out in the comments: This feature will most likely be deprecated.
#Update - Newer Way
From Angular 4.3.0, all piercing css combinators were deprecated. Angular team introduced a new combinator ::ng-deep
(still it is experimental and not the full and final way) as shown below,
DEMO : https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview
styles: [
`
:host { color: red; }
:host ::ng-deep parent {
color:blue;
}
:host ::ng-deep child{
color:orange;
}
:host ::ng-deep child.class1 {
color:yellow;
}
:host ::ng-deep child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
You can use encapsulation mode
and/or piercing CSS combinators >>>, /deep/ and ::shadow
working example : http://plnkr.co/edit/1RBDGQ?p=preview
styles: [
`
:host { color: red; }
:host >>> parent {
color:blue;
}
:host >>> child{
color:orange;
}
:host >>> child.class1 {
color:yellow;
}
:host >>> child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
I realize this is a very old post, but I encountered a similar issue in which my displayed image always had a border around it. I was trying to fill the browser window with a single image. Adding styles like border:none; did not remove the border and neither did margin:0; or padding:0; or any combination of the three.
However, adding position:absolute;top:0;left:0; fixed the problem.
The original post above has position:absolute; but does not have top:0;left:0; and this was adding a default border on my page.
To illustrate the solution, this has a white border (to be precise, it has a top and left offset):
<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;">
This does not have a border:
<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;">
Hopefully this helps someone finding this post looking to resolve a similar problem.
Here's a practical example (build a dataset from your current location):
$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])
dir | foreach {
$dr = $ds.Tables["tblTest"].NewRow()
$dr["Name"] = $_.name
$dr["Path"] = $_.fullname
$ds.Tables["tblTest"].Rows.Add($dr)
}
$ds.Tables["tblTest"]
$ds.Tables["tblTest"]
is an object that you can manipulate just like any other Powershell object:
$ds.Tables["tblTest"] | foreach {
write-host 'Name value is : $_.name
write-host 'Path value is : $_.path
}
Another option now may be HTML5 text to speech, which is in Chrome 33+ and many others.
Here is a sample:
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
With this, perhaps you do not need to use a web service at all.
In modern c++
you may use the <random>
header that came with c++11
.
To get random float
's you can use std::uniform_real_distribution<>
.
You can use a function to generate the numbers and if you don't want the numbers to be the same all the time, set the engine and distribution to be static
.
Example:
float get_random()
{
static std::default_random_engine e;
static std::uniform_real_distribution<> dis(0, 1); // rage 0 - 1
return dis(e);
}
It's ideal to place the float
's in a container such as std::vector
:
int main()
{
std::vector<float> nums;
for (int i{}; i != 5; ++i) // Generate 5 random floats
nums.emplace_back(get_random());
for (const auto& i : nums) std::cout << i << " ";
}
Example output:
0.0518757 0.969106 0.0985112 0.0895674 0.895542
It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.
char *buff;
size_t buff_size = 100;
int choice;
do{
buff = (char *)malloc(buff_size *sizeof(char));
getline(&buff, &buff_size, stdin);
choice = atoi(buff);
free(buff);
}while((choice<1)&&(choice>9));
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
Probable simplest and generally efficient:
#include <iostream>
int main()
{
std::cout << std::cin.rdbuf();
}
If needed, use stream of other types like std::ostringstream
as buffer instead of standard output stream here.
Use get_the_category()
function.
$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);
Flex is the better way. Just try..
display: flex;
You are not using Oracle, so you should be using the modulus operator:
SELECT * FROM Orders where OrderID % 2 = 0;
The MOD()
function exists in Oracle, which is the source of your confusion.
Have a look at this SO question which discusses your problem.
Try the following:
#restart::before {
content: '';
display: block;
}
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
for .NET CORE use System.AppContext.BaseDirectory
(as a replacement for AppDomain.CurrentDomain.BaseDirectory
)
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
If you look into the source of java.lang.Runtime, you'll see exec finally call protected method: execVM, which means it uses Virtual memory. So for Unix-like system, VM depends on amount of swap space + some ratio of physical memory.
Michael's answer did solve your problem but it might (or to say, would eventually) cause the O.S. deadlock in memory allocation issue since 1 tell O.S. less careful of memory allocation & 0 is just guessing & obviously that you are lucky that O.S. guess you can have memory THIS TIME. Next time? Hmm.....
Better approach is that you experiment your case & give a good swap space & give a better ratio of physical memory used & set value to 2 rather than 1 or 0.
#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
Will remove capital Y and S from str, leaving "ourtring".
Note that remove
is an algorithm and needs the header <algorithm>
included.
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.
In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using new
)? The second is when should we use pointers?
The important take-home message is that you should always use the appropriate tool for the job. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.
In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing Object myObject;
within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you do new Object()
, the object has dynamic storage duration, which means it stays alive until you explicitly delete
it. You should only use dynamic storage duration when you need it.
That is, you should always prefer creating objects with automatic storage duration when you can.
The main two situations in which you might require dynamic allocation:
When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs RAII (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at std::unique_ptr
and std::shared_ptr
, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the Rule of Zero).
However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, always prefer the alternatives unless you really need pointers.
You need reference semantics. Sometimes you want to pass an object using a pointer (regardless of how it was allocated) because you want the function to which you're passing it to have access that that specific object (not a copy of it). However, in most situations, you should prefer reference types to pointers, because this is specifically what they're designed for. Note this is not necessarily about extending the lifetime of the object beyond the current scope, as in situation 1 above. As before, if you're okay with passing a copy of the object, you don't need reference semantics.
You need polymorphism. You can only call functions polymorphically (that is, according to the dynamic type of an object) through a pointer or reference to the object. If that's the behavior you need, then you need to use pointers or references. Again, references should be preferred.
You want to represent that an object is optional by allowing a nullptr
to be passed when the object is being omitted. If it's an argument, you should prefer to use default arguments or function overloads. Otherwise, you should preferably use a type that encapsulates this behavior, such as std::optional
(introduced in C++17 - with earlier C++ standards, use boost::optional
).
You want to decouple compilation units to improve compilation time. The useful property of a pointer is that you only require a forward declaration of the pointed-to type (to actually use the object, you'll need a definition). This allows you to decouple parts of your compilation process, which may significantly improve compilation time. See the Pimpl idiom.
You need to interface with a C library or a C-style library. At this point, you're forced to use raw pointers. The best thing you can do is make sure you only let your raw pointers loose at the last possible moment. You can get a raw pointer from a smart pointer, for example, by using its get
member function. If a library performs some allocation for you which it expects you to deallocate via a handle, you can often wrap the handle up in a smart pointer with a custom deleter that will deallocate the object appropriately.
Firstly It tries insert. If there is a conflict on url
column then it updates content and last_analyzed fields. If updates are rare this might be better option.
INSERT INTO URLs (url, content, last_analyzed)
VALUES
(
%(url)s,
%(content)s,
NOW()
)
ON CONFLICT (url)
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();
border:0;
outline:none;
box-shadow:none;
This should do the trick.
From http://php.quicoto.com/inline-ifelse-statement-ngclick-angularjs/, this is how you do it, if you really have to:
ng-click="variable = (condition=='X' ? 'Y' : 'X')"
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
Don't need a regex
.
string[: string.find(' ')]
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
As discussed, svgs render in order and don't take z-index into account (for now). Maybe just send the specific element to the bottom of its parent so that it'll render last.
function bringToTop(targetElement){
// put the element at the bottom of its parent
let parent = targetElement.parentNode;
parent.appendChild(targetElement);
}
// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));
Worked for me.
If you have a nested SVG, containing groups, you'll need to bring the item out of its parentNode.
function bringToTopofSVG(targetElement){
let parent = targetElement.ownerSVGElement;
parent.appendChild(targetElement);
}
A nice feature of SVG's is that each element contains it's location regardless of what group it's nested in :+1:
netstat -ln | awk '/^(tcp|udp)/ { split($4, a, /:/); print $1, a[2]}' | sort -u
gives you the active tcp/udp ports. Then you can use the ports with fuser -n tcp
or fuser -n udp
, as root, and supposing that fuser
is GNU fuser or has similar options.
If you need more help, let me know.
we can change the icon of markers, i did it on right click event. Lets see if it works for you...
// Create a Marker
var marker = new google.maps.Marker({
position: location,
map: map,
title:'Sample Tool Tip'
});
// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
marker.setIcon('blank.png'); // set image path here...
});
The simple way to use XMLHttpRequest
with pure JavaScript
. You can set custom header
but it's optional used based on requirement.
window.onload = function(){
var request = new XMLHttpRequest();
var params = "UID=CORS&name=CORS";
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('POST', 'https://www.example.com/api/createUser', true);
request.setRequestHeader('api-key', 'your-api-key');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
}
You can send params using POST method.
Please run below example and will get an JSON response.
window.onload = function(){_x000D_
var request = new XMLHttpRequest();_x000D_
_x000D_
request.onreadystatechange = function() {_x000D_
if (this.readyState == 4 && this.status == 200) {_x000D_
console.log(this.responseText);_x000D_
}_x000D_
};_x000D_
_x000D_
request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');_x000D_
request.send();_x000D_
}
_x000D_
With ES6, you can now use the spread operator to create a new array with your new elements inserted before the original elements.
// Prepend a single item._x000D_
const a = [1, 2, 3];_x000D_
console.log([0, ...a]);
_x000D_
// Prepend an array._x000D_
const a = [2, 3];_x000D_
const b = [0, 1];_x000D_
console.log([...b, ...a]);
_x000D_
I intended this answer to present an alternative syntax that I think is more memorable and concise. It should be noted that according to some benchmarks (see this other answer), this syntax is significantly slower. This is probably not going to matter unless you are doing many of these operations in a loop.
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
From Firefox 34 onwards you now have an option for Storage Inspector, which you can enable it from developer tools settings
Once there, you can enable the Storage
options under Default Firefox Developer tools
Updated 27-3-16
Firefox 48.0a1 now supports Cookies editing.
Updated 3-4-16
Firefox 48.0a1 now supports localStorage and sessionStorage editing.
Updated 02-08-16
Firefox 48 (stable release) and onward supports editing of all storage types, except IndexedDB
You can use varStatus in your c:forEach loop
In your first example you can get the counter to work properly as follows...
<c:forEach var="tableEntity" items='${requestScope.tables}'>
<c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="count">
my count is ${count.count}
</c:forEach>
</c:forEach>
Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.
The explanation is that JDK is a bit specific and does not contain the library tools.jar. For my development, I need this library and Mac's JDK doesn't provide it:
tools.jar does not exist. Classes usually located here are instead included in classes.jar. Scripts that rely on the existence of tools.jar need to be rewritten accordingly.
It sucks!
Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.
Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.
In your app level build.gradle
file add the following,
dependencies {
def fragment_version = "1.2.5"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
In your activity
supportFragmentManager.commit {
replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
addToBackStack(null)
}
References
This is very annoying and I expect future versions of C# will address this need. I find the easiest work around to be either use a different data structure type or rename the "items" for your sanity and for the sanity of others reading your code.
Tuple<ApiResource, JSendResponseStatus> result = await SendApiRequest();
ApiResource apiResource = result.Item1;
JSendResponseStatus jSendStatus = result.Item2;
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
On Android API Level 28, I simply ensure that I set up my LinearLayoutManager
and RecyclerView.Adapter
in my Fragment#onCreateView
method, and everything Just Worked™?. I didn't need to do any onSaveInstanceState
or onRestoreInstanceState
work.
Eugen Pechanec's answer explains why this works.
This seems a relict from the old days of simple linkers. You can use static variables in static methods as workaround:
// header.hxx
#include <vector>
class Class {
public:
static std::vector<int> & replacement_for_initialized_static_non_const_variable() {
static std::vector<int> Static {42, 0, 1900, 1998};
return Static;
}
};
int compilation_unit_a();
and
// compilation_unit_a.cxx
#include "header.hxx"
int compilation_unit_a() {
return Class::replacement_for_initialized_static_non_const_variable()[1]++;
}
and
// main.cxx
#include "header.hxx"
#include <iostream>
int main() {
std::cout
<< compilation_unit_a()
<< Class::replacement_for_initialized_static_non_const_variable()[1]++
<< compilation_unit_a()
<< Class::replacement_for_initialized_static_non_const_variable()[1]++
<< std::endl;
}
build:
g++ -std=gnu++0x -save-temps=obj -c compilation_unit_a.cxx
g++ -std=gnu++0x -o main main.cxx compilation_unit_a.o
run:
./main
The fact that this works (consistently, even if the class definition is included in different compilation units), shows that the linker today (gcc 4.9.2) is actually smart enough.
Funny: Prints 0123
on arm and 3210
on x86.
You may connect to Oracle database using sqlplus:
sqlplus "/as sysdba"
Then create new users and assign privileges.
grant all privileges to dac;