.Net lucene has an inbuilt porter stemmer. You can try that. But note that porter stemming does not consider word context when deriving the lemma. (Go through the algorithm and its implementation and you will see how it works)
This is caused because all the changes to the RemoteViews are serialised (e.g. setInt and setImageViewBitmap ). The bitmaps are also serialised into an internal bundle. Unfortunately this bundle has a very small size limit.
You can solve it by scaling down the image size this way:
public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {
final float densityMultiplier = context.getResources().getDisplayMetrics().density;
int h= (int) (newHeight*densityMultiplier);
int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));
photo=Bitmap.createScaledBitmap(photo, w, h, true);
return photo;
}
Choose newHeight to be small enough (~100 for every square it should take on the screen) and use it for your widget, and your problem will be solved :)
If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the +
or +=
operator are extremely slow on IE. This is especially true for IE6. On modern browsers +=
is usually just as fast as array joins.
When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:
var html = [];
html.push(
"<html>",
"<body>",
"bla bla bla",
"</body>",
"</html>"
);
return html.join("");
Note that the push
methods accepts multiple arguments.
I just want to add that if you want to somehow store the encrypted byte array as String and then retrieve it and decrypt it (often for obfuscation of database values) you can use this approach:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
public void run()
{
try
{
String text = "Hello World";
String key = "Bar12345Bar12345"; // 128 bit key
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b: encrypted) {
sb.append((char)b);
}
// the encrypted String
String enc = sb.toString();
System.out.println("encrypted:" + enc);
// now convert the string to byte array
// for decryption
byte[] bb = new byte[enc.length()];
for (int i=0; i<enc.length(); i++) {
bb[i] = (byte) enc.charAt(i);
}
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(bb));
System.err.println("decrypted:" + decrypted);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
StrongAES app = new StrongAES();
app.run();
}
}
here is the example using Pure JavaScript
function scrollpage() { _x000D_
function f() _x000D_
{_x000D_
window.scrollTo(0,i);_x000D_
if(status==0) {_x000D_
i=i+40;_x000D_
if(i>=Height){ status=1; } _x000D_
} else {_x000D_
i=i-40;_x000D_
if(i<=1){ status=0; } // if you don't want continue scroll then remove this line_x000D_
}_x000D_
setTimeout( f, 0.01 );_x000D_
}f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
#top { border: 1px solid black; height: 20000px; }_x000D_
#bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:
$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];
@Rynant 's solution worked for me. I had a couple of additional requirements though:
Here's what I got working (finally):
[PS script code]
& runner.bat bat_to_run.bat logfile.txt
[runner.bat]
@echo OFF
REM This script can be executed from within a powershell script so that the bat file
REM passed as %1 will not cause execution to halt if PAUSE is encountered.
REM If {logfile} is included, bat file output will be appended to logfile.
REM
REM Usage:
REM runner.bat [path of bat script to execute] {logfile}
if not [%2] == [] GOTO APPEND_OUTPUT
@echo | call %1
GOTO EXIT
:APPEND_OUTPUT
@echo | call %1 1> %2 2>&1
:EXIT
make
will do this for you. Investigate the -j
and -l
switches in the man page. I don't think g++
is parallelizable.
I've seen only one simple way of reading an arbitrarily long string, but I've never used it. I think it goes like this:
char *m = NULL;
printf("please input a string\n");
scanf("%ms",&m);
if (m == NULL)
fprintf(stderr, "That string was too long!\n");
else
{
printf("this is the string %s\n",m);
/* ... any other use of m */
free(m);
}
The m
between %
and s
tells scanf()
to measure the string and allocate memory for it and copy the string into that, and to store the address of that allocated memory in the corresponding argument. Once you're done with it you have to free()
it.
This isn't supported on every implementation of scanf()
, though.
As others have pointed out, the easiest solution is to set a limit on the length of the input. If you still want to use scanf()
then you can do so this way:
char m[100];
scanf("%99s",&m);
Note that the size of m[]
must be at least one byte larger than the number between %
and s
.
If the string entered is longer than 99, then the remaining characters will wait to be read by another call or by the rest of the format string passed to scanf()
.
Generally scanf()
is not recommended for handling user input. It's best applied to basic structured text files that were created by another application. Even then, you must be aware that the input might not be formatted as you expect, as somebody might have interfered with it to try to break your program.
Use group_concat() function of mysql.
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;
It'll give you concatenated string like :
5,6,9,10,12,14,15,17,18,779
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
Not sure, if that's what you want, but you could make the inner div an inline-element. This way the border should be wrapped only around the text. Even better than that is to use an inline-element for your title.
Solution 1
<div id="page" style="width: 600px;">
<div id="title" style="display: inline; border...">Title</div>
</div>
Solution 2
<div id="page" style="width: 600px;">
<span id="title" style="border...">Title</span>
</div>
Edit: Strange, SO doesn't interpret my code-examples correctly as block, so I had to use inline-code-method.
Set level to OFF (instead of DEBUG, INFO, ....)
In my case, the problem was that my POST request was sent to the same url as GET (with get parameters using "?..=..") and that parameters had the same name as form parameters. Probably Spring is merging them into an array and parsing was throwing error.
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
View.getContext()
: Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext()
: Returns the context for the entire application (the process all the Activities are running inside
of). Use this instead of the current Activity context if you need a
context tied to the lifecycle of the entire application, not just the
current Activity.
ContextWrapper.getBaseContext()
: If you need access to a Context from within another context, you use a ContextWrapper. The
Context referred to from inside that ContextWrapper is accessed via
getBaseContext().
From your service method:
function serviceMethod() {
return $timeout(function() {
return {
property: 'value'
};
}, 1000);
}
And in your controller:
serviceName
.serviceMethod()
.then(function(data){
//handle the success condition here
var x = data.property
});
For excluding multiple file types, you can use '+' to concatenate other lists. For example:
xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan
Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/
Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript
language spec that look like this:
Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.
Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString()
. Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.
For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:
There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.
Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:
// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;
A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.
In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.
Various libraries and plugins for localization:
Feel free to add/edit.
Versions of sed
that support the -i
option for editing a file in place write to a temporary file and then rename the file.
Alternatively, you can just use ed
. For example, to change all occurrences of foo
to bar
in the file file.txt
, you can do:
echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
Syntax is similar to sed
, but certainly not exactly the same.
Even if you don't have a -i
supporting sed
, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file
, you could do inline file sed 's/foo/bar/g'
. Such a script is trivial to write. For example:
#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN" # preserve hard links
should be adequate for most uses.
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = @"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)
Its a parameter the you need to define. to prevent SQL Injection you should pass all your variables in as parameters.
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
NOTE if you are using python 3.x:
request.FILES
is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile']
you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:
list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
filename = f.name
list.append(filename)
of course one can squeeze the whole thing in one line, but this is easy to understand
(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")
If you don't mind downloading something, use timeout
(sudo apt-get install timeout
) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils
)
timeout 10 ping www.goooooogle.com
If you don't want to download something, do what timeout does internally:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )
In case that you want to do a timeout for longer bash code, use the second option as such:
( cmdpid=$BASHPID;
(sleep 10; kill $cmdpid) \
& while ! ping -w 1 www.goooooogle.com
do
echo crap;
done )
Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.
Does someone know how I can use a String constant or String[] constant to supply value to an annotation?
Unfortunately, you can't do this with arrays. With non-array variables, the value must be final static.
I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".
As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.
But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.
Hope this helps :)
begins the session, you need to say this at the top of a page or before you call session code
session_start();
put a user id in the session to track who is logged in
$_SESSION['user'] = $user_id;
Check if someone is logged in
if (isset($_SESSION['user'])) {
// logged in
} else {
// not logged in
}
Find the logged in user ID
$_SESSION['user']
So on your page
<?php
session_start();
if (isset($_SESSION['user'])) {
?>
logged in HTML and code here
<?php
} else {
?>
Not logged in HTML and code here
<?php
}
On Executing: for /f %%i in ('application arg0 arg1') do set VAR=%%i
i was getting error: %%i was unexpected at this time.
As a fix, i had to execute above as for /f %i in ('application arg0 arg1') do set VAR=%i
A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.
Something like...
link: function(scope, elem, attr){
var wrapper = angular.element('<div tooltip></div>');
elem.before(wrapper);
$compile(wrapper)(scope);
wrapper.append(elem);
}
This solution has the advantage that it keeps things simple by not recompiling the original element.
This wouldn't work if any of the added directive's require
any of the original element's directives or if the original element has absolute positioning.
In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.
This is normally more an issue with ToMany than ToOnes. For example,
Select e from Employee e
join fetch e.phones p
where p.areaCode = '613'
This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.
Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.
I would have to say a sleep is a better implementation with a state machine behind it. This would still keep you in control of the application at all times, but allowing any response needed at any specific time. This also will handle timer callbacks that are shorter than the "Processing execution time in the loop"
For example..
<!-- language: c# -->
public enum State
{
Idle = 0,
Processing = 1,
Stop = 100,
}
public void Run()
{
State state = State.Idle; // could be a member variable, so a service could stop this too
double intervalInSeconds = 60;
System.DateTime nextExecution = System.DateTime.Now.AddSeconds(intervalInSeconds);
while (state != State.Stop)
{
switch (state)
{
case State.Idle:
{
if (nextExecution > System.DateTime.Now)
{
state = State.Processing;
}
}
break;
case State.Processing:
{
// do your once-per-minute code here
// if you want it to stop, just set it state to stop.
// if this was a service, you could stop execution by setting state to stop, also
// only time it would not stop is if it was waiting for the process to finish, which you can handle in other ways
state = State.Idle;
nextExecution = System.DateTime.Now.AddSeconds(intervalInSeconds);
}
break;
default:
break;
}
System.Threading.Thread.Sleep(1);
}
}
Try looking here: Best way to get application folder path
To quote from there:
System.IO.Directory.GetCurrentDirectory()
returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).
Use request npm module and after call
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
For best practice also use some winston logger module or else simple console.log and then run your application like
npm start output.txt
Result of above command will generate one txt file on root with all data which you have printed in console.log
None of these solutions worked for me when mousing over/out of objects created after the document has loaded as the question requests. I know this question is old but I have a solution for those still looking:
$("#container").on('mouseenter', '.selector', function() {
//do something
});
$("#container").on('mouseleave', '.selector', function() {
//do something
});
This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.
Update: This only works for the local copy of the repository (the "client"). Please see others' comments below.
With a recent version of git (Feb 2014), the correct procedure would be:
git remote set-head $REMOTE_NAME $BRANCH
So for example, switching the head on remote origin
to branch develop
would be:
git remote set-head origin develop
There's a nice way to eject webpack.config.js from angular-cli. Just run:
$ ng eject
This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of
$ ng serve
you would have to do something like
$ npm run build & npm run start
This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)
I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It's called Mousetrap.
You can check it out at http://craig.is/killing/mice
If your csv file contains extra data, columns can be deleted from the DataFrame after import.
import pandas as pd
from StringIO import StringIO
csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""
df = pd.read_csv(StringIO(csv),
index_col=["date", "loc"],
usecols=["dummy", "date", "loc", "x"],
parse_dates=["date"],
header=0,
names=["dummy", "date", "loc", "x"])
del df['dummy']
Which gives us:
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
Perhaps the single biggest "benefit" of dynamic typing is the shallower learning curve. There is no type system to learn and no non-trivial syntax for corner cases such as type constraints. That makes dynamic typing accessible to a lot more people and feasible for many people for whom sophisticated static type systems are out of reach. Consequently, dynamic typing has caught on in the contexts of education (e.g. Scheme/Python at MIT) and domain-specific languages for non-programmers (e.g. Mathematica). Dynamic languages have also caught on in niches where they have little or no competition (e.g. Javascript).
The most concise dynamically-typed languages (e.g. Perl, APL, J, K, Mathematica) are domain specific and can be significantly more concise than the most concise general-purpose statically-typed languages (e.g. OCaml) in the niches they were designed for.
The main disadvantages of dynamic typing are:
Run-time type errors.
Can be very difficult or even practically impossible to achieve the same level of correctness and requires vastly more testing.
No compiler-verified documentation.
Poor performance (usually at run-time but sometimes at compile time instead, e.g. Stalin Scheme) and unpredictable performance due to dependence upon sophisticated optimizations.
Personally, I grew up on dynamic languages but wouldn't touch them with a 40' pole as a professional unless there were no other viable options.
One more option is WinRun4J. There is an Eclipse Plugin for WinRun4J that allows you to export your application as a single executable with necessary jars/classes embedded.
(full disclosure: I work on this project)
The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)
After the redirect put exit(); to stop the rest of the script to execute
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
Since you actually stored the previous LAST_INSERT_ID() into the second table, you can get it from there:
INSERT INTO table1 (title,userid) VALUES ('test',1);
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
SELECT parentid FROM table2 WHERE id = LAST_INSERT_ID();
Try this one ;
CSS
#indicator{
width:20px;
height:20px;
display:block;
border-radius:10px;
}
.green{
background-color:green;
display:block;
}
.red{
background-color:red;
display:block;
}
HTML
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" id="password" /></label> <br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" /><span id="indicator"></span> <br>
</label>
<label>
<input type="submit" name="submit" id="regbtn" value="registration" />
</label>
</form>
JQuery
$('#confirm_password').keyup(function(){
var pass = $('#password').val();
var cpass = $('#confirm_password').val();
if(pass!=cpass){
$('#indicator').attr({class:'red'});
$('#regbtn').attr({disabled:true});
}
else{
$('#indicator').attr({class:'green'});
$('#regbtn').attr({disabled:false});
}
});
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
Use a ValueConverter
[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("{0}:{1}", (string) value, (string) parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
and in the markup
<src:MyConverter x:Key="MyConverter"/>
. . .
<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />
If you're on a Mac:
PhpStorm -> Preferences... -> Editor -> Appearance -> Show Line Numbers
var string="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3
$six_digit_random_number = mt_rand(100000, 999999);
As all numbers between 100,000 and 999,999 are six digits, of course.
In case it's useful to anyone else, working on a Code-First approach using attribute mappings, I wanted something that just left me needing to bind an entity in the object model. So thanks to Carnotaurus' answer, I extended it as per their own suggestion and made a couple of tweaks.
This relies therefore on this solution comprising TWO parts, both of which are SQL Scalar-Valued functions:
- An 'Initial Caps' function (taken from: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8a58dbe1-7a4b-4287-afdc-bfecb4e69b23/similar-to-initcap-in-sql-server-tsql and slightly modified to meet my needs)
ALTER function [dbo].[ProperCase] (@cStringToProper varchar(8000))
returns varchar(8000)
as
begin
declare @Position int
select @cStringToProper = stuff(lower(@cStringToProper) , 1 , 1 , upper(left(@cStringToProper , 1)))
, @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)
while @Position > 0
select @cStringToProper = stuff(@cStringToProper , @Position , 2 , upper(substring(@cStringToProper , @Position , 2)))
, @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)
select @cStringToProper = replace(@cStringToProper, '_','')
return @cStringToProper
end
The output function itself, which extends Carnotaurus' solution by:
- Correctly outputting newline characters
- Performing some basic tabulation
- Writing out an appropriate a [Table] mapping (as suggested)
- Writing out an appropriate [Column] mapping, including the type name (as suggested)
- Allowing the Entity name to differ from the name of the table
- Fixes the limitation of the Print @Result truncating when you have tables with a large number of columns
CREATE FUNCTION [dbo].[GetEntityObject] (@NameSpace NVARCHAR(MAX), @TableName NVARCHAR(MAX), @EntityName NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN
DECLARE @result NVARCHAR(MAX)
SET @result = @result + 'using System;' + CHAR(13) + CHAR(13)
IF (@NameSpace IS NOT NULL) BEGIN
SET @result = @result + 'namespace ' + @NameSpace + CHAR(13) + '{' + CHAR(13) END
SET @result = @result + '[Table(name: ' + CHAR(34) + @TableName + CHAR(34) + ')]' + CHAR(13) SET @result = @result + 'public class ' + @EntityName + CHAR(13) + '{' + CHAR(13)
SET @result = @result + '#region Instance Properties' + CHAR(13)
SELECT @result = @result + CHAR(13) + '[Column(name: ' + CHAR(34) + OriginalColumnName + CHAR(34) + ', TypeName = ' + CHAR(34) + DataType
+ CHAR(34) + ')]' + CHAR(13)
+ 'public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13) FROM (
SELECT dbo.ProperCase (c.COLUMN_NAME) AS ColumnName
, CASE c.DATA_TYPE
WHEN 'bigint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
WHEN 'binary' THEN 'Byte[]'
WHEN 'bit' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END
WHEN 'char' THEN 'String'
WHEN 'date' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime2' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetimeoffset' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END
WHEN 'decimal' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'float' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Single?' ELSE 'Single' END
WHEN 'image' THEN 'Byte[]'
WHEN 'int' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
WHEN 'money' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nchar' THEN 'String'
WHEN 'ntext' THEN 'String'
WHEN 'numeric' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nvarchar' THEN 'String'
WHEN 'real' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Double?' ELSE 'Double' END
WHEN 'smalldatetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'smallint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END
WHEN 'smallmoney' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'text' THEN 'String'
WHEN 'time' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END
WHEN 'timestamp' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'tinyint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END
WHEN 'uniqueidentifier' THEN 'Guid'
WHEN 'varbinary' THEN 'Byte[]'
WHEN 'varchar' THEN 'String'
ELSE 'Object'
END AS ColumnType
, c.ORDINAL_POSITION , c.COLUMN_NAME as OriginalColumnName ,c.DATA_TYPE as DataType
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_NAME = @TableName) t ORDER BY t.ORDINAL_POSITION
SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)
SET @result = @result + '}' + CHAR(13)
IF (@TableName IS NOT NULL) BEGIN
SET @result = @result + CHAR(13) + '}' END
return @result END
Usage from within MS SQL Management Studio:
SELECT dbo.GetEntityObject('MyNameSpace', 'MyTableName', 'MyEntityName')
will result in a column value you can copy and paste into Visual Studio.
If it helps anyone, then great!
It says what it means:
make your class non-static:
public class employee
{
NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
or the member static:
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.
This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter
i=0;
w_h = 0;
w_m = 0;
textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
hl.removeCallbacksAndMessages(null);
Thread.currentThread().isInterrupted();
}
});
}`
Following two are the most probable cause of this issue:
$stmt->close(); // <<<-----This fixed the issue for me
$stmt = $conn->prepare("Insert statement");
To get around the access denied issue, I started SSMS as administrator and that allowed me to attach a database from my local drive. The database was created in another SQL and windows instance.
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client
.
You could try to run the 2to3
tool on your code, and try to have it translated automatically. References to httplib
will automatically be rewritten to use http.client
instead.
Better way is to use "bc", an arbitrary precision calculator.
variable=$(echo "OPTIONS; OPERATIONS" | bc)
ex:
my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)
where "scale=5" is accuracy.
man bc
comes with several usage examples.
If you have already set labels for your axis like how @andyhasit and @Marcus mentioned, and would like to change it at a later time, then you can try this:
chart.options.scales.yAxes[ 0 ].scaleLabel.labelString = "New Label";
Full config for reference:
var chartConfig = {
type: 'line',
data: {
datasets: [ {
label: 'DefaultLabel',
backgroundColor: '#ff0000',
borderColor: '#ff0000',
fill: false,
data: [],
} ]
},
options: {
responsive: true,
scales: {
xAxes: [ {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
} ],
yAxes: [ {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
} ]
}
}
};
I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:
>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9
So make sure the first operand is an integer (and not a string), and it will work.
try this:
HTML:
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
CSS:
.container {
width: 200px;
height: 100px;
display: flex;
overflow-x: auto;
}
.item {
width: 100px;
flex-shrink: 0;
height: 100px;
}
The white-space: nowrap; property dont let you wrap text. Just see here for an example: https://codepen.io/oezkany/pen/YoVgYK
//a[contains(@prop,'Foo')]
Works if I use this XML to get results back.
<bla>
<a prop="Foo1">a</a>
<a prop="Foo2">b</a>
<a prop="3Foo">c</a>
<a prop="Bar">a</a>
</bla>
Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use
/bla/a[contains(@prop,'Foo')]
This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element
//a[contains(@prop,'Foo')]
I added this for the sake of thoroughness and in the spirit of stackoverflow. :)
You can use jQuery DataTables plugin for applying column sorting in desired way.
The Databse Publishing Wizard can dump the schema (and other objects) from the command line.
try
std::fill
and also
std::size siz = vec.size();
//no memory allocating
vec.resize(0);
vec.resize(siz, 0);
Heres a Swift version:
import MessageUI
class YourVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if MFMailComposeViewController.canSendMail() {
var emailTitle = "Vea Software Feedback"
var messageBody = "Vea Software! :) "
var toRecipents = ["[email protected]"]
var mc:MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toRecipents)
self.presentViewController(mc, animated: true, completion: nil)
} else {
println("No email account found")
}
}
}
extension YourVC: MFMailComposeViewControllerDelegate {
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
switch result.value {
case MFMailComposeResultCancelled.value:
println("Mail Cancelled")
case MFMailComposeResultSaved.value:
println("Mail Saved")
case MFMailComposeResultSent.value:
println("Mail Sent")
case MFMailComposeResultFailed.value:
println("Mail Failed")
default:
break
}
self.dismissViewControllerAnimated(false, completion: nil)
}
}
In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")
See sync-request: https://github.com/ForbesLindesay/sync-request
Example:
var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());
Here is how I got it going specifically for the admob sdk jar file:
jar
file into the libs folder.jar
file and select Add Library
now the jar file is a library lets add it to the compile pathbuild.gradle
file (note there are two build.gradle
files at least, don't use the root one use the one in your project scope).Find the dependencies section (for me i was trying to the admob -GoogleAdMobAdsSdk jar file) e.g.
dependencies {
compile files('libs/android-support-v4.jar','libs/GoogleAdMobAdsSdk-6.3.1.jar')
}
Last go into settings.gradle
and ensure it looks something like this:
include ':yourproject', ':yourproject:libs:GoogleAdMobAdsSdk-6.3.1'
If you really don't want to use any server controls, you should put the Response.Write
in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search
There are a lot of answered questions in Stack Overflow with more data on this:
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
Have a look at the following
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
your controller should have action method which would accept HttpPostedFileBase
;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
Update 1
In case you want to upload files using jQuery with asynchornously, then try this article.
the code to handle the server side (for multiple upload) is;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.
Alternatively, you can try Async File Uploads in MVC 4.
You can Get the table meta data using this query
SELECT * FROM SYSIBM.COLUMNS WHERE TABLE_NAME = 'ASTPCLTEXT';
FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put
myservice.$loaded().then(function() {$rootScope.myservice = myservice;});
and in the view I just did
ng-if="myservice" ng-init="somevar=myfunct()"
in the first/parent view element/wrapper so the controller can run everything inside
myfunct()
without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.
I had the same issue!
My solution was to insert the public_html
folder into the download URL.
Real file location on the server:
myhost.com/public_html/myimages/image.png
Web URL:
www.myhost.com/myimages/image.png
use this class inside nav tag
class="navbar navbar-expand-lg navbar-light bg-light sticky-top"
For bootstrap 4
I would store the timespan.TotalSeconds in a float and then retrieve it using Timespan.FromSeconds(totalSeconds).
Depending on the resolution you need you could use TotalMilliseconds, TotalMinutes, TotalDays.
You could also adjust the precision of your float in the database.
It's not an exact value... but the nice thing about this is that it's easy to read and calculate in simple queries.
This is actually pretty easy to do. All you have to do is change the css.
Here's a fiddle with a very simple fade animation: http://jsfiddle.net/elthrasher/sNpjH/
To make it into a sliding animation, I first had to put my element in a box (that's the slide-container), then I added another element to replace the one that was leaving, just because I thought it would look nice. Take it out and the example will still work.
I changed the animation css from 'fade' to 'slide' but please note that these are the names I gave it. I could have written slide animation css named 'fade' or anything else for that matter.
The important part is what's in the css. Here's the original 'fade' css:
.fade-hide, .fade-show {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.fade-hide {
opacity:1;
}
.fade-hide.fade-hide-active {
opacity:0;
}
.fade-show {
opacity:0;
}
.fade-show.fade-show-active {
opacity:1;
}
This code changes the opacity of the element from 0 (completely transparent) to 1 (completely opaque) and back again. The solution is to leave opacity alone and instead change the top (or left, if you want to move left-right).
.slide-hide, .slide-show {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
}
.slide-hide {
position: relative;
top: 0;
}
.slide-hide.slide-hide-active {
position: absolute;
top: -100px;
}
.slide-show {
position: absolute;
top: 100px;
}
.slide-show.slide-show-active {
position: relative;
top: 0px;
}
I'm also changing from relative to absolute positioning so only one of the elements takes up space in the container at a time.
Here's the finished product: http://jsfiddle.net/elthrasher/Uz2Dk/. Hope this helps!
Addition:
When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()
[1])
In this case, use an additional cast to binary:
SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;
Otherwise, the SELECT
statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.
My answer is to add a listener (using addListenerOnce) to check if the infoWindow has been added to the DOM, then opening the infoWindow again (no need to close it).
// map, marker and infoWindow code, we'll call them
// myMap, myMarker and myInfoWindow
myInfoWindow.open(myMap, myMarker);
google.maps.event.addListenerOnce(myInfoWindow, 'domready', function(){
myInfoWindow.open(myMap, myMarker);
});
Why don't you use stream to convert List of Strings to List of integers? like below
List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
"50", "60", "70"));
List<Integer> integerList = stringList.stream()
.map(Integer::valueOf).collect(Collectors.toList());
complete operation could be something like this
String s = "AttributeGet:1,16,10106,10111";
List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
Arrays.asList(s.replace("AttributeGet:", "").split(","))
.stream().map(Integer::valueOf).collect(Collectors.toList())
: new ArrayList<Integer>();
select (case when locate('(', LocationName) = 0
then
horse_name
else
left(LocationName, locate('(', LocationName) - 1)
end) as Country
from tblcountry;
The simplest way to put a Toolbar transparent is to define a opacity in @colors section, define a TransparentTheme in @styles section and then put these defines in your toolbar.
@colors.xml
<color name="actionbar_opacity">#33000000</color>
@styles.xml
<style name="TransparentToolbar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:windowActionBarOverlay">true</item>
<item name="windowActionBarOverlay">true</item>
</style>
@activity_main.xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:background="@color/actionbar_opacity"
app:theme="@style/TransparentToolbar"
android:layout_height="?attr/actionBarSize"/>
That's the result:
A better solution might be to introduce a license file with a counter. Write into the license file the install date of the application (during installation). Then everytime the application is run you can edit the license file and increment the count by 1. Each time the application starts up you just do a quick check to see if the 30 uses of the application has been reached i.e.
if (LicenseFile.Counter == 30)
// go into expired mode
Also this will solve the issue if the user has put the system clock back as you can do a simple check to say
if (LicenseFile.InstallationDate < SystemDate)
// go into expired mode (as punishment for trying to trick the app!)
The problem with your current setup is the user will have to use the application every day for 30 days to get their full 30 day trial.
From James Gosling in "The Java Programming Language":
"...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple. .."
Just wanted to throw out a real use case that demonstrates idempotence. In JavaScript, say you are defining a bunch of model classes (as in MVC model). The way this is often implemented is functionally equivalent to something like this (basic example):
function model(name) {
function Model() {
this.name = name;
}
return Model;
}
You could then define new classes like this:
var User = model('user');
var Article = model('article');
But if you were to try to get the User
class via model('user')
, from somewhere else in the code, it would fail:
var User = model('user');
// ... then somewhere else in the code (in a different scope)
var User = model('user');
Those two User
constructors would be different. That is,
model('user') !== model('user');
To make it idempotent, you would just add some sort of caching mechanism, like this:
var collection = {};
function model(name) {
if (collection[name])
return collection[name];
function Model() {
this.name = name;
}
collection[name] = Model;
return Model;
}
By adding caching, every time you did model('user')
it will be the same object, and so it's idempotent. So:
model('user') === model('user');
You need to handle an event on Form1 that is raised as a result of user interaction. For example, if you have a "Settings" button that the user clicks in order to show the settings form (Form2), you should handle the Click
event for that button:
private void settingsButton_Click(Object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
}
In addition to the Show
method, you could also choose to use the ShowDialog
method. The difference is that the latter shows the form as a modal dialog, meaning that the user cannot interact with the other forms in your application until they close the modal form. This is the same way that a message box works. The ShowDialog
method also returns a value indicating how the form was closed.
When the user closes the settings form (by clicking the "X" in the title bar, for example), Windows will automatically take care of closing it.
If you want to close it yourself before the user asks to close it, you can call the form's Close
method:
this.Close();
Can you learn to draw, sculpt, or paint in ten weeks? Anyone can learn to punch the keys to program, just as anyone can pick up a brush, but it takes time and talent to cultivate the artistry to develop. Do yourself a favor and put the time and effort in to learning, not cramming. The lessons you learn by a concerted effort to know how to develop will serve you much better than binging on it to meet some arbitrary date.
In my case I had a multi module project just like you. I had to change a group Id of one of the external libraries my project was depending on as shown below.
From:
<dependencyManagement>
<dependency>
<groupId>org.thirdparty</groupId>
<artifactId>calculation-api</artifactId>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependencyManagement>
To:
<dependencyManagement>
<dependency>
<groupId>org.thirdparty.module</groupId>
<artifactId>calculation-api</artifactId>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependencyManagement>
Pay attention to the <groupId> section. It turned out that I was forgetting to modifiy the corresponding section of the submodules that define this dependency in their pom files.
It drove me very crazy because the module was available locally.
var el = document.getElementById('foo');
el.parentNode.innerHTML;
If you are using angular pre v1.1.5 (i.e. no ternary operator) and you still want an equivalent way to set a value in both conditions you can do something like this:
ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"
Try GACView if you have a fear of command prompts.
You have not set the PATH properly in DOS.You need to point the path to where the gacutil resides to use it in DOS.
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
Assuming you have a Map<KeyType, ValueType>
, you can print it like this:
for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
On macOS (El Capitan). You can simply use: brew install postgresql
Check gradle console tab in android studio (by default in bottom right corner). In my case there were errors like this:
C:\Users\Jozef Bar??k\.gradle\caches\transforms-1\files-1.1\appcompat-v7-25.4.0.aar\d68bb9d2059935a7891196f4dfb81686\res\drawable-hdpi-v4\abc_ic_menu_share_mtrl_alpha.png: error: file not found.
Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
:app:mergeDebugResources FAILED
I solved the issue setting gradle user home to another location without white or special characters:
C:\Android\.gradle
You can configure it setting "Service directory path" in Gradle settings dialog. In my case it was necessary to delete old .gradle directory on previous location and restart android studio.
I just posted a slight variation on some of the examples above on another thread (Finding perfect squares) and thought I'd include a slight variation of what I posted there here (using nsqrt as a temporary variable), in case it's of interest / use:
import math
def is_square(n):
if not (isinstance(n, int) and (n >= 0)):
return False
else:
nsqrt = math.sqrt(n)
return nsqrt == math.trunc(nsqrt)
It is incorrect for a large non-square such as 152415789666209426002111556165263283035677490.
what about simply this:
byte[] args2 = getByteArry();
String byteStr = new String(args2);
object-fit
, behaves like background-size
, solving the issue of scaling images up and down to fit.
The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
.cover img {
width: 100%;
height: 100%;
object-fit: cover;
overflow: hidden;
}
There's no IE support, and support in Edge begins at v16, only for img
element: https://caniuse.com/#search=object-fit
The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo.
For Edge pre v16, and ie9, ie10, ie11:
You can crop and scale any image using CSS
object-fit
andobject-position
. However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers.If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an
<svg>
, and using theviewBox
andpreserveAspectRatio
attributes to do whatobject-fit
andobject-position
do.http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap
(The author explains the technique thoroughly, and duplicating the detail here would be impractical.)
The best way is to combine these, so it will hide the back button even if you set it up manually :
self.navigationItem.leftBarButtonItem=nil;
self.navigationItem.hidesBackButton=YES;
ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()
This should be different from int(time.time())
, but it is safe to use something like x % (60*60*24)
datetime — Basic date and time types:
Unlike the time module, the datetime module does not support leap seconds.
This is just an explanation not addressed in other answers
At least in recent versions of Mysql, your first query is not committed.
If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.
What's going on?
When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.
So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE
, UPDATE
, INSERT
or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT
) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).
That's why the solution involves declaring handlers to immediately ROLLBACK
when an error happens.
Extra
Inside the handler you can also re-raise the error using RESIGNAL
, otherwise the stored procedure executes "Successfully"
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
#.. Query 1 ..
#.. Query 2 ..
#.. Query 3 ..
COMMIT;
END
The commented out version is the more correct way to do this.
If you use the ==
operator on strings, you're comparing the strings' addresses (where they're allocated in memory) rather than the values of the strings. This is very occasional useful (it indicates you have the exact same string object), but 99% of the time you want to compare the values, which you do like so:
if([myT isEqualToString:@"10"] || [myT isEqualToString:@"11"] || [myT isEqualToString:@"12"])
I found the xmessage command, which is sort of good enough.
You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:
http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/
CREATE OR REPLACE FUNCTION update_modified_column() RETURNS TRIGGER AS $$ BEGIN NEW.modified = now(); RETURN NEW; END; $$ language 'plpgsql';
Apply the trigger like this:
CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE update_modified_column();
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
class MyQueue {
Stack<Integer> input;
Stack<Integer> output;
/** Initialize your data structure here. */
public MyQueue() {
input = new Stack<Integer>();
output = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return output.pop();
}
/** Get the front element. */
public int peek() {
if(output.isEmpty()) {
while(!input.isEmpty()) {
output.push(input.pop());
}
}
return output.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return input.isEmpty() && output.isEmpty();
}
}
This flexbox principle also works horizontally
During calculations of flex bases and flexible lengths, auto margins
are treated as 0.
Prior to alignment via justify-content and
align-self, any positive free space is distributed to auto margins in
that dimension.
Setting an automatic left margin for the Last Item will do the work.
.last-item {
margin-left: auto;
}
Code Example:
.container {_x000D_
display: flex;_x000D_
width: 400px;_x000D_
outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
margin: 5px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p class="last-item"></p>_x000D_
</div>
_x000D_
This can be very useful for Desktop Footers.
As Envato did here with the company logo.
On the unstaged file, click on the three dots on the right side. Once you click it, a popover menu will appear where you can then Discard file
.
It basically tells the program when you encounter an error just continue at the next line.
You're getting the toString()
value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,
Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);
Please read the tutorial on how to use it as it will explain all.
Edit
Please look here: Scanner tutorial
Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.
Even shorter way, may require newer ASP.Net:
string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)
The UriComponents enum lets you specify which component(s) of the URI you want to include.
There is a performance issue related with the left join as well as full join with large data.
In my opinion this is the best solution:
select [First Name], count(1) e from (select * from [Temp Test Data] union all select * from [Temp Test Data 2]) a group by [First Name] having e = 1
The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.
List<int> ints = new List<int>( new[] {1,5,7}); // 1
List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2
var i = 5;
var x = ints.Contains(i); // return true or false
In most of the cases, if you are unable to export the certificate as a PFX (including the private key) is because MMC/IIS cannot find/don't have access to the private key (used to generate the CSR). These are the steps I followed to fix this issue:
Hope this helps!
In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.
Right click your project file on the Solution Explorer, select Add
, then New item
(or CTRL+SHIFT+A). There you can find Application Manifest File
.
The file name is app.manifest.
As per bash - The Set Builtin manual, if -e
/errexit
is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.
By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail
option is enabled (it's disabled by default).
If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.
If you'd like to execute something on exit, try defining trap
, for example:
trap onexit EXIT
where onexit
is your function to do something on exit, like below which is printing the simple stack trace:
onexit(){ while caller $((n++)); do :; done; }
There is similar option -E
/errtrace
which would trap on ERR instead, e.g.:
trap onerr ERR
Zero status example:
$ true; echo $?
0
Non-zero status example:
$ false; echo $?
1
Negating status examples:
$ ! false; echo $?
0
$ false || true; echo $?
0
Test with pipefail
being disabled:
$ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
1
Test with pipefail
being enabled:
$ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
1
You can use a SqlDataAdapter
:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
DateTime values should be inserted as if they are strings surrounded by single quotes
'20201231'
but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME)
to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:
CREATE TABLE dbo.T(D DATETIME)
--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')
--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))
I also had this issue and ended up using Andy's code to create a function to clean things up when multiple commands need to be run.
It'll return stderr, stdout, and exit codes as objects. One thing to note: the function won't accept .\
in the path; full paths must be used.
Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $commandPath
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $commandArguments
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
[pscustomobject]@{
commandTitle = $commandTitle
stdout = $p.StandardOutput.ReadToEnd()
stderr = $p.StandardError.ReadToEnd()
ExitCode = $p.ExitCode
}
}
Here's how to use it:
$DisableACMonitorTimeOut = Execute-Command -commandTitle "Disable Monitor Timeout" -commandPath "C:\Windows\System32\powercfg.exe" -commandArguments " -x monitor-timeout-ac 0"
Short answer: I don't think so. C# .Net is compiled (to bytecode) and can't evaluate strings at runtime, as far as I know. JScript .Net can, however; but I would still advise you to code a parser and stack-based evaluator yourself.
You can also do this.
//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName");
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);
Try this in your console:
javac {$PathToYourProyect}/*
If you also need any external library, try:
javac -cp {$PathToYourLibrary}.jar {$PathToYourProyect}/*
Angular ui-router supports nested views. I haven't used it yet but looks very promising.
In newer versions of angular (I'm using 1.3) you can basically set the model and the value and the double binding do all the work this example works like a charm:
angular.module('radioExample', []).controller('ExampleController', ['$scope', function($scope) {_x000D_
$scope.color = {_x000D_
name: 'blue'_x000D_
};_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
<html>_x000D_
<body ng-app="radioExample">_x000D_
<form name="myForm" ng-controller="ExampleController">_x000D_
<input type="radio" ng-model="color.name" value="red"> Red <br/>_x000D_
<input type="radio" ng-model="color.name" value="green"> Green <br/>_x000D_
<input type="radio" ng-model="color.name" value="blue"> Blue <br/>_x000D_
<tt>color = {{color.name}}</tt><br/>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
If you're using a variable when searching in a string, mysql_real_escape_string()
is good for you. Just my suggestion:
$char = "and way's 'hihi'";
$myvar = mysql_real_escape_string($char);
select * from tablename where fields like "%string $myvar %";
window.onload = function() {
var userImage = document.getElementById('imageOtherUser');
var hangoutButton = document.getElementById("hangoutButtonId");
userImage.onclick = function() {
hangoutButton.click(); // this will trigger the click event
};
};
this will do the trick
This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.
As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left,
this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}
.
This method wraps the prerequisites in a promise and calls pdf.save()
in the finally()
method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.
// Get List of paged elements._x000D_
let elems = document.querySelectorAll('.elemClass');_x000D_
let pdf = new jsPDF("portrait", "mm", "a4");_x000D_
_x000D_
// Fix Graphics Output by scaling PDF and html2canvas output to 2_x000D_
pdf.scaleFactor = 2;_x000D_
_x000D_
// Create a new promise with the loop body_x000D_
let addPages = new Promise((resolve,reject)=>{_x000D_
elems.forEach((elem, idx) => {_x000D_
// Scaling fix set scale to 2_x000D_
html2canvas(elem, {scale: "2"})_x000D_
.then(canvas =>{_x000D_
if(idx < elems.length - 1){_x000D_
pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
pdf.addPage();_x000D_
} else {_x000D_
pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
console.log("Reached last page, completing");_x000D_
}_x000D_
})_x000D_
_x000D_
setTimeout(resolve, 100, "Timeout adding page #" + idx);_x000D_
})_x000D_
_x000D_
addPages.finally(()=>{_x000D_
console.log("Saving PDF");_x000D_
pdf.save();_x000D_
});
_x000D_
In my case there is a textView in my Viewpager, on a button click in mainActivity I want to change the color of that textView and update pagerAdapter. On the button Click I saved the color in SharedPreference and update pagerAdapter, that it can update the color taken from shared prefrence. So, I update viewPager view the following way .
btn_purple.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int color = ContextCompat.getColor(mContext, R.color.colorPrimaryDark2);
editor.putInt("sahittoFontColor", color);
editor.apply();
toNotifyDatasetChanged();
}
});
now the update method :
private void toNotifyDatasetChanged (){
if(viewPager!=null&& pagerAdapter!=null) {
viewPager.setAdapter(null);
viewPager.setAdapter(pagerAdapter);
}
}
And my pagerAdapter Was :
pagerAdapter = new Sahitto_ViewPagerAdapter (mContext, filenameParameter, 30, lineList);
viewPager.setAdapter(pagerAdapter);
And in instantiateItem was (in PagerAdapter) :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
int bnfntcolor=settings.getInt("sahittoFontColor", 0);
if (bnfntcolor!=0){
textView.setTextColor(bnfntcolor);
}
Thus, when I click the button, the color changes immediately in pagerAdapter's Textview.
Happy coding.
I think the best way is to store them in some yml file and then load that file using this command in intializer file
APP_CONFIG = YAML.load_file("#{Rails.root}/config/CONFIG.yml")[Rails.env].to_hash
you can easily access environment related config variables.
Your Yml file key value structure:
development:
app_key: 'abc'
app_secret: 'abc'
production:
app_key: 'xyz'
app_secret: 'ghq'
I had a recent issue with an update to Swift 5 where the table view would flash select and then deselect the selected cell. I tried several of the solutions here and none worked. The solution is setting clearsSelectionOnViewWillAppear
to false.
I had previously used the UIView and selectedBackgroundColor property, so I kept with that approach.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "popoverCell", for: indexPath) as! PopoverCell
let backgroundView = UIView()
backgroundView.backgroundColor = Color.Blue
cell.selectedBackgroundView = backgroundView
}
Below are the changes I needed for Swift 5. The property clearsSelectionOnViewWillAppear
was the reason my cells were deselecting. The following select was necessary on first load.
override func viewDidLoad() {
super.viewDidLoad()
clearsSelectionOnViewWillAppear = false
popoverTableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none)
}
If you're using the default http client, here's how to do it using the default http params:
HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);
Original credit goes to http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If your working at a company, they may be preventing you from downloading outside software and installing it. You may need to install the plugins manually or repoint to an internal mirror repository.
I spent days writing my own custom tool to parallelize the copies required for this, but then I ran across documentation on how to get the AWS S3 CLI sync command to synchronize buckets with massive parallelization. The following commands will tell the AWS CLI to use 1,000 threads to execute jobs (each a small file or one part of a multipart copy) and look ahead 100,000 jobs:
aws configure set default.s3.max_concurrent_requests 1000
aws configure set default.s3.max_queue_size 100000
After running these, you can use the simple sync command as follows:
aws s3 sync s3://source-bucket/source-path s3://destination-bucket/destination-path
On an m4.xlarge machine (in AWS--4 cores, 16GB RAM), for my case (3-50GB files) the sync/copy speed went from about 9.5MiB/s to 700+MiB/s, a speed increase of 70x over the default configuration.
Update: Note that S3CMD has been updated over the years and these changes are now only effective when you're working with lots of small files. Also note that S3CMD on Windows (only on Windows) is seriously limited in overall throughput and can only achieve about 3Gbps per process no matter what instance size or settings you use. Other systems like S5CMD have the same problem. I've spoken to the S3 team about this and they're looking into it.
.outside {
width: 200px;
height: 200px;
background-color: #EEE; /*to make it visible*/
}
Needs to be
.outside {
position: relative;
width: 200px;
height: 200px;
background-color: #EEE; /*to make it visible*/
}
Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.
The (very) short answer to your question is that paintComponent
is called "when it needs to be." Sometimes it's easier to think of the Java Swing GUI system as a "black-box," where much of the internals are handled without too much visibility.
There are a number of factors that determine when a component needs to be re-painted, ranging from moving, re-sizing, changing focus, being hidden by other frames, and so on and so forth. Many of these events are detected auto-magically, and paintComponent
is called internally when it is determined that that operation is necessary.
I've worked with Swing for many years, and I don't think I've ever called paintComponent
directly, or even seen it called directly from something else. The closest I've come is using the repaint()
methods to programmatically trigger a repaint of certain components (which I assume calls the correct paintComponent
methods downstream.
In my experience, paintComponent
is rarely directly overridden. I admit that there are custom rendering tasks that require such granularity, but Java Swing does offer a (fairly) robust set of JComponents and Layouts that can be used to do much of the heavy lifting without having to directly override paintComponent
. I guess my point here is to make sure that you can't do something with native JComponents and Layouts before you go off trying to roll your own custom-rendered components.
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
In my case, the dump file I restored had these commands.
CREATE SCHEMA employees;
SET search_path = employees, pg_catalog;
I've commented those and restored again. The issue got resolved
Note that from Netbeans 8 there is no Run panel in the project Properties.
To do what you want I simply add the following line (example setting the locale) in my project's properties file:
run.args.extra=--locale fr:FR
Jason's code can not be used for elements inside an iframe (as the scope differs from window and document). I fixed that problem and I modified it in order to be used as any other jQuery plugin (chainable):
Example 1: Selection of all text inside < code > tags with single click and add class "selected":
$(function() {
$("code").click(function() {
$(this).selText().addClass("selected");
});
});
Example 2: On button click, select an element inside an Iframe:
$(function() {
$("button").click(function() {
$("iframe").contents().find("#selectme").selText();
});
});
Note: remember that the iframe source should reside in the same domain to prevent security errors.
jQuery Plugin:
jQuery.fn.selText = function() {
var obj = this[0];
if ($.browser.msie) {
var range = obj.offsetParent.createTextRange();
range.moveToElementText(obj);
range.select();
} else if ($.browser.mozilla || $.browser.opera) {
var selection = obj.ownerDocument.defaultView.getSelection();
var range = obj.ownerDocument.createRange();
range.selectNodeContents(obj);
selection.removeAllRanges();
selection.addRange(range);
} else if ($.browser.safari) {
var selection = obj.ownerDocument.defaultView.getSelection();
selection.setBaseAndExtent(obj, 0, obj, 1);
}
return this;
}
I tested it in IE8, Firefox, Opera, Safari, Chrome (current versions). I'm not sure if it works in older IE versions (sincerely I don't care).
<script>
is HTML 5.
<script type='text/javascript'>
is HTML 4.x (and XHTML 1.x).
<script language="javascript">
is HTML 3.2.
Is it different for different webservers?
No.
when I did an offline javascript test, i realised that i need the
<script type = 'text/javascript'>
tag.
That isn't the case. Something else must have been wrong with your test case.
Yes. Take a look at this other thread for details: How to apply CSS to iframe?
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].document.body.appendChild(cssLink);
It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree
it's probably OSError
:
>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
If you want to silently ignore that error, you would do:
try:
shutil.rmtree(path)
except OSError:
pass
Why? Say you (somehow) accidently pass the function an integer instead of a string, like:
shutil.rmtree(2)
It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.
If you definitely want to ignore all errors, catch Exception
rather than a bare except:
statement. Again, why?
Not specifying an exception catches every exception, including the SystemExit
exception which for example sys.exit()
uses:
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
Compare this to the following, which correctly exits:
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
If you want to write ever better behaving code, the OSError
exception can represent various errors, but in the example above we only want to ignore Errno 2
, so we could be even more specific:
import errno
try:
shutil.rmtree(path)
except OSError as e:
if e.errno != errno.ENOENT:
# ignore "No such file or directory", but re-raise other errors
raise
If you have this in your CSS file:
.myApp
{
border-bottom-color:#FF0000;
}
and a div for instance of:
<div id="myDiv">test text</div>
you can use:
$("#myDiv").addClass('myApp');// to add the style
$("#myDiv").removeClass('myApp');// to remove the style
or you can just use
$("#myDiv").css( 'border-bottom-color','#FF0000');
I prefer the first example, keeping all the CSS related items in the CSS files.
We can use
Model::whereNotNull('sent_at');
Or
Model::whereRaw('sent_at is not null');
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
You can create a custom link as described here using a small jQuery script
$('.linkPinIt').click(function(){
var url = $(this).attr('href');
var media = $(this).attr('data-image');
var desc = $(this).attr('data-desc');
window.open("//www.pinterest.com/pin/create/button/"+
"?url="+url+
"&media="+media+
"&description="+desc,"_blank","top=0,right=0,width=750,height=320");
return false;
});
this will work for all links with class linkPinIt
which have the image and the description stored in the HTML 5 data attributes data-image
and data-desc
<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F"
data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg"
data-desc="Title for Pinterest Photo" class="linkPinIt">
Pin it!
</a>
see this jfiddle example
There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.
name = gets
"mukesh\n"
You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type
name = gets
you will see somethings like"mukesh\n"
You can get rid of pesky newline character using chomp method.
The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.
name = gets.chomp
"mukesh"
You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.
When written inside your Ruby program, ARGV will take take a command line command that looks like this:
test.rb hi my name is mukesh
and create an array that looks like this:
["hi", "my", "name", "is", "mukesh"]
But, if I want to passed limited input then we can use something like this.
test.rb 12 23
and use those input like this in your program:
a = ARGV[0]
b = ARGV[1]
We can use javascript DOMParser
for special characters conversion.
const parser = new DOMParser();
const convertedValue = (parser.parseFromString("' & ' < >", "application/xml").body.innerText;
You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key
By mid-2016 the Chromium engine (v53) supports just 3 emphasis styles:
Plain text, bold, and super-bold...
<div style="font:normal 400 14px Arial;">Testing</div>
<div style="font:normal 700 14px Arial;">Testing</div>
<div style="font:normal 800 14px Arial;">Testing</div>
Use Son Of Strike which has a command ObjSize
.
Note that actual memory consumed is always larger than ObjSize
reports due to a synkblk
which resides directly before the object data.
Read more about both here MSDN Magazine Issue 2005 May - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects.
IMHO there are three reasons to use OpenGL ES in a game:
Drawing text is always a problem in game design, because you are drawing things, so you cannot have the look and feel of a common activity, with widgets and so on.
You can use a framework to generate Bitmap fonts from TrueType fonts and render them. All the frameworks I've seen operate the same way: generate the vertex and texture coordinates for the text in draw time. This is not the most efficient use of OpenGL.
The best way is to allocate remote buffers (vertex buffer objects - VBOs) for the vertices and textures early in code, avoiding the lazy memory transfer operations in draw time.
Keep in mind that game players don't like to read text, so you won't write a long dynamically generated text. For labels, you can use static textures, leaving dynamic text for time and score, and both are numeric with a few characters long.
So, my solution is simple:
Draw operations are fast, if you use remote static buffers.
I create an XML file with screen positions (based on screen's diagonal percentage) and textures (static and characters), and then I load this XML before rendering.
To get a high FPS rate, you should avoid generating VBOs at draw time.
Try this
link_to "+ Service", my_services_new_path(:account_id => acct.id)
it will pass the account_id as you want.
For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.backgroundColor = .black
blurEffectView.alpha = 0.5
blurEffectView.frame = topView.bounds
if !self.presenting {
blurEffectView.frame.origin.x = 0
} else {
blurEffectView.frame.origin.x = -topView.frame.width
}
blurEffectView.frame.origin.x = -topView.frame.width
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) {
if !self.presenting {
blurEffectView.frame.origin.x = -topView.frame.width
} else {
blurEffectView.frame.origin.x = 0
}
view.addSubview(blurEffectView)
} completion: { (status) in
}
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
You can reset both the user and workspace settings in VS Code as shown in the following images
i = Your_int_value
Write bytes value like this for example:
the_file.write(i.to_bytes(2,"little"))
Depend of you int value size and the bit order your prefer
It looks like the latest version of anaconda forces install of pyqt5.6 over any pyqt build, which will be fatal for your applications. In a terminal, Try:
conda install -c anaconda pyqt=4.11.4
It will prompt to downgrade conda client. After that, it should be good.
UPDATE: If you want to know what pyqt versions are available for install, try:
conda search pyqt
UPDATE: The most recent version of conda installs anaconda-navigator. This depends on qt5, and should first be removed:
conda uninstall anaconda-navigator
Then install "newest" qt4:
conda install qt=4
This lists all the gems I have installed.
gem query --local
http://guides.rubygems.org/command-reference/#gem-list
See 2.7 Listing all installed gems
Just set these in php.ini:
upload_max_filesize = 1000M;
post_max_size = 1000M;
I faced the same problem on Mac OS X and with Miniconda. After trying many of the proposed solutions for hours I found that I needed to correctly set Condas environment – specifically requests environment variable – to use the Root certificate that my company provided rather than the generic ones that Conda provides.
Here is how I solved it:
openssl x509 -inform der -in /path/to/your/certificate.cer -out /path/to/converted/certificate.pem
export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem
.bshrs
or e.g. .zshrc
) and add this line: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem
. Now exit your terminal/shell and reopen. Check again. You should be set and Conda should work fine.
There is another way to draw a circle - draw it in fragment shader. Create a quad:
float right = 0.5;
float bottom = -0.5;
float left = -0.5;
float top = 0.5;
float quad[20] = {
//x, y, z, lx, ly
right, bottom, 0, 1.0, -1.0,
right, top, 0, 1.0, 1.0,
left, top, 0, -1.0, 1.0,
left, bottom, 0, -1.0, -1.0,
};
Bind VBO:
unsigned int glBuffer;
glGenBuffers(1, &glBuffer);
glBindBuffer(GL_ARRAY_BUFFER, glBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*20, quad, GL_STATIC_DRAW);
and draw:
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_VALUE);
glVertexAttribPointer(ATTRIB_VERTEX , 3, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(ATTRIB_VALUE , 2, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(12));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
Vertex shader
attribute vec2 value;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
varying vec2 val;
void main() {
val = value;
gl_Position = projectionMatrix*viewMatrix*vertex;
}
Fragment shader
varying vec2 val;
void main() {
float R = 1.0;
float R2 = 0.5;
float dist = sqrt(dot(val,val));
if (dist >= R || dist <= R2) {
discard;
}
float sm = smoothstep(R,R-0.01,dist);
float sm2 = smoothstep(R2,R2+0.01,dist);
float alpha = sm*sm2;
gl_FragColor = vec4(0.0, 0.0, 1.0, alpha);
}
Don't forget to enable alpha blending:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
UPDATE: Read more
Somewhat late to the party, but I included this in my MarkUtils-Web library in WebUtils - Checkstyle-approved and JUnit-tested:
import javax.servlet.http.HttpServletRequest;
public class GetRequestUrl{
/**
* <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
* (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
* that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
* <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
* >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
* @author Mark A. Ziesemer
* <a href="http://www.ziesemer.com."><www.ziesemer.com></a>
*/
public String getRequestUrl(final HttpServletRequest req){
final String scheme = req.getScheme();
final int port = req.getServerPort();
final StringBuilder url = new StringBuilder(256);
url.append(scheme);
url.append("://");
url.append(req.getServerName());
if(!(("http".equals(scheme) && (port == 0 || port == 80))
|| ("https".equals(scheme) && port == 443))){
url.append(':');
url.append(port);
}
url.append(req.getRequestURI());
final String qs = req.getQueryString();
if(qs != null){
url.append('?');
url.append(qs);
}
final String result = url.toString();
return result;
}
}
Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.
See also:
This seems to be the cleanest way to do
if (foo === 1) {
} else if (bar === 99) {
} else if (foo === 2) {
} else {
}
in the template:
<ng-container *ngIf="foo === 1; else elseif1">foo === 1</ng-container>
<ng-template #elseif1>
<ng-container *ngIf="bar === 99; else elseif2">bar === 99</ng-container>
</ng-template>
<ng-template #elseif2>
<ng-container *ngIf="foo === 2; else else1">foo === 2</ng-container>
</ng-template>
<ng-template #else1>else</ng-template>
Notice that it works like a proper else if
statement should when the conditions involve different variables (only 1 case is true at a time). Some of the other answers don't work right in such a case.
aside: gosh angular, that's some really ugly else if
template code...
use NPOI to read and write excel..it's free and open source
for exapmle
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
//.....
private void button1_Click(object sender, EventArgs e)
{
HSSFWorkbook hssfwb;
using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
{
hssfwb= new HSSFWorkbook(file);
}
ISheet sheet = hssfwb.GetSheet("Arkusz1");
for (int row = 0; row <= sheet.LastRowNum; row++)
{
if (sheet.GetRow(row) != null) //null is when the row only contains empty cells
{
MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
}
}
}
see this Stackoverflow question
This should be everything you need :
<meta name='viewport'
content='width=device-width, initial-scale=1.0, maximum-scale=1.0,
user-scalable=0' >
This works successfully.
INSERT INTO DestinationDB.dbo.DestinationTable (col1,col1)
SELECT Src-col1,Src-col2 FROM SourceDB.dbo.SourceTable
Try this
div#ImageContainer { width: 600px; }
#ImageContainer img{ max-width: 600px}
I managed to make it work with alpha28 like this:
import {Component, View} from 'angular2/angular2';
@Component({
selector: 'circle',
properties: ['color: color'],
})
@View({
template: `<style>
.circle{
width:50px;
height: 50px;
border-radius: 25px;
}
</style>
<div class="circle" [style.background-color]="changeBackground()">
<content></content>
</div>
`
})
export class Circle {
color;
constructor(){
}
changeBackground(): string {
return this.color;
}
}
and called it like this <circle color='yellow'></circle>
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
For those coming across this in the future:
If you would like to see a list of relations for several schemas:
$psql mydatabase
mydatabase=# SET search_path TO public, usa; #schema examples
SET
mydatabase=# \dt
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------
public | counties | table | postgres
public | spatial_ref_sys | table | postgres
public | states | table | postgres
public | us_cities | table | postgres
usa | census2010 | table | postgres
Use Series.view
for convert boolean to integers:
df["somecolumn"] = df["somecolumn"].view('i1')
This question is quite old and the problem seems to have been solved, but if only to remind myself next time I am facing this problem, here is another solution (tested only on Windows 10, though).
The shortcut for the jupyter notebook (be it from the start menu, a desktop shortcut or pinned to the taskbar) calls a number of Scripts (presumably to initialize the jupyter notebook etc.), which are written in the Target text field from the shortcut's Properties window
.
Appending
--notebook-dir='C:/Your/Desired/Start/Directory/'
should start the notebook in the specified directory (as @Victor O pointed out, it cannot be a drive, but has to be a folder).
If that doesn't do the trick, it can't hurt to also add the same directory to the Start in field.
Note: I used forward-slashes in the Target field and back-slashes in the Start in field. Feel free to change that up, if you are curious which combinations are working.
Also, this was not my idea, but I forgot where it came from (I checked the shortcut from my previous installation, because I was sure not to have tried anything from this page, but the proposed way from the link the OP provided.). If anyone wants to supply the link, please do so.
Sorry if I can't add any fundamental research to this, but the solution worked for me on four separate systems and is fairly simple to implement.
Why not just using
<div [ngClass]="classes"> </div>
https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
A slightly simpler method:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
<View style={{flexDirection:'row'}}>
<Text style={{flex: 1, flexWrap: 'wrap'}}>
This will work
Use this commands
DEBUG_LEVEL=all node file.js
DEBUG=* node file.js
node file.js --inspect
Better way, with solution to tab and chrome problem and new jquery way
$("#element").on("focus keyup", function(e){
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if(keycode === 9 || !keycode){
// Hacemos select
var $this = $(this);
$this.select();
// Para Chrome's que da problema
$this.on("mouseup", function() {
// Unbindeamos el mouseup
$this.off("mouseup");
return false;
});
}
});
I am just mentioning how to get all the column names from a csv file. I am using pandas library.
First we read the file.
import pandas as pd
file = pd.read_csv('details.csv')
Then, in order to just get all the column names as a list from input file use:-
columns = list(file.head(0))
This might be helpful
from bs4 import UnicodeDammit
with open('automate_data/billboard.csv', 'rb') as file:
content = file.read()
suggestion = UnicodeDammit(content)
suggestion.original_encoding
#'iso-8859-1'
@{var listItems = new List<ListItem>
{
new ListItem { Text = "Exemplo1", Value="Exemplo1" },
new ListItem { Text = "Exemplo2", Value="Exemplo2" },
new ListItem { Text = "Exemplo3", Value="Exemplo3" }
};
}
@Html.DropDownList("Exemplo",new SelectList(listItems,"Value","Text"))
The +
operator should do the trick just fine. Keep something in mind though, if one of the columns is null or does not have any value, it will give you a NULL
result. Instead, combine +
with the function COALESCE
and you'll be set.
Here is an example:
SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1.
For this example, if column1
is NULL
, then the results of column2
will show up, instead of a simple NULL
.
Hope this helps!
For your case Elasticdump is the perfect answer.
First, you need to download the mapping and then the index
# Install the elasticdump
npm install elasticdump -g
# Dump the mapping
elasticdump --input=http://<your_es_server_ip>:9200/index --output=es_mapping.json --type=mapping
# Dump the data
elasticdump --input=http://<your_es_server_ip>:9200/index --output=es_index.json --type=data
If you want to dump the data on any server I advise you to install esdump through docker. You can get more info from this website Blog Link
You can try this if you want date time string:
use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"
If you want timestamp, you can try:
use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328
i found textView.setTypeface(Typeface.DEFAULT_BOLD);
to be the simplest method.
Why not simply use
function addDays(theDate, days) {
return new Date(theDate.getTime() + days*24*60*60*1000);
}
var newDate = addDays(new Date(), 5);
or -5 to remove 5 days
Since youre using JSON, I would Base64 Encode it before sending it across the wire.
If the files are large, try to look at BSON, or some other format that is better with binary transfers.
You could also zip the files, if they compress well, before base64 encoding them.
I was looking for a way to do this myself and figured out a simple solution.
I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:
Project -> Properties -> Linker -> System -> Subsystem
And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.
Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.
So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.
The starting part of your program should now look something like this:
#include <iostream>
using namespace std;
// Main function for the console
int main(){
// Calling the wWinMain function to start the GUI program
// Parameters:
// GetModuleHandle(NULL) - To get a handle to the current instance
// NULL - Previous instance is not needed
// NULL - Command line parameters are not needed
// 1 - To show the window normally
wWinMain(GetModuleHandle(NULL), NULL,NULL, 1);
system("pause");
return 0;
}
// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
// This will display "Hello World" in the console as soon as the GUI begins.
cout << "Hello World" << endl;
.
.
.
Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
i % 2 == 0
If you are just opened a new java project then create a new folder src/ in the man project location.
Then cut and paste all your package in that folder.
Then Right click on src directory and select option Mark Directory As > Sources Root.
For postgres, I found it easier and more accurate to use the
function, like:
select name, sum(count), date_trunc('minute',timestamp) as timestamp
FROM table
WHERE xxx
GROUP BY name,date_trunc('minute',timestamp)
ORDER BY timestamp
You can provide various resolutions like 'minute','hour','day' etc... to date_trunc.
It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".
maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi
Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.
I had this problem in laravel migration too
the order of drop tables in down() method does matter
Schema::dropIfExists('groups');
Schema::dropIfExists('contact');
may not work, but if you change the order, it works.
Schema::dropIfExists('contact');
Schema::dropIfExists('groups');