This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:
- APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
different; type shape differs in key cases). These differences
currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
include more of the .NET Framework BCL APIs over time.- Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
programming model. For example, Code Access Security (CAS) is not
supported, while reflection is supported.
If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.
My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.
Linq and Entity framework are included in .NET Core, so you are safe to take a shot.
How about just chaining the greps?
grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'
Adding to the solutions of others, I'd like to suggest using the plotly
package for R
, as this has worked well for me.
Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:
x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z
library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")
The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.
You can also try it with the built-in volcano
dataset from R
:
plot_ly(z=volcano, type="surface")
For prevent an error "can't modify frozen string" for encoding a varible you can use: var.dup.force_encoding(Encoding::ASCII_8BIT)
or var.dup.force_encoding(Encoding::UTF_8)
This often happens when your SQL is bad (implicit type conversions etc.).
Turn on hibernate SQL logging by adding the following lines to your log4j properties file:
log4j.logger.org.hibernate.SQL=debug
log4j.logger.org.hibernate.type=trace
Before failing you will see the last SQL statement attempted in your log, copy and paste this SQL into an external SQL client and run it.
Just as Brian said, you can use remote debugging:
mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 com.mycompany.app.App"
Then in your eclipse, you can use remote debugging and attach the debugger to localhost:1044.
The REST camp have some guiding principles that we can use to standardize the way we use HTTP verbs. This is helpful when building RESTful API's as you are doing.
In a nutshell: GET should be Read Only i.e. have no effect on server state. POST is used to create a resource on the server. PUT is used to update or create a resource. DELETE is used to delete a resource.
In other words, if your API action changes the server state, REST advises us to use POST/PUT/DELETE, but not GET.
User agents usually understand that doing multiple POSTs is bad and will warn against it, because the intent of POST is to alter server state (eg. pay for goods at checkout), and you probably don't want to do that twice!
Compare to a GET which you can do an often as you like (idempotent).
What actually causes a java.lang.StackOverflowError is typically unintentional recursion. For me it's often when I intended to call a super method for the overidden method. Such as in this case:
public class Vehicle {
public void accelerate(float acceleration, float maxVelocity) {
// set the acceleration
}
}
public class SpaceShip extends Vehicle {
@Override
public void accelerate(float acceleration, float maxVelocity) {
// update the flux capacitor and call super.accelerate
// oops meant to call super.accelerate(acceleration, maxVelocity);
// but accidentally wrote this instead. A StackOverflow is in our future.
this.accelerate(acceleration, maxVelocity);
}
}
First, it's useful to know what happens behind the scenes when we call a function. The arguments and the address of where the method was called is pushed on the stack (see http://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Runtime_memory_management) so that the called method can access the arguments and so that when the called method is completed, execution can continue after the call. But since we are calling this.accelerate(acceleration, maxVelocity) recursively (recursion is loosely when a method calls itself. For more info see http://en.wikipedia.org/wiki/Recursion_(computer_science)) we are in a situation known as infinite recursion and we keep piling the arguments and return address on the call stack. Since the call stack is finite in size, we eventually run out of space. The running out of space on the call stack is known as overflow. This is because we are trying to use more stack space than we have and the data literally overflows the stack. In the Java programming language, this results in the runtime exception java.lang.StackOverflow and will immediately halt the program.
The above example is somewhat simplified (although it happens to me more than I'd like to admit.) The same thing can happen in a more round about way making it a bit harder to track down. However, in general, the StackOverflow is usually pretty easy to resolve, once it occurs.
In theory, it is also possible to have a stack overflow without recursion, but in practice, it would appear to be a fairly rare event.
If you used
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
you would imply that chaining was possible when it is not.
This would be better:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
Alternatively, from the FAQ:
if ( $('#myDiv').length ) { /* Do something */ }
You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { /* Do something */ }
If you are not working with others (or are happy to cause them significant annoyance), then it is possible to remove commits from bitbucket branches.
git reset HEAD^ # remove the last commit from the branch history
git push origin :branch_name # delete the branch from bitbucket
git push origin branch_name # push the branch back up again, without the last commit
In git generally, the master branch is not special - it's just a convention. However, bitbucket and github and similar sites usually require there to be a main branch (presumably because it's easier than writing more code to handle the event that a repository has no branches - not sure). So you need to create a new branch, and make that the main branch:
# on master:
git checkout -b master_temp
git reset HEAD^ # undo the bad commit on master_temp
git push origin master_temp # push the new master to Bitbucket
On Bitbucket, go to the repository settings, and change the "Main branch" to master_temp
(on Github, change the "Default branch").
git push origin :master # delete the original master branch from Bitbucket
git checkout master
git reset master_temp # reset master to master_temp (removing the bad commit)
git push origin master # re-upload master to bitbucket
Now go to Bitbucket, and you should see the history that you want. You can now go to the settings page and change the Main branch back to master
.
This process will also work with any other history changes (e.g. git filter-branch
). You just have to make sure to reset to appropriate commits, before the new history split off from the old.
edit: apparently you don't need to go to all this hassle on github, as you can force-push a reset branch.
Next time anyone tries to pull from your repository, (if they've already pulled the bad commit), the pull will fail. They will manually have to reset to a commit before the changed history, and then pull again.
git reset HEAD^
git pull
If they have pulled the bad commit, and committed on top of it, then they will have to reset, and then git cherry-pick
the good commits that they want to create, effectively re-creating the whole branch without the bad commit.
If they never pulled the bad commit, then this whole process won't affect them, and they can pull as normal.
npm config edit
Opens the config file in an editor. Use the --global flag to edit the global config. now you can delete what ever the registry's you don't want and save file.
npm config list will display the list of available now.
Apple mail has also been known to make an encoding error on text and csv attachments outbound. In essence it replaces line terminators with soft line breaks on each line, which look like =0D in the encoding. If the attachment is emailed to Outlook, Outlook sees the soft line breaks, removes the = then appends real line breaks i.e. 0D0A so you get 0D0D0A (cr cr lf) at the end of each line. The encoding should be =0D= if it is a mac format file (or any other flavour of unix) or =0D0A= if it is a windows format file.
If you are emailing out from apple mail (in at least mavericks or yosemite), making the attachment not a text or csv file is an acceptable workaround e.g. compress it.
The bug also exists if you are running a windows VM under parallels and email a txt file from there using apple mail. It is the email encoding. Form previous comments here, it looks like netscape had the same issue.
#include <algorithm> // std::search
#include <string>
using std::search; using std::count; using std::string;
int main() {
string mystring = "The needle in the haystack";
string str = "needle";
string::const_iterator it;
it = search(mystring.begin(), mystring.end(),
str.begin(), str.end()) != mystring.end();
// if string is found... returns iterator to str's first element in mystring
// if string is not found... returns iterator to mystring.end()
if (it != mystring.end())
// string is found
else
// not found
return 0;
}
You can use tojson
to convert each record to JSON in a MongoDB shell script.
Run this script in RoboMongo:
var cursor = db.getCollection('foo').find({}, {});
while(cursor.hasNext()) {
print(tojson(cursor.next()))
}
This prints all results as a JSON-like array.
The result is not really JSON! Some types, such as dates and object IDs, are printed as JavaScript function calls, e.g., ISODate("2016-03-03T12:15:49.996Z")
.
Might not be very efficient for large result sets, but you can limit the query. Alternatively, you can use mongoexport
.
I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was
const [favoriteFilms, setFavoriteFilms] = useState('');
I changed it to
const [favoriteFilms, setFavoriteFilms] = useState([]);
and the component that uses those values stopped throwing error with .map function.
If you are on SQL Server 2008 you can also use
CRYPT_GEN_RANDOM(2) % 10000
Which seems somewhat simpler (it is also evaluated once per row as newid
is - shown below)
DECLARE @foo TABLE (col1 FLOAT)
INSERT INTO @foo SELECT 1 UNION SELECT 2
UPDATE @foo
SET col1 = CRYPT_GEN_RANDOM(2) % 10000
SELECT * FROM @foo
Returns (2 random probably different numbers)
col1
----------------------
9693
8573
Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.
CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
BEGIN
DECLARE @Result INT
SET @Result = CRYPT_GEN_RANDOM(2)
RETURN CASE
WHEN @Result < 60000
OR @@NESTLEVEL = 32 THEN @Result % 10000
ELSE dbo.RandomNumber()
END
END
The best way to get good control over the colorbar position is to give it its own axis. Like so:
# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)
# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
cb = plt.colorbar(ax1, cax = cbaxes)
The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.
You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:
<?php
$filename = $_GET['file'];
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
exit;
} elseif ( ! file_exists( $filename ) )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
exit;
};
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
This is what I am going to use based on marc_s answer:
SELECT
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)
FROM WEBPAGECONTENT
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0
Return a substring on the search where the search criteria exists
Saving and Retriving data to - from Firebase ( deprecated ver 2.4.2 )
Firebase fb_parent = new Firebase("YOUR-FIREBASE-URL/");
Firebase fb_to_read = fb_parent.child("students/names");
Firebase fb_put_child = fb_to_read.push(); // REMEMBER THIS FOR PUSH METHOD
//INSERT DATA TO STUDENT - NAMES I Use Push Method
fb_put_child.setValue("Zacharia"); //OR fb_put_child.setValue(YOUR MODEL)
fb_put_child.setValue("Joseph"); //OR fb_put_child.setValue(YOUR MODEL)
fb_put_child.setValue("bla blaaa"); //OR fb_put_child.setValue(YOUR MODEL)
//GET DATA FROM FIREBASE INTO ARRAYLIST
fb_to_read.addValuesEventListener....{
public void onDataChange(DataSnapshot result){
List<String> lst = new ArrayList<String>(); // Result will be holded Here
for(DataSnapshot dsp : result.getChildren()){
lst.add(String.valueOf(dsp.getKey())); //add result into array list
}
//NOW YOU HAVE ARRAYLIST WHICH HOLD RESULTS
for(String data:lst){
Toast.make(context,data,Toast.LONG_LENGTH).show;
}
}
}
If you want to set the precision for all decimals
in EF6 you could replace the default DecimalPropertyConvention
convention used in the DbModelBuilder
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(38, 18));
}
The default DecimalPropertyConvention
in EF6 maps decimal
properties to decimal(18,2)
columns.
If you only want individual properties to have a specified precision then you can set the precision for the entity's property on the DbModelBuilder
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().Property(e => e.Value).HasPrecision(38, 18);
}
Or, add an EntityTypeConfiguration<>
for the entity which specifies the precision:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MyEntityConfiguration());
}
internal class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
internal MyEntityConfiguration()
{
this.Property(e => e.Value).HasPrecision(38, 18);
}
}
There is no way to automatically set CMAKE_PREFIX_PATH
in a way you want. I see following ways to solve this problem:
Put all libraries files in the same dir. That is, include/
would contain headers for all libs, lib/
- binaries, etc. FYI, this is common layout for most UNIX-like systems.
Set global environment variable CMAKE_PREFIX_PATH
to D:/develop/cmake/libs/libA;D:/develop/cmake/libs/libB;...
. When you run CMake, it would aautomatically pick up this env var and populate it's own CMAKE_PREFIX_PATH
.
Write a wrapper .bat script, which would call cmake
command with -D CMAKE_PREFIX_PATH=...
argument.
I would recommend the technique that MathieuK offers. In my case, I needed to try it with Chromium:
> Chromium.app/Contents/MacOS/Chromium --enable-remote-fonts
I realize this doesn't solve the OP's problem, but hopefully it saves someone else's time. :)
I had the same problem. I deleted the image emulator on the .android/avd folder and after I installed the lib32stdc++6:
sudo apt-get install lib32stdc++6
So, it works! Magic?
Simply throw Exception if input is invalid
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Please input an integer");
//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("This is not an integer");
}
To get records from the last 24 hours:
SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
In C and C++ and many languages, %
is the remainder NOT the modulus operator.
For example in the operation -21 / 4
the integer part is -5
and the decimal part is -.25
. The remainder is the fractional part times the divisor, so our remainder is -1
. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
_x000D_
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.
try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.
The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.
I faced similar issue when the SDK tools installation was failed during the initial setup. To resolution is to download SDK tools from Android Developer Site
The following should work for any struct type. It is based off code by Matt Manela from MSDN forums. As Murph points out the exception handling could be expensive compared to using the Types dedicated TryParse method.
public static bool TryParseStruct<T>(this string value, out Nullable<T> result)
where T: struct
{
if (string.IsNullOrEmpty(value))
{
result = new Nullable<T>();
return true;
}
result = default(T);
try
{
IConvertible convertibleString = (IConvertible)value;
result = new Nullable<T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));
}
catch(InvalidCastException)
{
return false;
}
catch (FormatException)
{
return false;
}
return true;
}
These were the basic test cases I used.
string parseOne = "1";
int? resultOne;
bool successOne = parseOne.TryParseStruct<int>(out resultOne);
Assert.IsTrue(successOne);
Assert.AreEqual(1, resultOne);
string parseEmpty = string.Empty;
int? resultEmpty;
bool successEmpty = parseEmpty.TryParseStruct<int>(out resultEmpty);
Assert.IsTrue(successEmpty);
Assert.IsFalse(resultEmpty.HasValue);
string parseNull = null;
int? resultNull;
bool successNull = parseNull.TryParseStruct<int>(out resultNull);
Assert.IsTrue(successNull);
Assert.IsFalse(resultNull.HasValue);
string parseInvalid = "FooBar";
int? resultInvalid;
bool successInvalid = parseInvalid.TryParseStruct<int>(out resultInvalid);
Assert.IsFalse(successInvalid);
date +%s%N
returns the number of seconds + current nanoseconds.
Therefore, echo $(($(date +%s%N)/1000000))
is what you need.
Example:
$ echo $(($(date +%s%N)/1000000))
1535546718115
date +%s
returns the number of seconds since the epoch, if that's useful.
It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:
from __future__ import print_function # In python 2.7
import sys
@app.route('/button/')
def button_clicked():
print('Hello world!', file=sys.stderr)
return redirect('/')
Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post
The :query_string_normalizer
option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
in Netbeans 7.4 try Window -> Output OR Ctrl + 4
If you got the same error in Sql server 2008 management studio than below link will resolve this error after so much effort i found this link: http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/
Use bellow command from CLI interface
[root@localhost~]# mysqladmin variables -p<password> | grep datadir
this is the code i use it but your apps must run with net version 3.5
private void txtRead_Click(object sender, EventArgs e)
{
// var filename = @"d:\shiptest.txt";
openFileDialog1.InitialDirectory = "d:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
if (openFileDialog1.FileName != "")
{
var reader = ReadAsLines(openFileDialog1.FileName);
var data = new DataTable();
//this assume the first record is filled with the column names
var headers = reader.First().Split(',');
foreach (var header in headers)
{
data.Columns.Add(header);
}
var records = reader.Skip(1);
foreach (var record in records)
{
data.Rows.Add(record.Split(','));
}
dgList.DataSource = data;
}
}
}
static IEnumerable<string> ReadAsLines(string filename)
{
using (StreamReader reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
-XX:PermSize -XX:MaxPermSize
are used to set size for Permanent Generation.
Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.
YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
if(window.frames[0].window.confirm("Are you sure?")){
// what to do if answer "YES"
}else{
// what to do if answer "NO"
}
Enjoy it!
If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.
Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings
and Settings.Designer.settings
that contain the singleton class Settings
inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
This technique is applicable both for console, Windows Forms, and other project types.
Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.
Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs
Quotes!
if [ "$1" != -v ]; then
Otherwise, when $1
is completely empty, your test becomes:
[ != -v ]
instead of
[ "" != -v ]
...and !=
is not a unary operator (that is, one capable of taking only a single argument).
OK let's inspect some code.
File.java
lines 428 to 435 in File.<init>
:
String p = uri.getPath();
if (p.equals(""))
throw new IllegalArgumentException("URI path component is empty");
// Okay, now initialize
p = fs.fromURIPath(p);
if (File.separatorChar != '/')
p = p.replace('/', File.separatorChar);
And let's read fs/*(FileSystem)*/.fromURIPath()
docs:
java.io.FileSystem
public abstract String fromURIPath(String path)
Post-process the given URI path string if necessary. This is used on win32, e.g., to transform "/c:/foo" into "c:/foo". The path string still has slash separators; code in the File class will translate them after this method returns.
This means FileSystem.fromURIPath()
does post processing on URI path only in Windows, and because in the next line:
p = p.replace('/', File.separatorChar);
It replaces each '/' with system dependent seperatorChar
, you can always be sure that '/' is safe in every OS.
edit your ~/.vimrc
$ vim ~/.vimrc
add following lines :
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
Java8
Stream.of(Direction.values()).forEach(System.out::println);
from Java5+
for ( Direction d: Direction.values()){
System.out.println(d);
}
SetForegroundWindow( /* window to gain focus */ );
SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.
There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .
The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.
Here're the themes:
styles.xml
<style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowShowWallpaper">true</item>
</style>
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
</style>
<style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
<item name="android:displayOptions">showCustom</item>
<item name="android:background">#88000000</item>
</style>
value-v19/styles.xml
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:
getSupportActionBar().setDisplayShowCustomEnabled(true);
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
From Bootstrap's docs about the remote
option;
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
If a remote URL is provided, content will be loaded one time via jQuery's
load
method and injected into the.modal-content
div. If you're using the data-api, you may alternatively use thehref
attribute to specify the remote source. An example of this is shown below:<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>
That's the .modal-content
div, not .modal-body
. If you want to put content inside .modal-body
then you need to do that with custom javascript.
So I would call jQuery.load
programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.
To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal
event to load content into the .modal-body
div.
HTML Link/Button
<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>
jQuery
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
You can use Dialog to create this easily
create a Dialog instance using the context
Dialog dialog = new Dialog(contex);
You can design your layout as you like.
You can add this layout to your dialog by
dialog.setContentView(R.layout.popupview);//popup view is the layout you created
then you can access its content (textviews, etc.) by using findViewById
method
TextView txt = (TextView)dialog.findViewById(R.id.textbox);
you can add any text here. the text can be stored in the String.xml file in res\values.
txt.setText(getString(R.string.message));
then finally show the pop up menu
dialog.show();
more information http://developer.android.com/guide/topics/ui/dialogs.html
http://developer.android.com/reference/android/app/Dialog.html
One main difference is the Local
part of LocalDateTime
. If you live in Germany and create a LocalDateTime
instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant
, which is calculated independently from time zone.
LocalDateTime
stores date and time without timezone, but it's initial value is timezone dependent. Instant
's is not.
Moreover, LocalDateTime
provides methods for manipulating date components like days, hours, months. An Instant
does not.
apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime
Both classes have the same precision. LocalDateTime
does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.
For delphi 2010, you need to create your own split function.
function Split(const Texto, Delimitador: string): TStringArray;
var
i: integer;
Len: integer;
PosStart: integer;
PosDel: integer;
TempText:string;
begin
i := 0;
SetLength(Result, 1);
Len := Length(Delimitador);
PosStart := 1;
PosDel := Pos(Delimitador, Texto);
TempText:= Texto;
while PosDel > 0 do
begin
Result[i] := Copy(TempText, PosStart, PosDel - PosStart);
PosStart := PosDel + Len;
TempText:=Copy(TempText, PosStart, Length(TempText));
PosDel := Pos(Delimitador, TempText);
PosStart := 1;
inc(i);
SetLength(Result, i + 1);
end;
Result[i] := Copy(TempText, PosStart, Length(TempText));
end;
You can refer to it as such
type
TStringArray = array of string;
var Temp2:TStringArray;
Temp1="hello:world";
Temp2=Split(Temp1,':')
This will grab records with strings (in the fieldName column) that are 10 characters long:
select * from table where length(fieldName)=10
the solution is easy: execute via sh
... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;
Absolutely.
If the constructor doesn't receive valid input, or can't construct the object in a valid manner, it has no other option but to throw an exception and alert its caller.
This question is very useful in practice. It's only necessary to list every explicit columns in software programming, where you pay particular careful to deal with all conditions.
Imagine when debugging, or, try to use DBMS as daily office tool, instead of something alterable implementation of specific programmer's abstract underlying infrastructure, we need to code a lot of SQLs. The scenario can be found everywhere, like database conversion, migration, administration, etc. Most of these SQLs will be executed only once and never be used again, give the every column names is just waste of time. And don't forget the invention of SQL isn't only for the programmers use.
Usually I will create a utility view with column names prefixed, here is the function in pl/pgsql, it's not easy but you can convert it to other procedure languages.
-- Create alias-view for specific table.
create or replace function mkaview(schema varchar, tab varchar, prefix varchar)
returns table(orig varchar, alias varchar) as $$
declare
qtab varchar;
qview varchar;
qcol varchar;
qacol varchar;
v record;
sql varchar;
len int;
begin
qtab := '"' || schema || '"."' || tab || '"';
qview := '"' || schema || '"."av' || prefix || tab || '"';
sql := 'create view ' || qview || ' as select';
for v in select * from information_schema.columns
where table_schema = schema and table_name = tab
loop
qcol := '"' || v.column_name || '"';
qacol := '"' || prefix || v.column_name || '"';
sql := sql || ' ' || qcol || ' as ' || qacol;
sql := sql || ', ';
return query select qcol::varchar, qacol::varchar;
end loop;
len := length(sql);
sql := left(sql, len - 2); -- trim the trailing ', '.
sql := sql || ' from ' || qtab;
raise info 'Execute SQL: %', sql;
execute sql;
end
$$ language plpgsql;
Examples:
-- This will create a view "avp_person" with "p_" prefix to all column names.
select * from mkaview('public', 'person', 'p_');
select * from avp_person;
Use the same function (cor
) on a data frame, e.g.:
> cor(VADeaths)
Rural Male Rural Female Urban Male Urban Female
Rural Male 1.0000000 0.9979869 0.9841907 0.9934646
Rural Female 0.9979869 1.0000000 0.9739053 0.9867310
Urban Male 0.9841907 0.9739053 1.0000000 0.9918262
Urban Female 0.9934646 0.9867310 0.9918262 1.0000000
Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:
> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
mpg cyl disp hp drat wt qsec vs am gear carb
mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.6640389 -0.8108118 -0.7104159 -0.7230967 0.44027846 -0.5549157 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953 -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870 -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059 -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
Laravel 4.2 and beyond, may use try relationship querying:-
Products::whereHas('product_category', function($query) {
$query->whereIn('category_id', ['223', '15']);
});
public function product_category() {
return $this->hasMany('product_category', 'product_id');
}
I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop()
all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.
I become frustrated trying to implement something that looked consistent in all browsers and went with an svg button which can be styled with css.
html
<svg>
<circle cx="12" cy="12" r="11" stroke="black" stroke-width="2" fill="white" />
<path stroke="black" stroke-width="4" fill="none" d="M6.25,6.25,17.75,17.75" />
<path stroke="black" stroke-width="4" fill="none" d="M6.25,17.75,17.75,6.25" />
</svg>
css
svg {
cursor: pointer;
height: 24px;
width: 24px;
}
svg > circle {
stroke: black;
fill: white;
}
svg > path {
stroke: black;
}
svg:hover > circle {
fill: red;
}
svg:hover > path {
stroke: white;
}
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
Need to replace
.setJSMainModulePath("index") with .setJSMainModulePath("index.android")
Just ad this in the select :
DATE_FORMAT($yourDate, \'%X %V\') as week
And
group_by(week);
Instead of configuring Tomcat to redirect requests, use Apache as a frontend with the Apache Tomcat connector so that Apache is only serving static content, while asking tomcat for dynamic content.
Using the JKmount directive (or others) you could specify exactly which requests are sent to Tomcat.
Requests for static content, such as images, would be served directly by Apache, using a standard virtual host configuration, while other requests, defined in the JKMount directive will be sent to Tomcat workers.
I think this implementation would give you the most flexibility and control on the overall application.
In my case I was throwing Exception
on a namespaced file, so php tried to catch My\Namespace\Exception
therefore not catching any exceptions at all.
Worth checking if catch (Exception $e)
is finding the right Exception
class.
Just try catch (\Exception $e)
(with that \
there) and see if it works.
You can also use the Uri class.
new Uri("file:///Users/smcho/filegen_from_directory/AIRPassthrough").Segments.Last()
You may prefer to use this class if you want to get some other segment, or if you want to do the same thing with a web address.
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
To align the text in the proper format -
Ctrl + K + D for front end pages like .aspx
or .cshtml
Ctrl + K + F for a .cs
page
But observe to press all buttons in sequence...
git pull
= git fetch
+ git merge origin/branch
git pull
and git pull origin branch
only differ in that the latter will only "update" origin/branch and not all origin/* as git pull
does.
git pull origin/branch
will just not work because it's trying to do a git fetch origin/branch
which is invalid.
Question related: git fetch + git merge origin/master vs git pull origin/master
Here is worker like this. \o/
- name: "Exec items"
shell: "{{ item }}"
with_items:
- echo "hello"
- echo "hello2"
In my case, it was unable to find the .eslintrc
file so I copied from node_modules/.bin to root.
After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"
example of adding (compile 'io.reactivex:rxjava:1.1.0'):
If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}
Facelets is a XML based view technology. The &
is a special character in XML representing the start of an entity like &
which ends with the ;
character. You'd need to either escape it, which is ugly:
rendered="#{beanA.prompt == true && beanB.currentBase != null}"
or to use the and
keyword instead, which is preferred as to readability and maintainability:
rendered="#{beanA.prompt == true and beanB.currentBase != null}"
Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true
:
rendered="#{beanA.prompt and beanB.currentBase != null}"
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())
I had this problem with this kind of simple form:
public partial class MyForm : Form
{
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
}
internal void UpdateLabel(string s)
{
Invoke(new Action(() => { label1.Text = s; }));
}
}
Then for n
other async threads I was using new MyForm().UpdateLabel(text)
to try and call the UI thread, but the constructor gives no handle to the UI thread instance, so other threads get other instance handles, which are either Object reference not set to an instance of an object
or Invoke or BeginInvoke cannot be called on a control until the window handle has been created
. To solve this I used a static object to hold the UI handle:
public partial class MyForm : Form
{
private static MyForm _mf;
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
_mf = this;
}
internal void UpdateLabel(string s)
{
_mf.Invoke((MethodInvoker) delegate { _mf.label1.Text = s; });
}
}
I guess it's working fine, so far...
Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:
HTML
<table id="HelpdeskOverview">
<thead>
<tr>
<th>Ärende</th>
<th>Rapporterad</th>
<th>Syst/Utr/Appl</th>
<th>Prio</th>
<th>Rubrik</th>
<th>Status</th>
<th>Ägare</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Javascript
function InitOverviewDataTable()
{
oOverviewTable =$('#HelpdeskOverview').dataTable(
{
"bPaginate": true,
"bJQueryUI": true, // ThemeRoller-stöd
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bInfo": true,
"bAutoWidth": true,
"bProcessing": true,
"iDisplayLength": 10,
"sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
});
}
function RefreshTable(tableId, urlData)
{
$.getJSON(urlData, null, function( json )
{
table = $(tableId).dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
function AutoReload()
{
RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');
setTimeout(function(){AutoReload();}, 30000);
}
$(document).ready(function () {
InitOverviewDataTable();
setTimeout(function(){AutoReload();}, 30000);
});
If you use struct
without typedef
, you'll always have to write
struct mystruct myvar;
It's illegal to write
mystruct myvar;
If you use the typedef
you don't need the struct
prefix anymore.
The Objective-C type you should use is BOOL
. There is nothing like a native boolean datatype, therefore to be sure that the code compiles on all compilers use BOOL
. (It's defined in the Apple-Frameworks.
Also websocket scope is added:
Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
As the per the content of the documentation, there is also thread scope, that is not registered by default.
Ok here's how I fixed this
My model is a list
of categories. Each category contains a list
of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton
will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton
instead of Html.RadioButtonFor
.
Here's the final 'working' pseudo-code:
@foreach (var cat in Model.Categories)
{
//A piece of code & html here
@foreach (var item in cat.SubCategories)
{
@Html.RadioButton(item.CategoryID.ToString(), item.ID)
}
}
The result is:
<input name="127" type="radio" value="110">
Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.
Thanks to all of the people who helped me solve this ;)
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
I can confirm that there is no XPath support within Beautiful Soup.
IF EXISTS(SELECT * FROM service s WHERE s.service_id = ?)
BEGIN
--DO STUFF HERE
END
You don't need to copy a Python string. They are immutable, and the copy
module always returns the original in such cases, as do str()
, the whole string slice, and concatenating with an empty string.
Moreover, your 'hello'
string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.
One way you could work around this is to actually create a new string, then slice that string back to the original content:
>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)
But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.
If all you wanted to know is how much memory a Python object requires, use sys.getsizeof()
; it gives you the memory footprint of any Python object.
For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:
>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360
You can then choose to use id()
tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.
Question 1: Use .delegate
on the div to bind a click handler to the button.
Question 2: Use $(this).val()
or this.value
(the latter would be faster) inside of the click handler. this
will refer to the button.
$("#pg_menu_content").on('click', '#btn_a', function () {
alert($(this).val());
});
$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');
jveitchmichaelis at https://github.com/ContinuumIO/anaconda-issues/issues/223 provided a thorough answer. Here I copied his answer:
The documentation in OpenCV says (hidden away) that you can only write to avi using OpenCV3. Whether that's true or not I've not been able to determine, but I've been unable to write to anything else.
However, OpenCV is mainly a computer vision library, not a video stream, codec and write one. Therefore, the developers tried to keep this part as simple as possible. Due to this OpenCV for video containers supports only the avi extension, its first version.
From: http://docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html
My setup: I built OpenCV 3 from source using MSVC 2015, including ffmpeg. I've also downloaded and installed XVID and openh264 from Cisco, which I added to my PATH. I'm running Anaconda Python 3. I also downloaded a recent build of ffmpeg and added the bin folder to my path, though that shouldn't make a difference as its baked into OpenCV.
I'm running in Win 10 64-bit.
This code seems to work fine on my computer. It will generate a video containing random static:
writer = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480)) for frame in range(1000): writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8')) writer.release()
Some things I've learned through trial and error:
- Only use '.avi', it's just a container, the codec is the important thing.
Be careful with specifying frame sizes. In the constructor you need to pass the frame size as (column, row) e.g. 640x480. However the array you pass in, is indexed as (row, column). See in the above example how it's switched?
If your input image has a different size to the VideoWriter, it will fail (often silently)
- Only pass in 8 bit images, manually cast your arrays if you have to (.astype('uint8'))
- In fact, never mind, just always cast. Even if you load in images using cv2.imread, you need to cast to uint8...
- MJPG will fail if you don't pass in a 3 channel, 8-bit image. I get an assertion failure for this at least.
- XVID also requires a 3 channel image but fails silently if you don't do this.
- H264 seems to be fine with a single channel image
- If you need raw output, say from a machine vision camera, you can use 'DIB '. 'RAW ' or an empty codec sometimes works. Oddly if I use DIB, I get an ffmpeg error, but the video is saved fine. If I use RAW, there isn't an error, but Windows Video player won't open it. All are fine in VLC.
In the end I think the key point is that OpenCV is not designed to be a video capture library - it doesn't even support sound. VideoWriter is useful, but 99% of the time you're better off saving all your images into a folder and using ffmpeg to turn them into a useful video.
To Convert BEGIN OPENSSH PRIVATE KEY
to BEGIN RSA PRIVATE KEY
:
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa
if put 'http_errors' => false
in guzzle request options, then it would stop throw exception while get 4xx or 5xx error, like this: $client->get(url, ['http_errors' => false])
. then you parse the response, not matter it's ok or error, it would be in the response
for more info
Mobile browsers generally ignore this attribute to prevent consuming data until user explicitly starts the download.
UPDATE: newer version of mobile browser on Android and iOS do support autoplay function. But it only works if the video is muted or has no audio channel:
Some additional info: https://webkit.org/blog/6784/new-video-policies-for-ios/
In a question tagged 'bash' that explicitly has "in Bash" in the title, I'm a little surprised by all of the replies saying you should avoid [[
...]]
because it only works in bash!
It's true that portability is the primary objection: if you want to write a shell script which works in Bourne-compatible shells even if they aren't bash, you should avoid [[
...]]
. (And if you want to test your shell scripts in a more strictly POSIX shell, I recommend dash
; though it is an incomplete POSIX implementation since it lacks the internationalization support required by the standard, it also lacks support for the many non-POSIX constructs found in bash, ksh, zsh, etc.)
The other objection I see is at least applicable within the assumption of bash: that [[
...]]
has its own special rules which you have to learn, while [
...]
acts like just another command. That is again true (and Mr. Santilli brought the receipts showing all the differences), but it's rather subjective whether the differences are good or bad. I personally find it freeing that the double-bracket construct lets me use (
...)
for grouping, &&
and ||
for Boolean logic, <
and >
for comparison, and unquoted parameter expansions. It's like its own little closed-off world where expressions work more like they do in traditional, non-command-shell programming languages.
A point I haven't seen raised is that this behavior of [[
...]]
is entirely consistent with that of the arithmetic expansion construct $((
...))
, which is specified by POSIX, and also allows unquoted parentheses and Boolean and inequality operators (which here perform numeric instead of lexical comparisons). Essentially, any time you see the doubled bracket characters you get the same quote-shielding effect.
(Bash and its modern relatives also use ((
...))
– without the leading $
– as either a C-style for
loop header or an environment for performing arithmetic operations; neither syntax is part of POSIX.)
So there are some good reasons to prefer [[
...]]
; there are also reasons to avoid it, which may or may not be applicable in your environment. As to your coworker, "our style guide says so" is a valid justification, as far as it goes, but I'd also seek out backstory from someone who understands why the style guide recommends what it does.
Just call Math.abs. For example:
int x = Math.abs(-5);
Which will set x
to 5
.
Note that if you pass Integer.MIN_VALUE
, the same value (still negative) will be returned, as the range of int
does not allow the positive equivalent to be represented.
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
I had a problem with this. I didn't even create any passwords so I was confused. I googled it and I found out that I should just write root as username and than click GO. I hope it helps.
For those who are still frustrated, if you are using the experimental ART runtime, try switching back to dalvik (in developer options on device)
These commands worked for Artik 10 :
and these others didn't :
I use this function in all my js projects
You call it: hideAndResetModals("#IdModalDialog")
You define if:
function hideAndResetModals(modalID)
{
$(modalID).modal('hide');
clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
$(modalID).on('hidden.bs.modal', function ()
{
$(modalID).find('form').trigger('reset');
});
}
Mike's answer is working good until you are using the "re-use" bind value.
For example:
SELECT * FROM `an_modules` AS `m` LEFT JOIN `an_module_sites` AS `ms` ON m.module_id = ms.module_id WHERE 1 AND `module_enable` = :module_enable AND `site_id` = :site_id AND (`module_system_name` LIKE :search OR `module_version` LIKE :search)
The Mike's answer can only replace first :search but not the second.
So, I rewrite his answer to work with multiple parameters that can re-used properly.
public function interpolateQuery($query, $params) {
$keys = array();
$values = $params;
$values_limit = [];
$words_repeated = array_count_values(str_word_count($query, 1, ':_'));
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
$values_limit[$key] = (isset($words_repeated[':'.$key]) ? intval($words_repeated[':'.$key]) : 1);
} else {
$keys[] = '/[?]/';
$values_limit = [];
}
if (is_string($value))
$values[$key] = "'" . $value . "'";
if (is_array($value))
$values[$key] = "'" . implode("','", $value) . "'";
if (is_null($value))
$values[$key] = 'NULL';
}
if (is_array($values)) {
foreach ($values as $key => $val) {
if (isset($values_limit[$key])) {
$query = preg_replace(['/:'.$key.'/'], [$val], $query, $values_limit[$key], $count);
} else {
$query = preg_replace(['/:'.$key.'/'], [$val], $query, 1, $count);
}
}
unset($key, $val);
} else {
$query = preg_replace($keys, $values, $query, 1, $count);
}
unset($keys, $values, $values_limit, $words_repeated);
return $query;
}
Something like this should do the trick
<select id="leave" onchange="leaveChange()">
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
<div id="message"></div>
Javascript
function leaveChange() {
if (document.getElementById("leave").value != "100"){
document.getElementById("message").innerHTML = "Common message";
}
else{
document.getElementById("message").innerHTML = "Having a Baby!!";
}
}
A shorter version and more general could be
HTML
<select id="leave" onchange="leaveChange(this)">
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
Javascript
function leaveChange(control) {
var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
document.getElementById("message").innerHTML = msg;
}
simple one:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
if you have many STRINGS to Concatenate, you should use NSMutableString
for better performance
Also, a bit simpler....
>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]
Go to Project pane> Android > Gradle Scripts and open "graddle-wrapper.properties" file check the distribution URL:
Go to your ".gradle/wrapper/dists/" folder and remove that file for me it was "gradle-5.6.4-all"
Then go back to android studio and click on File > Sync Project with Gradle Files. And it will start to download again
The problem might be your split()
call. Try just split(" ")
without the square brackets.
The following POSIX program will print the names of the files in the current directory:
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
Tested in Ubuntu 16.04.
Here is the solution without scripting and no external jars like ant-conrib:
The trick is to use ANT's resources:
<loadresource property="propB">
<propertyresource name="propA"/>
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from=" " to="_"/>
</tokenfilter>
</filterchain>
</loadresource>
This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.
You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
I would do this
var myDateStr= new Date("2015/5/2");
if( ! isNaN ( myDateStr.getMonth() )) {
console.log("Valid date");
}
else {
console.log("Invalid date");
}
Play here
Try this....
ul.list-group li {
padding-left: 13px;
position: relative;
}
ul.list-group li:before {
left: 0 !important;
position: absolute;
}
You don't need a counter for back presses.
Just store a reference to the toast that is shown:
private Toast backtoast;
Then,
public void onBackPressed() {
if(USER_IS_GOING_TO_EXIT) {
if(backtoast!=null&&backtoast.getView().getWindowToken()!=null) {
finish();
} else {
backtoast = Toast.makeText(this, "Press back to exit", Toast.LENGTH_SHORT);
backtoast.show();
}
} else {
//other stuff...
super.onBackPressed();
}
}
This will call finish()
if you press back while the toast is still visible, and only if the back press would result in exiting the application.
Angular ui-router supports nested views. I haven't used it yet but looks very promising.
More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.
In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.
You pick what matters the most to you.
Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.
You could move the common parts to another configuration file and include
from both server contexts. This should work:
server {
listen 80;
server_name server1.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
server {
listen 80;
server_name another-one.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled
(normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org
's configuration file is /etc/nginx/sites-enabled
and it looks like this:
server {
listen 80 default_server;
listen [2a01:4f8:120:3105::101:1]:80 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-80;
}
server {
listen 443 default_server;
listen [2a01:4f8:120:3105::101:1]:443 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/ssl-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-443;
}
As an example here's the /etc/nginx/include.d/all-common
file that's included from both server
contexts:
index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;
location ~ /\.ht {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location ~ /(README|ChangeLog)$ {
types { }
default_type text/plain;
}
To put it analogously to SQL "Pandas merge is to outer/inner join and Pandas join is to natural join". Hence when you use merge in pandas, you want to specify which kind of sqlish join you want to use whereas when you use pandas join, you really want to have a matching column label to ensure it joins
I found this to work very well, but initially I have my textboxes on a panel so none of my textboxes cleared as expected so I added
this.panel1.Controls.....
Which got me to thinking that is you have lots of textboxes for different functions and only some need to be cleared out, perhaps using the multiple panel hierarchies you can target just a few and not all.
foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
..
}
Light red fill with dark red text.
{'bg_color': '#FFC7CE', 'font_color': '#9C0006'})
Light yellow fill with dark yellow text.
{'bg_color': '#FFEB9C', 'font_color': '#9C6500'})
Green fill with dark green text.
{'bg_color': '#C6EFCE', 'font_color': '#006100'})
You can wrap it in another class which knows the type of your generic type.
Eg,
class Wrapper {
private Data<Something> data;
}
mapper.readValue(jsonString, Wrapper.class);
Here Something is a concrete type. You need a wrapper per reified type. Otherwise Jackson does not know what objects to create.
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.
the lib of apache-httpcomponents
// ipv4 is true
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
// not detect the ipv6
assertFalse(InetAddressUtils.isIPv4Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
maven lib (update Sep, 2019)
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
The wizard likely created the package as a file. Do a search on your system for files with an extension of .dtsx. This is the actual "SSIS Package" file.
As for loading it in Management Studio, you don't actually view it through there. If you have SQL Server 2005 loaded on your machine, look in the program group. You should find an application with the same icon as Visual Studio called "SQL Server Business Intelligence Development Studio". It's basically a stripped down version of VS 2005 which allows you to create SSIS packages.
Create a blank solution and add your .dtsx file to that to edit/view it.
I'm using visual studio 2015 and the solutions given above didn't work for me, so i did the following:
Delete the packages folder from my solution and also bin and obj folders from every project in the solution and give it a rebuild.
Maybe you will have the next error:
unable to locate nuget.exe
To solve this: Change this line in your NuGet.targets file and setting it to true:
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe>
Reference:https://stackoverflow.com/a/30918648 and https://stackoverflow.com/a/20502049
Alternatively you can register a call back delegate which ignores the certification error:
...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...
static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-"
for a red line, or by explicitely stating the color
argument.
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line
plt.show()
See also the plot command's documentation.
In case you already have a line with a certain color, you can change that with the lines2D.set_color()
method.
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line
plt.show()
If you want to change this color later on, you can do so by
plt.gca().get_lines()[0].set_color("black")
This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them
for ax in plt.gcf().axes:
ax.get_lines()[0].set_color("black")
and if you have more lines you can loop over them as well.
Truth be told there are many, many resources explaining how to do this already out on the web:
Git: how to reverse-merge a commit?
Git: how to reverse-merge a commit?
Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)
So I guess I'll just summarize some of these:
git revert <merge commit hash>
This creates an extra "revert" commit saying you undid a merge
git reset --hard <commit hash *before* the merge>
This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick
them on to afterwards.
But honestly this guide here is better than anything I can explain, with diagrams! :)
Not sure it is a "proper" way to "do things".
If there's no API way to resolve the (or a) question than you should think a little, maybe you're doing something wrong and read more docs instead etc.
(As I understood static variables is a commonly wrong way in android. Of cause it could work, but there definitely will be cases when it wont work[for example, in production, on million devices]).
Exactly in your case I suggest to think why do you need to know if another activity is alive?.. you can start another activity for result to get its functionality. Or you can derive the class to obtain its functionality and so on.
Best Regards.
None of those will do any extra copying. Even if RVO isn't used, the new standard says that move construction is preferred to copy when doing returns I believe.
I do believe that your second example causes undefined behavior though because you're returning a reference to a local variable.
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()
var validator = $( "#myform" ).validate();
validator.form();
If myString contains an account number that begins at offset 6 and has length 9, then you can extract the account number this way: acct = myString[6:][:9]
.
If the OP accepts that, they might want to try, in an experimental fashion,
myString[2:][:999999]
It works - no error is raised, and no default 'string padding' occurs.
For remove in NestJS need to add option to Shema() decorator
@Schema({ versionKey: false })
I had same issue at the last half hour...
Was not able to delete a zombie build running in my multi-branch pipeline.
Even Server restarts by UI or even from commandline via sudo service jenkins restart
did block the execution... The build was not stoppable... It always reapeared.
Used Version: Jenkins ver 2.150.2
I was very annoyed, but... when looking into the log of the build I found something intersting at the end of the log:
The red marked parts are the "frustrating parts"... As you can see I always wanted to Abort the build from UI but it did not work...
But there is a hyperlink with text Click here to forcibly terminate running steps
...(first green one)
Now I pressed the link...)
After the link execution a message about Still paused
appeared with another Link Click
here to forcibily kill entire build
(second green one)
After pressing this link also the build finally was hard killed...
So this seems to work without any special plugins (except the multibranch-pipeline build plugin itself).
Using detach is magnitudes faster than any of the other answers here:
$('#mytable').find('tbody').detach();
Don't forget to put the tbody element back into the table since detach removed it:
$('#mytable').append($('<tbody>'));
Also note that when talking efficiency $(target).find(child)
syntax is faster than $(target > child)
. Why? Sizzle!
Elapsed Time to Empty 3,161 Table Rows
Using the Detach() method (as shown in my example above):
Using the empty() method:
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
Had the same problem. Found this in the docker documentation:
Note: The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.
So, mounting a read/write host directory is only possible with the -v
parameter in the docker run
command, as the other answers point out correctly.
The compile()
method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int)
to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher()
method, and the only way to get ahold of the Pattern object is through the compile()
method. Then there's the find()
method which, unlike matches()
, is not duplicated in the String or Pattern classes.
The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches()
method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:
for (String s : myStringList) {
if ( s.matches("\\d+") ) {
doSomething();
}
}
...is exactly equivalent to this:
for (String s : myStringList) {
if ( Pattern.compile("\\d+").matcher(s).matches() ) {
doSomething();
}
}
Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
if ( m.reset(s).matches() ) {
doSomething();
}
}
If you're familiar with .NET regexes, you may be wondering if Java's compile()
method is related to .NET's RegexOptions.Compiled
modifier; the answer is no. Java's Pattern.compile()
method is merely equivalent to .NET's Regex constructor. When you specify the Compiled
option:
Regex r = new Regex(@"\d+", RegexOptions.Compiled);
...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String)
and one you create explicitly with Pattern#compile(String)
.
(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches()
, not when you call a Regex constructor directly. ref)
A .o object file file (also .obj on Windows) contains compiled object code (that is, machine code produced by your C or C++ compiler), together with the names of the functions and other objects the file contains. Object files are processed by the linker to produce the final executable. If your build process has not produced these files, there is probably something wrong with your makefile/project files.
Here is my combined solution for various PHP versions.
In my company we are working with different servers with various PHP versions, so I had to find solution working for all.
$phpVersion = substr(phpversion(), 0, 3)*1;
if($phpVersion >= 5.4) {
$encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
$encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}
Credits should go to Marco Gasi & abu. The solution for PHP >= 5.4 is provided in the json_encode docs.
Roughly you can have 3 choices to display RTSP video stream in a web page:
You can find the code to embed the activeX via google search.
As far as I know, there are some limitations for each player.
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
You should use the following:
<td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>
You will need to add the FormsModule
to your app.module
in the inputs
section as follows:
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule
],
..
The use of the brackets around the ngModel
are as follows:
The []
show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.
The ()
show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.
The [()]
are both (e.g. a two way binding)
See here for more information: https://angular.io/guide/template-syntax
I would also suggest replacing id="priceInput-{{orderLine.id}}"
with something like this [id]="getElementId(orderLine)"
where getElementId(orderLine)
returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1
in one place and priceInput-1
in another. (if you still need to access the input by it's Id somewhere else)
As explained in the different asnwers already, sys.argv
contains the command line arguments that called your Python script.
However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse
would spare you the need to write a lot of boilerplate code.
There is no reason not to use C <stdio.h>
in C++, and in fact it is often the optimal choice.
#include <stdio.h>
int
main() // (void) not necessary in C++
{
int c;
while ((c = getchar()) != EOF) {
// do something with 'c' here
}
return 0; // technically not necessary in C++ but still good style
}
2014 While
is back
Just think logical.
Look at this
for( var index = 0 , length = array.length ; index < length ; index++ ) {
//do stuff
}
for
loop has 3 parametersNow tell me why this should be faster than:
var length = array.length;
while( --length ) { //or length--
//do stuff
}
while
has only one parameterI was totally confused when Chrome 28 showed that the for loop is faster than the while. This must have ben some sort of
"Uh, everyone is using the for loop, let's focus on that when developing for chrome."
But now, in 2014 the while loop is back on chrome. it's 2 times faster , on other/older browsers it was always faster.
Lately i made some new tests. Now in real world envoirement those short codes are worth nothing and jsperf can't actually execute properly the while loop, because it needs to recreate the array.length which also takes time.
you CAN'T get the actual speed of a while loop on jsperf.
you need to create your own custom function and check that with window.performance.now()
And yeah... there is no way the while loop is simply faster.
The real problem is actually the dom manipulation / rendering time / drawing time or however you wanna call it.
For example i have a canvas scene where i need to calculate the coordinates and collisions... this is done between 10-200 MicroSeconds (not milliseconds). it actually takes various milliseconds to render everything.Same as in DOM.
BUT
There is another super performant way using the for loop
in some cases... for example to copy/clone an array
for(
var i = array.length ;
i > 0 ;
arrayCopy[ --i ] = array[ i ] // doing stuff
);
Notice the setup of the parameters:
Said that, this confirms that machines like the --
writing that i was thinking to make it a little shorter and remove some useless stuff and wrote this one using the same style:
for(
var i = array.length ;
i-- ;
arrayCopy[ i ] = array[ i ] // doing stuff
);
Even if it's shorter it looks like using i
one more time slows down everything.
It's 1/5 slower than the previous for
loop and the while
one.
Note: the ;
is very important after the for looo without {}
Even if i just told you that jsperf is not the best way to test scripts .. i added this 2 loops here
http://jsperf.com/caching-array-length/40
And here is another answer about performance in javascript
https://stackoverflow.com/a/21353032/2450730
This answer is to show performant ways of writing javascript. So if you can't read that, ask and you will get an answer or read a book about javascript http://www.ecma-international.org/ecma-262/5.1/
Empty-ness and "NULL-ness" are two different concepts. As others mentioned the former can be achieved via std::string::empty()
, the latter can be achieved with boost::optional<std::string>
, e.g.:
boost::optional<string> myStr;
if (myStr) { // myStr != NULL
// ...
}
FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).
For more information try this link.
I'v been used following code in IE. (IE8 compatible)
var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );
GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:
A Repository as documented on GitHub:
A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.
A Project as documented on GitHub:
Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.
Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.
''.join('%02x'%i for i in input)
for i=1:length(list)
elm = list(i);
//do something with elm.
You can use the following solution to check if a PHP session has already started:
if(session_id()== '')
{
echo"Session isn't Start";
}
else
{
echo"Session Started";
}
you can rename constraint objects using sp_rename (as described in this answer)
for example:
EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint'
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
Using DISTINCT will work
SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table
REf:- this
Yes, there is a way to show a single command output on the console (screen) and in a file. Using your example, use...
@ECHO OFF
FOR /F "tokens=*" %%I IN ('DIR') DO ECHO %%I & ECHO %%I>>windows-dir.txt
Detailed explanation:
The FOR
command parses the output of a command or text into a variable, which can be referenced multiple times.
For a command, such as DIR /B
, enclose in single quotes as shown in example below. Replace the DIR /B
text with your desired command.
FOR /F "tokens=*" %%I IN ('DIR /B') DO ECHO %%I & ECHO %%I>>FILE.TXT
For displaying text, enclose text in double quotes as shown in example below.
FOR /F "tokens=*" %%I IN ("Find this text on console (screen) and in file") DO ECHO %%I & ECHO %%I>>FILE.TXT
... And with line wrapping...
FOR /F "tokens=*" %%I IN ("Find this text on console (screen) and in file") DO (
ECHO %%I & ECHO %%I>>FILE.TXT
)
If you have times when you want the output only on console (screen), and other times sent only to file, and other times sent to both, specify the "DO" clause of the FOR loop using a variable, as shown below with %TOECHOWHERE%
.
@ECHO OFF
FOR %%I IN (TRUE FALSE) DO (
FOR %%J IN (TRUE FALSE) DO (
SET TOSCREEN=%%I & SET TOFILE=%%J & CALL :Runit)
)
GOTO :Finish
:Runit
REM Both TOSCREEN and TOFILE get assigned a trailing space in the FOR loops
REM above when the FOR loops are evaluating the first item in the list,
REM "TRUE". So, the first value of TOSCREEN is "TRUE " (with a trailing
REM space), the second value is "FALSE" (no trailing or leading space).
REM Adding the ": =" text after "TOSCREEN" tells the command processor to
REM remove all spaces from the value in the "TOSCREEN" variable.
IF "%TOSCREEN: =%"=="TRUE" (
IF "%TOFILE: =%"=="TRUE" (
SET TEXT=On screen, and in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I & ECHO %%I>>FILE.TXT"
) ELSE (
SET TEXT=On screen, not in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I"
)
) ELSE (
IF "%TOFILE: =%"=="TRUE" (
SET TEXT=Not on screen, but in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I>>FILE.txt"
) ELSE (
SET TEXT=Not on screen, nor in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I>NUL"
)
)
FOR /F "tokens=*" %%I IN ("%TEXT%") DO %TOECHOWHERE:~1,-1%
GOTO :eof
:Finish
ECHO Finished [this text to console (screen) only].
PAUSE
I've found an easy way to export query results from SQL Server Management Studio 2005 to Excel.
1) Select menu item Query -> Query Options.
2) Set check box in Results -> Grid -> Include column headers when copying or saving the results.
After that, when you Select All and Copy the query results, you can paste them to Excel, and the column headers will be present.
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
>>> import pandas
>>> pandas.DataFrame(data, teams_list, teams_list)
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
The reason eval
and exec
are so dangerous is that the default compile
function will generate bytecode for any valid python expression, and the default eval
or exec
will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.
Instead, you can easily create a simple eval
function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.
c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]
The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d
, which is the bytecode for LOAD_CONST
, followed by the number of the constant to load (usually the last one in the list), followed by S
, which is the bytecode for RETURN_VALUE
. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).
This also opens the door to some more sophisticated input formats. For example:
stringExp = "1 + cos(2)"
This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS)
or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION
only allow functions in a 'safe' list.
from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator
globs = {'sin':sin, 'cos':cos}
safe = globs.values()
stack = LifoQueue()
class BINARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get(),stack.get()))
class UNARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get()))
def CALL_FUNCTION(context, arg):
argc = arg[0]+arg[1]*256
args = [stack.get() for i in range(argc)]
func = stack.get()
if func not in safe:
raise TypeError("Function %r now allowed"%func)
stack.put(func(*args))
def LOAD_CONST(context, arg):
cons = arg[0]+arg[1]*256
stack.put(context['code'].co_consts[cons])
def LOAD_NAME(context, arg):
name_num = arg[0]+arg[1]*256
name = context['code'].co_names[name_num]
if name in context['locals']:
stack.put(context['locals'][name])
else:
stack.put(context['globals'][name])
def RETURN_VALUE(context):
return stack.get()
opfuncs = {
opmap['BINARY_ADD']: BINARY(operator.add),
opmap['UNARY_INVERT']: UNARY(operator.invert),
opmap['CALL_FUNCTION']: CALL_FUNCTION,
opmap['LOAD_CONST']: LOAD_CONST,
opmap['LOAD_NAME']: LOAD_NAME
opmap['RETURN_VALUE']: RETURN_VALUE,
}
def VMeval(c):
context = dict(locals={}, globals=globs, code=c)
bci = iter(c.co_code)
for bytecode in bci:
func = opfuncs[ord(bytecode)]
if func.func_code.co_argcount==1:
ret = func(context)
else:
args = ord(bci.next()), ord(bci.next())
ret = func(context, args)
if ret:
return ret
def evaluate(expr):
return VMeval(compile(expr, 'userinput', 'eval'))
Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST
and a couple others would allow for input like 'x=5;return x+x
or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto
bytecodes, which means changing from a for
iterator to while
and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER
being the most obvious).
While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile
take anything arbitrarily complicated and reduces it to a sequence of simple instructions).
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
comm.Parameters.Add("person", "Myname");
You can also do this with ant contrib's if task.
<if>
<equals arg1="${condition}" arg2="true"/>
<then>
<copy file="${some.dir}/file" todir="${another.dir}"/>
</then>
<elseif>
<equals arg1="${condition}" arg2="false"/>
<then>
<copy file="${some.dir}/differentFile" todir="${another.dir}"/>
</then>
</elseif>
<else>
<echo message="Condition was neither true nor false"/>
</else>
</if>
Right now i had this error and resolved it. Your url could match with created virtual directory.
You have to check virtual directories, in my example i found in applicationhost.config
next row:
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/admin/roles" physicalPath="C:\..." />
</application>
I tried to open page with an url (http://localhost/admin/roles
) of AdminController
and Roles
action and got this error.
If you want to improve on a regex that has been working reasonably well over several years, then the answer depends on what exactly you want to achieve - what kinds of email addresses have been failing. Fine-tuning email regexes is very difficult, and I have yet to see a perfect solution.
The leading answer to your question currently links to a "fully RFC-822–compliant regex". However, in spite of the complexity of that regex and its presumed attention to detail in RFC rules, it completely fails when it comes to Unicode support.
The regex that I've written for most of my apps focuses on Unicode support, as well as reasonably good overall adherence to RFC standards:
/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFFu20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\.!#$%&'*+-/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\-\.\d]+)((\.([a-zA-Z\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF]){2,63})+)$/i
I'll avoid copy-pasting complete answers, so I'll just link this to a similar answer I provided here: How to validate a unicode email?
There is also a live demo available for the regex above at: http://jsfiddle.net/aossikine/qCLVH/3/
Simple, just wrap it up in a table div...
The HTML:
<div class="fake-table">
<div class="left-side">
some text
</div>
<div class="right-side">
My Navigation or something
</div>
</div>
The CSS:
<style>
.fake-table{display:table;width:100%;height:100%;}
.left-size{width:30%;height:100%;}
.left-size{width:70%;height:100%;}
</style>
The solution is pretty simple.
<table id="TASK_LIST_GRID" class="table table-striped table-bordered table-hover dataTable no-footer" width="100%" role="grid" aria-describedby="TASK_LIST_GRID_info">_x000D_
<thead>_x000D_
<tr role="row">_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Solution</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Status</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Category</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Type</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Due Date</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Create Date</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Owner</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Comments</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Mnemonic</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Domain</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Approve</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Dismiss</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody></tbody>_x000D_
</table>
_x000D_
TASKLISTGRID = $("#TASK_LIST_GRID").DataTable({_x000D_
data : response,_x000D_
columns : columns.AdoptionTaskInfo.columns,_x000D_
paging: true_x000D_
});_x000D_
_x000D_
//Note: columns : columns.AdoptionTaskInfo.columns has at least a column not definded in the <thead>
_x000D_
Note: columns : columns.AdoptionTaskInfo.columns has at least a column not defined in the table head
For Swift 5:
extension UIImage {
func resized(to newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: newSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
I'm LATE to the party, but I had to solve this recently, figured I'd share the wealth.
const url = window.location.origin + window.location.pathname
//http://example.com/somedir/somefile/
window.location.origin
will give you the base url, in our test case: http://example.com
window.location.pathname
will give you the route path (after the base url), in our test case /somedir/somefile
SOLUTION 2
You can simply do the following to get rid of the query parameters.
const url = window.location.href.split('?')[0]
In my case (curl 7.47.0), it is because I set the header content-length
on curl command manually with a value which is calculated by postman (I used postman to generate curl command parameters and copy them to shell). After I delete header content-length
, it works normally.
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
With that in mind, the closest you could come is to use a PHP variable in your JS:
<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
//must wrap in quotes so that it is still string foo when JS does execute
//when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>
As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:
$a
to be created as string 'foo'$a
to be outputted in context of some JavaScript (which is not currently executing)$a
As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):
<script>
var a = 'foo';
</script>
Then, and only then, will the JS start executing with its own variable a
set to "foo" (at which point PHP is out of the picture).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
If both exim and ssmtp are running, you may enter into troubles. So if you just want to run a simple MTA, just to have a simple smtp client to send email notifications for insistance, you shall purge the eventually preinstalled MTA like exim or postfix first and reinstall ssmtp.
Then it's quite straight forward, configuring only 2 files (revaliases and ssmtp.conf) - See ssmtp doc - , and usage in your bash or bourne script is like :
#!/bin/sh
SUBJECT=$1
RECEIVER=$2
TEXT=$3
SERVER_NAME=$HOSTNAME
SENDER=$(whoami)
USER="noreply"
[[ -z $1 ]] && SUBJECT="Notification from $SENDER on server $SERVER_NAME"
[[ -z $2 ]] && RECEIVER="another_configured_email_address"
[[ -z $3 ]] && TEXT="no text content"
MAIL_TXT="Subject: $SUBJECT\nFrom: $SENDER\nTo: $RECEIVER\n\n$TEXT"
echo -e $MAIL_TXT | sendmail -t
exit $?
Obviously do not forget to open your firewall output to the smtp port (25).
I was getting the same error Requires: container-selinux >= 2.9 on amazon ec2 instance(Rhel7)
I tried to add extra package rmp repo by executing
sudo yum-config-manager --enable rhui-REGION-rhel-server-extras
but it works.
followed steps from https://installdocker.blogspot.com/ and I was able to install docker.
Did a little research on this, it appears that you are looping from 1 to 2147483647, in increments of 1.
(1, 1, 2147483647): The firs number is the starting number, the next number is the step, and the last number is the end number.
Edited To Add
It appears that the loop runs to completion regardless of any test conditions. I tested
FOR /L %%F IN (1, 1, 5) DO SET %%F=6
And it ran very quickly.
Second Edit
Since this is the only line in the batch file, you might try the EXIT command:
FOR /L %%F IN (1, 1, 2147483647) DO @IF NOT EXIST %%F EXIT
However, this will also close the DOS prompt window.
int segundo = 0;
DateTime dt = new DateTime();
private void timer1_Tick(object sender, EventArgs e){
segundo++;
label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss");
}
In my case I was accidentally returning a child view from within Layout.onCreateView()
as shown below:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_reject, container, false);
Button button = view.findViewById(R.id.some_button);
return button; // <-- Problem is this
}
The solution was to return the parent view instead of the child view.
There is a module on npm called mssqlhelper
You can install it to your project by npm i mssqlhelper
Example of connecting and performing a query:
var db = require('./index');
db.config({
host: '192.168.1.100'
,port: 1433
,userName: 'sa'
,password: '123'
,database:'testdb'
});
db.query(
'select @Param1 Param1,@Param2 Param2'
,{
Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
,Param2: { type : 'Int',value : 321 }
}
,function(res){
if(res.err)throw new Error('database error:'+res.err.msg);
var rows = res.tables[0].rows;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
}
}
);
You can read more about it here: https://github.com/play175/mssqlhelper
:o)
The first example changes the interface for that object only. The second example changes the interface for all object of that class.
Try this:
string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
This would require knowledge of a backend website language.
Fortunately, Python's Flask Library is a suitable backend language for the project at hand.
Check out this answer from another thread.
All the examples are great, but I figure I'd add one more to show how working in a "tidy" format simplifies things. Right now the data frame is in "wide" format meaning the variables "a" through "d" are represented in columns. To get to a "tidy" (or long) format, you can use gather()
from the tidyr
package which shifts the variables in columns "a" through "d" into rows. Then you use the group_by()
and summarize()
functions to get the mean of each group. If you want to present the data in a wide format, just tack on an additional call to the spread()
function.
library(tidyverse)
# Create reproducible df
set.seed(101)
df <- tibble(a = sample(1:5, 10, replace=T),
b = sample(1:5, 10, replace=T),
c = sample(1:5, 10, replace=T),
d = sample(1:5, 10, replace=T),
grp = sample(1:3, 10, replace=T))
# Convert to tidy format using gather
df %>%
gather(key = variable, value = value, a:d) %>%
group_by(grp, variable) %>%
summarize(mean = mean(value)) %>%
spread(variable, mean)
#> Source: local data frame [3 x 5]
#> Groups: grp [3]
#>
#> grp a b c d
#> * <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 3.000000 3.5 3.250000 3.250000
#> 2 2 1.666667 4.0 4.666667 2.666667
#> 3 3 3.333333 3.0 2.333333 2.333333
A very interesting use of internal - with internal member of course being limited only to the assembly in which it is declared - is getting "friend" functionality to some degree out of it. A friend member is something that is visible only to certain other assemblies outside of the assembly in which its declared. C# has no built in support for friend, however the CLR does.
You can use InternalsVisibleToAttribute to declare a friend assembly, and all references from within the friend assembly will treat the internal members of your declaring assembly as public within the scope of the friend assembly. A problem with this is that all internal members are visible; you cannot pick and choose.
A good use for InternalsVisibleTo is to expose various internal members to a unit test assembly thus eliminating the needs for complex reflection work arounds to test those members. All internal members being visible isn't so much of a problem, however taking this approach does muck up your class interfaces pretty heavily and can potentially ruin encapsulation within the declaring assembly.
Actually for Bootstrap 3 you also need to override the .modal-open class on body.
body.modal-open,
.modal-open
.navbar-fixed-top,
.modal-open
.navbar-fixed-bottom {
margin-right: 15px; /*<-- to margin-right: 0px;*/
}
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
See my code:
@IBAction func foundclicked(sender: AnyObject) {
if (amountTF.text.isEmpty)
{
let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
else {
var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
UIAlertAction in
JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
alertController .removeFromParentViewController()
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
This is the first response that comes up for google searches on how to download a binary file with requests. In case you need to download an arbitrary file with requests, you can use:
import requests
url = 'https://s3.amazonaws.com/lab-data-collections/GoogleNews-vectors-negative300.bin.gz'
open('GoogleNews-vectors-negative300.bin.gz', 'wb').write(requests.get(url, allow_redirects=True).content)
Try
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
The z
represents an integer of length same as size_t
, and the PRIu32
macro, defined in the C99 header inttypes.h
, represents an unsigned 32-bit integer.
I had the same problem, and my solution is changing the support version '27.+'(27.1.0) to '27.0.1'
git checkout -b <branch-name> <sha1-of-commit>
Have a look at the helper class: Mage_Customer_Helper_Data
To simply get the customer name, you can write the following code:-
$customerName = Mage::helper('customer')->getCustomerName();
For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-
echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";
From the helper class, you can also get information about customer login url, register url, logout url, etc.
From the isLoggedIn function in the helper class, you can also check whether a customer is logged in or not.
list() and [] work differently:
>>> def a(p):
... print(id(p))
...
>>> for r in range(3):
... a([])
...
139969725291904
139969725291904
139969725291904
>>> for r in range(3):
... a(list())
...
139969725367296
139969725367552
139969725367616
list() always create new object in heap, but [] can reuse memory cell in many reason.
As an addition to the all above mentioned great answers, check the https://crontab.guru/ - a useful online resource for checking your crontab syntax.
What you get is human readable representation of what you have specified.
See the examples below:
In Laravel 5.1+, you can use the value() instead of pluck.
To get first occurence, You can either use
DB::table('users')->value('name');
or use,
DB::table('users')->where('id', 1)->pluck('name')->first();
I used this script which I have put on my blog (How-to generate Insert statement procedures on sql server).
So far has worked for me, although they might be bugs I have not discovered yet .
Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.
max-width:something px;
max-height:something px;
The other option would be to use the devlopr tools and see if you can remove the natural padding.
padding: 0;
Your not applying Date formator. rather you are just parsing the date. to get output in this format
yyyy-MM-dd HH:mm:ss.SSSSSS
we have to use format() method here is full example:-
Here is full example:-
it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS
and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");
System.out.println(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(temp);
System.out.println(strDateOutput);
}
}
I use hive jdbc in a java maven project and have the same issues.
My method is to add a log4j2.xml file under src/main/java/resources
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClassName {
private static final Logger LOG = LoggerFactory.getLogger(MyClassName.class);
}
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="<your_package_name>.<your_class_name>" level="debug">
<AppenderRef ref="Console"/>
</Logger>
<Root level="WARN">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Simple Answer:
SELECT distinct(sal)
FROM emp
ORDER BY sal DESC
LIMIT 1, 1;
You will get only the second max salary.
And if you need any 3rd or 4th or Nth value you can increase the first value followed by LIMIT (n-1)
ie. for 4th salary : LIMIT 3, 1;
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
My solution works perfectly giving the exact value for each scroll direction.
distanceFromFirstCellToTop
contains the exact distance from the first cell to the top of the parent View. I save this value in previousDistanceFromFirstCellToTop
and as I scroll I compare it with the new value. If it's lower then I scrolled up, else, I scrolled down.
private int previousDistanceFromFirstCellToTop;
listview.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
View firstCell = listview.getChildAt(0);
int distanceFromFirstCellToTop = listview.getFirstVisiblePosition() * firstCell.getHeight() - firstCell.getTop();
if(distanceFromFirstCellToTop < previousDistanceFromFirstCellToTop)
{
//Scroll Up
}
else if(distanceFromFirstCellToTop > previousDistanceFromFirstCellToTop)
{
//Scroll Down
}
previousDistanceFromFirstCellToTop = distanceFromFirstCellToTop;
}
});
For Xamarin developers, the solution is the following:
Note: don't forget to run on UI thread
listView.Scroll += (o, e) =>
{
View firstCell = listView.GetChildAt(0);
int distanceFromFirstCellToTop = listView.FirstVisiblePosition * firstCell.Height - firstCell.Top;
if (distanceFromFirstCellToTop < previousDistanceFromFirstCellToTop)
{
//Scroll Up
}
else if (distanceFromFirstCellToTop > previousDistanceFromFirstCellToTop)
{
//Scroll Down
}
previousDistanceFromFirstCellToTop = distanceFromFirstCellToTop;
};
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
From the menu bar: Project -> Properties -> Java Compiler
Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"
That will allow you to compile "1.5" code using a "1.6" JDK.
If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:
Window -> preferences -> Installed JREs
And then go back to your project
Project -> properties -> Java Build Path -> libraries
remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.
Verify that the correct JRE is on the project's build path, save everything, and enjoy!