this also might be relevant to anyone using React -
install react-moment (npm i react-moment
)
import Moment from 'react-moment'
<Moment format="MM/DD/YYYY">{yourTimeStamp}</Moment>
(or any other format you'd like)
I have found out that is important where you call android.support.v4.app.Fragment.requestPermissions
.
If you do it in onCreate()
, onRequestPermissionsResult()
is never called.
Solution: Call it in onActivityCreated()
;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED)
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 0);
}
Check this out. The output is worth thousand words.
var b1 = document.getElementById("b1");_x000D_
_x000D_
checkif("1, no argument" );_x000D_
checkif("2, undefined explicitly", undefined);_x000D_
checkif("3, null explicitly", null);_x000D_
checkif("4, the 0", 0);_x000D_
checkif("5, empty string", '');_x000D_
checkif("6, string", "string");_x000D_
checkif("7, number", 123456);_x000D_
_x000D_
function checkif (a1, a2) {_x000D_
print("\ncheckif(), " + a1 + ":");_x000D_
if (a2 == undefined) {_x000D_
print("==undefined: YES");_x000D_
} else {_x000D_
print("==undefined: NO");_x000D_
}_x000D_
if (a2 === undefined) {_x000D_
print("===undefined: YES");_x000D_
} else {_x000D_
print("===undefined: NO");_x000D_
}_x000D_
if (a2 == null) {_x000D_
print("==null: YES");_x000D_
} else {_x000D_
print("==null: NO");_x000D_
}_x000D_
if (a2 === null) {_x000D_
print("===null: YES");_x000D_
} else {_x000D_
print("===null: NO");_x000D_
}_x000D_
if (a2 == '') {_x000D_
print("=='': YES");_x000D_
} else {_x000D_
print("=='': NO");_x000D_
}_x000D_
if (a2 === '') {_x000D_
print("==='': YES");_x000D_
} else {_x000D_
print("==='': NO");_x000D_
}_x000D_
if (isNaN(a2)) {_x000D_
print("isNaN(): YES");_x000D_
} else {_x000D_
print("isNaN(): NO");_x000D_
}_x000D_
if (a2) {_x000D_
print("if-?: YES");_x000D_
} else {_x000D_
print("if-?: NO");_x000D_
}_x000D_
print("typeof(): " + typeof(a2));_x000D_
}_x000D_
_x000D_
function print(v) {_x000D_
b1.innerHTML += v + "\n";_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<pre id="b1"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
See also:
Cheers!
Instead of dtAll = dtOne.Copy();
in Jeromy Irvine's answer you can start with an empty DataTable
and merge one-by-one iteratively:
dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...
and so on.
This technique is useful in a loop where you want to iteratively merge data tables:
DataTable dtAllCountries = new DataTable();
foreach(String strCountry in listCountries)
{
DataTable dtCountry = getData(strCountry); //Some function that returns a data table
dtAllCountries.Merge(dtCountry);
}
background:url(bgimage.jpg) no-repeat; background-size: cover;
This did the trick
I had the same problem on Win 7. The solution was to remove following files:
As for .hg/store/lock - there was no such file.
It'll vary depending on resources, but you could run the script bellow and see for yourself ;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
Some reference numbers (on an old CoreDuo machine)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
It seems that using the []
or {}
operators is more or less the same.
Here is an example of how to create an UnsignedLong current Timestamp:
UnsignedLong current = new UnsignedLong(new Timestamp(new Date().getTime()).getTime());
Are you using the userdir mod?
In that case the thing is that PHP5 seems to be disabling running scripts from that location by default and you have to comment out the following lines:
<IfModule mod_userdir.c>
<Directory /home/*/public_html>
php_admin_flag engine Off
</Directory>
</IfModule>
in /etc/apache2/mods-enabled/php5.conf
(on a ubuntu system)
If it is a Maven project then sometimes re-importing of it helps:
Hope it will resolve the issue.
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)
Why not just stream down the content with the correct content specifier?
That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.
To open the terminal:
Please find more about integrated terminal here https://code.visualstudio.com/docs/editor/integrated-terminal
Ideally these would go in a class called "FileNaming" or maybe just rename Encode to "FileNameEncode". Note: these are not designed to handle Full Paths, just the folder and/or file names. Ideally you would Split("/") your full path first and then check the pieces. And obviously instead of a union, you could just add the "%" character to the list of chars not allowed in Windows, but I think it's more helpful/readable/factual this way. Decode() is exactly the same but switches the Replace(Uri.HexEscape(s[0]), s) "escaped" with the character.
public static List<string> urlEncodedCharacters = new List<string>
{
"/", "\\", "<", ">", ":", "\"", "|", "?", "%" //and others, but not *
};
//Since this is a superset of urlEncodedCharacters, we won't be able to only use UrlEncode() - instead we'll use HexEncode
public static List<string> specialCharactersNotAllowedInWindows = new List<string>
{
"/", "\\", "<", ">", ":", "\"", "|", "?", "*" //windows dissallowed character set
};
public static string Encode(string fileName)
{
//CheckForFullPath(fileName); // optional: make sure it's not a path?
List<string> charactersToChange = new List<string>(specialCharactersNotAllowedInWindows);
charactersToChange.AddRange(urlEncodedCharacters.
Where(x => !urlEncodedCharacters.Union(specialCharactersNotAllowedInWindows).Contains(x))); // add any non duplicates (%)
charactersToChange.ForEach(s => fileName = fileName.Replace(s, Uri.HexEscape(s[0]))); // "?" => "%3f"
return fileName;
}
Thanks @simon-tewsi for the very usefull table above!
Here you can use set of folders from deletelist.txt while avoiding some patterns as well
foreach f (cat deletelist.txt)
rm -rf ls | egrep -v "needthisfile|*.cpp|*.h"
end
but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.
By starting out with smallest
set to Integer.MAX_VALUE
and largest
set to Integer.MIN_VALUE
, they don't have to worry later about the special case where smallest
and largest
don't have a value yet. If the data I'm looking through has a 10
as the first value, then numbers[i]<smallest
will be true (because 10
is <
Integer.MAX_VALUE
) and we'll update smallest
to be 10
. Similarly, numbers[i]>largest
will be true
because 10
is >
Integer.MIN_VALUE
and we'll update largest
. And so on.
Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest
and largest
.
Note the point Onome Sotu makes in the comments:
...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.
Which is true; here's a simpler example demonstrating the problem (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int value : values) {
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
}
}
To fix it, either:
Don't use else
, or
Start with smallest
and largest
equal to the first element, and then loop the remaining elements, keeping the else if
.
Here's an example of that second one (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = values[0];
int largest = values[0];
for (int n = 1; n < values.length; ++n) {
int value = values[n];
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 5
}
}
In your code $this->uri->segment(3)
refers to the pagination offset
which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;
, $this->uri->segment(3)
i.e segment 3 refers to the offset. The first segment is the controller
, second is the method
, there after comes the parameters
sent to the controllers as segments
.
The -I
directive does the job:
gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c
To convert a
Kotlin
source file to aJava
source file you need to (when you in Android Studio):
Press Cmd-Shift-A on a Mac, or press Ctrl-Shift-A on a Windows machine.
Type the action you're looking for: Kotlin Bytecode
and choose Show Kotlin Bytecode
from menu.
Decompile
button on the top of Kotlin Bytecode
panel.Another example for vertically and horizontally centered div or any object(s):
var obj = $("#divID");
var halfsc = $(window).height()/2;
var halfh = $(obj).height() / 2;
var halfscrn = screen.width/2;
var halfobj =$(obj).width() / 2;
var goRight = halfscrn - halfobj ;
var goBottom = halfsc - halfh;
$(obj).css({marginLeft: goRight }).css({marginTop: goBottom });
thanks for the answers. It helped me, but I had to improve it a bit for my needs. I had several pagestarts and finishes so I added a timer which checks if atfer the pagefinish is started a new pagestart. Okay, bad explanation. See the code :)
myWebView.setWebViewClient(new WebViewClient() {
boolean loadingFinished = true;
boolean redirect = false;
long last_page_start;
long now;
// Load the url
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(url);
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("p","pagestart");
loadingFinished = false;
last_page_start = System.nanoTime();
show_splash();
}
// When finish loading page
public void onPageFinished(WebView view, String url) {
Log.i("p","pagefinish");
if(!redirect){
loadingFinished = true;
}
//call remove_splash in 500 miSec
if(loadingFinished && !redirect){
now = System.nanoTime();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
remove_splash();
}
},
500);
} else{
redirect = false;
}
}
private void show_splash() {
if(myWebView.getVisibility() == View.VISIBLE) {
myWebView.setVisibility(View.GONE);
myWebView_splash.setVisibility(View.VISIBLE);
}
}
//if a new "page start" was fired dont remove splash screen
private void remove_splash() {
if (last_page_start < now) {
myWebView.setVisibility(View.VISIBLE);
myWebView_splash.setVisibility(View.GONE);
}
}
});
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
I solved it!!
For Razor the syntax is:
@Html.TextAreaFor(m=>m.Address, new { style="Width:174px" })
this adjusts the text area width to the width that i defined in the style parameter.
For ASPx the syntax is:
<%=Html.TextAreaFor(m => m.Description, new { cols = "20", rows = "15", style="Width:174px" })%>
this will do the trick
$
variables are only set to matches into the block:
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { "#{ $1.strip }" }
This is also the only way to call a method on the match. This will not change the match, only strip
"\1" (leaving it unchanged):
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1".strip)
The best solution is the word-spacing
property.
Add the <p>
in a container with a specific size (example 300px
) and after you have to add that size as the value in the word-spacing.
HTML
<div>
<p>Sentence Here</p>
</div>
CSS
div {
width: 300px;
}
p {
width: auto;
text-align: center;
word-spacing: 300px;
}
In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.
Here an example Codepen
You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:
auto f()
{
struct S
{
int a;
double b;
} s;
s.a = 42;
s.b = 42.0;
return s;
}
auto x = f();
a = x.a;
b = x.b;
Easy way with a touch of javascript
$("#myButton").click(function(event) {
var cont = confirm('Continue?');
if(cont) {
// do stuff here if OK was clicked
return true;
}
// If cancel was clicked button execution will be halted.
event.preventDefault();
}
I've seen those terms used interchangeably, but there are different ways of implementing it:
I would suspect that sticky might refer to the cookie way, and that affinity might refer to #2 and #3 in some contexts, but that's not how I have seen it used (or use it myself)
i use this
<style>
html, body{height:100%;margin:0;padding:0 0}
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:
android:background="#fff"
With TortoiseGit:
right click on the file and use
Context Menu ? Restore after commit
. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseGitMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.
If you visit this link https://msdn.microsoft.com/library/ms748948%28v=vs.100%29.aspx#Window_Lifetime_Events and scroll down to Window Lifetime Events it will show you the event order.
Open:
Close:
Generally, bash works better than python only in those environments where python is not available. :)
Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.
While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.
In this case, as snarly suggested, typing q is the intended way to quit git log
(as with most other pagers or applications that use pagers).
However normally, if you just want to abort a command that is currently executing, you can try ctrl+c (doesn't seem to work for git log
, however) or ctrl+z (although in bash, ctrl-z will freeze the currently running foreground process, which can then be thawed as a background process with the bg
command).
If the function is printing to System.out, you can capture that output by using the System.setOut method to change System.out to go to a PrintStream provided by you. If you create a PrintStream connected to a ByteArrayOutputStream, then you can capture the output as a String.
// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());
Version Code - It's a positive integer that's used for comparison with other version codes. It's not shown to the user, it's just for record-keeping in a way. You can set it to any integer you like but it's suggested that you linearly increment it for successive versions.
Version Name - This is the version string seen by the user. It isn't used for internal comparisons or anything, it's just for users to see.
For example: Say you release an app, its initial versionCode could be 1 and versionName could also be 1. Once you make some small changes to the app and want to publish an update, you would set versionName to "1.1" (since the changes aren't major) while logically your versionCode should be 2 (regardless of size of changes).
Say in another condition you release a completely revamped version of your app, you could set versionCode and versionName to "2".
Hope that helps.
You can read more about it here
Well, I have tried something I hope it helps ..
They changed the schema a little bit ..
Use the following :
1- Change the AccessDataSource to SQLDataSource in the toolbox.
2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)
3- Next -> Next -> Test Query -> Finish.
Worked for me.
find -iname "file_name"
Syntax :-
find -type type_descriptor file_name_here
type_descriptor types:-
f: regular file
d: directory
l: symbolic link
c: character devices
b: block devices
"Why does a scipy get so complicated?
It gets so complicated because Python's package management system is built to track Python package dependencies, and SciPy and other scientific tools have dependencies beyond Python. Wheels fix part of the problem, but my experience is that tools like pip
/virtualenv
are just not sufficient for installing and managing a scientific Python stack.
If you want an easy way to get up and running with SciPy, I would highly suggest the Anaconda distribution. It will give you everything you need for scientific computing in Python.
If you want a "short way" of doing this (I'm interpreting that as "I don't want to install a huge distribution"), you might try miniconda and then run conda install scipy
.
JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG
This works for me. Creating 5 windows with the given names and auto selecting to the home
window.
new -n home
neww -n emacs
neww -n puppet
neww -n haskell
neww -n ruby
selectw -t 1
If your database StartTime = 07:00:00
and endtime = 14:00:00
, and both are time type. Your query to get the time difference would be:
SELECT TIMEDIFF(Time(endtime ), Time(StartTime )) from tbl_name
If your database startDate = 2014-07-20 07:00:00
and endtime = 2014-07-20 23:00:00
, you can also use this query.
In javascript, make an ajax function,
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
Then call from html,
<a href="" onclick="myAjax()" class="deletebtn">Delete</a>
And in your ajax.php,
if($_POST['action'] == 'call_this') {
// call removeday() here
}
Check out python-nvd3. It is a python wrapper for nvd3. Looks cooler than d3.py and also has more chart options.
As of May 1st 2019, use BottomSheetTheme.
MaterialApp(
theme: ThemeData(
// Draw all modals with a white background and top rounded corners
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(10))
)
)
),
Introduced recently, using a theme to control the sheets style should be the most best to this problem.
If you want to theme different bottom sheets differently, include a new Theme object in the appropriate subtree to override the bottom sheet theme just for that area.
If for some reason you'd still like to override the theme manually when launching a bottom sheet, showBottomSheet and showModalBottomSheet now have a backgroundColor parameter. Use it like this:
showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (c) {return NavSheet();},
);
Using the theme allows bottom sheets to be re-used regardless of the app / app's current theme, and has none of the negative side effects of setting canvas color as mentioned.
For closing (not quit) the running application in Simulator the keyboard shortcut is "shift+command+h".
If you want to get first date of previous month , Then you can use as like following ... $prevmonth = date('M Y 1', strtotime('-1 months'));
what? first date will always be 1 :D
Go to prompt command and type "adb devices". If it is empty, then make sure you allowed for "MTP Transfer" or similar and you enabled debugging on your phone.
To enable debugging, follow this tutorial: https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm
Then type "adb devices" again. If a device is listed in there, then it should work now.
For anyone coming across this years later:
TL;DR check your pip version (2 vs 3)
I had this same issue and it was not fixed by running pip install simplejson
despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.
> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)
Installing with the correct version of pip is as easy as using pip2
:
> pip2 install simplejson
and then python 2 can import simplejson
fine.
One line solution :
const day = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"][new Date().getDay()]
Some Linux distributions don't use the gdb
style debugging symbols. (IIRC they prefer dwarf2
.)
In general, gcc
and gdb
will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g
.
Open the /etc/mysql/mysql.conf.d/mysqld.cnf
file and comment the
following line:
#bind-address = 127.0.0.1
Swift 4 Xcode 10 Update
extension Double {
var asNumber:String {
if self >= 0 {
let formatter = NumberFormatter()
formatter.numberStyle = .none
formatter.percentSymbol = ""
formatter.maximumFractionDigits = 2
return "\(formatter.string(from: NSNumber(value: self)) ?? "")"
}
return ""
}
}
I've been using vi and vim also for some 20 years, and I'm still learning new things.
David Rayner's Best of Vim Tips site is an excellent list, though it's probably more useful once you have some familiarity with vim.
I also want to mention the ViEmu site which has some great info on vi/vim tips and especially the article Why, oh WHY, do those nutheads use vi? (archived version)
First run go env
.
If you see that the go isn't installed, you can install it via homebrew
or via package and/or other ways.
If you are seeing output then your Go
is installed.
It shows you all the envs that are set and are not.
If you see empty for GOROOT
:
which go
(On my computer : /usr/local/go/bin/go
)export GOROOT=/usr/local/go
If you see empty for GOPATH
:
~/GO_PROJECTS
export GOPATH=~/GO_PROJECTS
now in Kotlin you can run threads this way:
class SimpleRunnable: Runnable {
public override fun run() {
println("${Thread.currentThread()} has run.")
}
}
fun main(args: Array<String>) {
val thread = SimpleThread()
thread.start() // Will output: Thread[Thread-0,5,main] has run.
val runnable = SimpleRunnable()
val thread1 = Thread(runnable)
thread1.start() // Will output: Thread[Thread-1,5,main] has run
}
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
I ran a similar test as @marcio but with the following loop instead:
String c = a;
for (long i = 0; i < 100000L; i++) {
c = c.concat(b); // make sure javac cannot skip the loop
// using c += b for the alternative
}
Just for good measure, I threw in StringBuilder.append()
as well. Each test was run 10 times, with 100k reps for each run. Here are the results:
StringBuilder
wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.a += b
takes about 40000ms (40s) for each run.concat
only requires 10000ms (10s) per run.I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b
spends much of the time creating new objects of StringBuilder
and then converting them back to String
.
To improve the Padraic's answer: when check_output
returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.
What I would do to catch this exception is:
#!/usr/bin/python
from subprocess import check_output, CalledProcessError
def getPIDs(process):
try:
pidlist = map(int, check_output(["pidof", process]).split())
except CalledProcessError:
pidlist = []
print 'list of PIDs = ' + ', '.join(str(e) for e in pidlist)
if __name__ == '__main__':
getPIDs("chrome")
The output:
$ python pidproc.py
list of PIDS = 31840, 31841, 41942
to identify hive version on a EC2 instance use
hive --version
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
MSDN has provided easy way to debug the stored procedure. Please check this link-
How to: Debug Stored Procedures
The following worked for me
import java.time.*;
import java.time.format.*;
public class Times {
public static void main(String[] args) {
final String dateTime = "2012-02-22T02:06:58.147Z";
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
System.out.println(parsed.toLocalDateTime());
}
}
and gave me output as
2012-02-22T02:06:58.147
You can keep it in the generic form and write it as:
// list 2 is made generic and can store any type of Object
ArrayList<Object> list2 = new ArrayList<Object>();
Setting type of ArrayList as Object gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.
You can use Cursor like that:
USE master
GO
DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'
DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database
OPEN Murderer
FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
EXEC (@SQL)
PRINT ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
FETCH NEXT FROM Murderer INTO @SPID
END
CLOSE Murderer
DEALLOCATE Murderer
I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor
There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type
(or :nth-child
-- either would work in this case.)
Smallest viewport:
@media (max-width:$smallest-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(2n) {
background: #fff;
}
}
Medium viewport:
@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
background: #fff;
}
}
Largest viewport:
@media (min-width:$mid-breakpoint) and (max-width:9999px) {
.row div {
background: #eee;
}
.row div:nth-of-type(6n+4),
.row div:nth-of-type(6n+5),
.row div:nth-of-type(6n+6) {
background: #fff;
}
}
Working fiddle here
For anyone that is seeing an issue with a black preview after image capture, hiding the status bar after the UIPickerController is shown seems to fix the issue.
UIImagePickerControllerSourceType source = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
UIImagePickerController *cameraController = [[UIImagePickerController alloc] init];
cameraController.delegate = self;
cameraController.sourceType = source;
cameraController.allowsEditing = YES;
[self presentViewController:cameraController animated:YES completion:^{
//iOS 8 bug. the status bar will sometimes not be hidden after the camera is displayed, which causes the preview after an image is captured to be black
if (source == UIImagePickerControllerSourceTypeCamera) {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}
}];
You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)
Directions:
On the Installation Type screen, select the appropriate SQL Server instance.
Advance through the rest of the wizard.
Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546
Stringifying a null
value in ActionScript will give the string "NULL"
. My suspicion is that someone has decided that it is, therefore, a good idea to decode the string "NULL"
as null
, causing the breakage you see here -- probably because they were passing in null
objects and getting strings in the database, when they didn't want that (so be sure to check for that kind of bug, too).
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
One of the coolest benefits of using something like Spring is that you don't have to wire your objects together. Zeus's head splits open and your classes appear, fully formed with all of their dependencies created and wired-in, as needed. It's magical and fantastic.
The more you say ClassINeed classINeed = (ClassINeed)ApplicationContext.getBean("classINeed");
, the less magic you're getting. Less code is almost always better. If your class really needed a ClassINeed bean, why didn't you just wire it in?
That said, something obviously needs to create the first object. There's nothing wrong with your main method acquiring a bean or two via getBean(), but you should avoid it because whenever you're using it, you're not really using all of the magic of Spring.
Try this:
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
JS Code
function search(ele) {
if(event.key === 'Enter') {
alert(ele.value);
}
}
No, it won't wait.
You could use performSelectorOnMainThread:withObject:waitUntilDone:
.
This will help you. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); print (df.format(new Date());
You could use an anchor element (<a></a>
), and use a:active and a:link to change the background image to toggle on or off. Just a thought.
Edit: The above method doesn't work too well for toggle. But you don't need to use jquery. Write a simple onClick javascript function for the element, which changes the background image appropriately to make it look like the button is pressed, and set some flag. Then on next click, image and flag is is reverted. Like so
var flag = 0;
function toggle(){
if(flag==0){
document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img1.gif";
flag=1;
}
else if(flag==1){
document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img2.gif";
flag=0;
}
}
And the html like so
<div id="toggleDiv" onclick="toggle()">Some thing</div>
These suggestions so far only work if the mysql server is installed as a windows service.
If it is not installed as a service, you can start the server by using the Windows Start button ==> Run, then browse to the /bin folder under your mysql installation path and execute mysqld. Or just open a command window in the bin folder and type: mysqld
Add to the info plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
import Alamofire
class AlamofireDataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
Alamofire.request(request).responseJSON { response in
let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
switch response.result {
case .success(let value): complete(.success(value as! [String: Any]))
case .failure(let error): complete(.failure(error))
}
}
}
func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
let request = URLRequest(url: url)
make(request: request) { response in closure?(response) }
}
}
private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
//.........
alamofireDataManager.searchRequest(term: "jack johnson") { result in
print(result.value ?? "no data")
print(result.error ?? "no error")
}
import Foundation
class DataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let task = session.dataTask(with: request) { [weak self] data, response, error in
self?.queue.async {
let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }
guard let self = self, error == nil else { complete(nil, error); return }
guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
complete(json, nil)
}
} catch let error { complete(nil, error); return }
}
}
task.resume()
}
func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
let request = URLRequest(url: url!)
make(request: request) { json, error in closure?(json, error) }
}
}
private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
// .......
dataManager.searchRequest(term: "jack johnson") { json, error in
print(error ?? "nil")
print(json ?? "nil")
print("Update views")
}
Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.
From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:
I Set:
.Timeout=5000
.ReadWriteTimeout=32000
The connect and post time for the HttpWebRequest took 26ms
but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.
I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.
For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.
This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:
net use \\server\share /user:<domain\username> <password>
And then do whatever you need to do in PowerShell...
Starting with your table definition:
- UserID
- Fname
- Lname
- Email
- Password
- IV
Here are the changes:
Fname
, Lname
and Email
will be encrypted using a symmetric cipher, provided by OpenSSL,IV
field will store the initialisation vector used for encryption. The storage requirements depend on the cipher and mode used; more about this later.Password
field will be hashed using a one-way password hash,Cipher and mode
Choosing the best encryption cipher and mode is beyond the scope of this answer, but the final choice affects the size of both the encryption key and initialisation vector; for this post we will be using AES-256-CBC which has a fixed block size of 16 bytes and a key size of either 16, 24 or 32 bytes.
Encryption key
A good encryption key is a binary blob that's generated from a reliable random number generator. The following example would be recommended (>= 5.3):
$key_size = 32; // 256 bits
$encryption_key = openssl_random_pseudo_bytes($key_size, $strong);
// $strong will be true if the key is crypto safe
This can be done once or multiple times (if you wish to create a chain of encryption keys). Keep these as private as possible.
IV
The initialisation vector adds randomness to the encryption and required for CBC mode. These values should be ideally be used only once (technically once per encryption key), so an update to any part of a row should regenerate it.
A function is provided to help you generate the IV:
$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
Let's encrypt the name field, using the earlier $encryption_key
and $iv
; to do this, we have to pad our data to the block size:
function pkcs7_pad($data, $size)
{
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
$name = 'Jack';
$enc_name = openssl_encrypt(
pkcs7_pad($name, 16), // padded data
'AES-256-CBC', // cipher and mode
$encryption_key, // secret key
0, // options (not used)
$iv // initialisation vector
);
The encrypted output, like the IV, is binary; storing these values in a database can be accomplished by using designated column types such as BINARY
or VARBINARY
.
The output value, like the IV, is binary; to store those values in MySQL, consider using BINARY
or VARBINARY
columns. If this is not an option, you can also convert the binary data into a textual representation using base64_encode()
or bin2hex()
, doing so requires between 33% to 100% more storage space.
Decryption of the stored values is similar:
function pkcs7_unpad($data)
{
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
$row = $result->fetch(PDO::FETCH_ASSOC); // read from database result
// $enc_name = base64_decode($row['Name']);
// $enc_name = hex2bin($row['Name']);
$enc_name = $row['Name'];
// $iv = base64_decode($row['IV']);
// $iv = hex2bin($row['IV']);
$iv = $row['IV'];
$name = pkcs7_unpad(openssl_decrypt(
$enc_name,
'AES-256-CBC',
$encryption_key,
0,
$iv
));
You can further improve the integrity of the generated cipher text by appending a signature that's generated from a secret key (different from the encryption key) and the cipher text. Before the cipher text is decrypted, the signature is first verified (preferably with a constant-time comparison method).
// generate once, keep safe
$auth_key = openssl_random_pseudo_bytes(32, $strong);
// authentication
$auth = hash_hmac('sha256', $enc_name, $auth_key, true);
$auth_enc_name = $auth . $enc_name;
// verification
$auth = substr($auth_enc_name, 0, 32);
$enc_name = substr($auth_enc_name, 32);
$actual_auth = hash_hmac('sha256', $enc_name, $auth_key, true);
if (hash_equals($auth, $actual_auth)) {
// perform decryption
}
See also: hash_equals()
Storing a reversible password in your database must be avoided as much as possible; you only wish to verify the password rather than knowing its contents. If a user loses their password, it's better to allow them to reset it rather than sending them their original one (make sure that password reset can only be done for a limited time).
Applying a hash function is a one-way operation; afterwards it can be safely used for verification without revealing the original data; for passwords, a brute force method is a feasible approach to uncover it due to its relatively short length and poor password choices of many people.
Hashing algorithms such as MD5 or SHA1 were made to verify file contents against a known hash value. They're greatly optimized to make this verification as fast as possible while still being accurate. Given their relatively limited output space it was easy to build a database with known passwords and their respective hash outputs, the rainbow tables.
Adding a salt to the password before hashing it would render a rainbow table useless, but recent hardware advancements made brute force lookups a viable approach. That's why you need a hashing algorithm that's deliberately slow and simply impossible to optimize. It should also be able to increase the load for faster hardware without affecting the ability to verify existing password hashes to make it future proof.
Currently there are two popular choices available:
This answer will use an example with bcrypt.
Generation
A password hash can be generated like this:
$password = 'my password';
$random = openssl_random_pseudo_bytes(18);
$salt = sprintf('$2y$%02d$%s',
13, // 2^n cost factor
substr(strtr(base64_encode($random), '+', '.'), 0, 22)
);
$hash = crypt($password, $salt);
The salt is generated with openssl_random_pseudo_bytes()
to form a random blob of data which is then run through base64_encode()
and strtr()
to match the required alphabet of [A-Za-z0-9/.]
.
The crypt()
function performs the hashing based on the algorithm ($2y$
for Blowfish), the cost factor (a factor of 13 takes roughly 0.40s on a 3GHz machine) and the salt of 22 characters.
Validation
Once you have fetched the row containing the user information, you validate the password in this manner:
$given_password = $_POST['password']; // the submitted password
$db_hash = $row['Password']; // field with the password hash
$given_hash = crypt($given_password, $db_hash);
if (isEqual($given_hash, $db_hash)) {
// user password verified
}
// constant time string compare
function isEqual($str1, $str2)
{
$n1 = strlen($str1);
if (strlen($str2) != $n1) {
return false;
}
for ($i = 0, $diff = 0; $i != $n1; ++$i) {
$diff |= ord($str1[$i]) ^ ord($str2[$i]);
}
return !$diff;
}
To verify a password, you call crypt()
again but you pass the previously calculated hash as the salt value. The return value yields the same hash if the given password matches the hash. To verify the hash, it's often recommended to use a constant-time comparison function to avoid timing attacks.
Password hashing with PHP 5.5
PHP 5.5 introduced the password hashing functions that you can use to simplify the above method of hashing:
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 13]);
And verifying:
if (password_verify($given_password, $db_hash)) {
// password valid
}
See also: password_hash()
, password_verify()
You are probably seeking:
ActiveRecord::Base.connection.tables
and
ActiveRecord::Base.connection.columns('projects').map(&:name)
You should probably wrap them in shorter syntax inside your .irbrc
.
With a running instance of myExecutableName
having a PID 15073
:
hitting Tab twice after $ gdb myExecu
in the command line, will automagically autocompletes to:
$ gdb myExecutableName 15073
and will attach gdb to this process. That's nice!
From Maven - Settings Reference
The repositories for download and deployment are defined by the repositories
and distributionManagement
elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
...
<servers>
<server>
<id>server001</id>
<username>my_login</username>
<password>my_password</password>
<privateKey>${user.home}/.ssh/id_dsa</privateKey>
<passphrase>some_passphrase</passphrase>
<filePermissions>664</filePermissions>
<directoryPermissions>775</directoryPermissions>
<configuration></configuration>
</server>
</servers>
...
</settings>
id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.
username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.
privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa
) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.
filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.
Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.
All you should need is the id
, username
and password
The id
and URL
should be defined in your pom.xml
like this:
<repositories>
...
<repository>
<id>acme-nexus-releases</id>
<name>acme nexus</name>
<url>https://nexus.acme.net/content/repositories/releases</url>
</repository>
...
</repositories>
If you need a username and password to your server, you should encrypt it. Maven Password Encryption
For portability, you really should do something like this:
public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);
unless you're absolutely certain that "\n"
is what you want.
Surely everyone's missed a trick here. The current file size limit of a json file is 18,446,744,073,709,551,616 characters or if you prefer bytes, or even 2^64 bytes if you're looking at 64 bit infrastructures at least.
For all intents, and purposes we can assume it's unlimited as you'll probably have a hard time hitting this issue...
It ought to be implemented in msysgit, but there are two downsides:
I did a quick search and there is work being actively done on this, see issue 224.
I use this chrome extension. It'll give you the wget command for any download link you open.
The atob
function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.
const byteCharacters = atob(b64Data);
Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt
method for each character in the string.
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array
constructor.
const byteArray = new Uint8Array(byteNumbers);
This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob
constructor.
const blob = new Blob([byteArray], {type: contentType});
The code above works. However the performance can be improved a little by processing the byteCharacters
in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {_x000D_
const byteCharacters = atob(b64Data);_x000D_
const byteArrays = [];_x000D_
_x000D_
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
const slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
const byteNumbers = new Array(slice.length);_x000D_
for (let i = 0; i < slice.length; i++) {_x000D_
byteNumbers[i] = slice.charCodeAt(i);_x000D_
}_x000D_
_x000D_
const byteArray = new Uint8Array(byteNumbers);_x000D_
byteArrays.push(byteArray);_x000D_
}_x000D_
_x000D_
const blob = new Blob(byteArrays, {type: contentType});_x000D_
return blob;_x000D_
}_x000D_
_x000D_
const contentType = 'image/png';_x000D_
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
const blob = b64toBlob(b64Data, contentType);_x000D_
const blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
const img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
Or for fun:
>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>>
ast.literal_eval
Even after you delete the file(s) and then commit, you will still have those files in history. To delete those, consider using BFG Repo-Cleaner. It is an alternative to git-filter-branch.
Yes - document.location = "http://my.new.url.com"
You can also retrieve it the same way eg.
var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:
hash Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL
EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId
will scroll to the element with id="myId"
. If the id
doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)
EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.
This is how use SignarR in order to target a specific user (without using any provider):
private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();
public string Login(string username)
{
clients.TryAdd(Context.ConnectionId, username);
return username;
}
// The variable 'contextIdClient' is equal to Context.ConnectionId of the user,
// once logged in. You have to store that 'id' inside a dictionaty for example.
Clients.Client(contextIdClient).send("Hello!");
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
I like to use this;
$('#container').prop('outerHTML');
main()
{
int *arr[5];
int i=31, j=5, k=19, l=71, m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
arr[4]=&m;
for(m=0; m<=4; m++)
{
printf("%d",*(arr[m]));
}
return 0;
}
The number of rows effected is returned from execute:
rows_affected=cursor.execute("SELECT ... ")
of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:
cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount
From the inline documentation of python MySQLdb:
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
Matlab allows you to return multiple values as well as receive them inline.
When you call it, receive individual variables inline:
[array, listp, freep] = initialize(size)
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
This is an easier way to do it.
In the second line of code the file result.json
gets created and opened as the variable fp
.
In the third line your dict sample
gets written into the result.json
!
m1 = (y2 - y1) / (x2 - x1)
if perpendicular two lines:
m1*m2 = -1
then
m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)
y = m2*x + b //b is offset of new perpendicular line..
b is something if you want to pass it from a point you defined
Use:
boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
[name()='AttachedXml'
and
namespace-uri()='http://xml.mycompany.com/XMLSchema'
]
)
In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
if overwriteFlag:
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want to overwrite the previous line, or
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
You don't need awk for this...
echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc
echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc
x=aaa0.bbb.ccc; echo ${x/.*/}
Heavier options:
sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc
'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).
if( x != null && x.equals("*BINGO*") {
then do something with x...
}
In SQL Server, you can do:
select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)
This attempts the conversion, keeping the previous value if available.
Note: I hope you learned a lesson about storing dates as dates and not strings.
Path.GetDirectoryName(filename);
You can also do it with print
instead of write
:
with open('test.txt', 'a') as f:
print('appended text', file=f)
If test.txt doesn't exist, it will be created...
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
You can now use a very simple API https://wa.me/
to perform this task where you can provide a valid whatsapp contact number like 15555555555 ( add country code, remove all '+', '-', brackets, spaces or leading zeros). You can also provide a urlencoded text as a predefined msg which user can send directly or change before sending.
Chat with me link : <a href="https://wa.me/15555555555">Contact me by whatsapp</a>
Chat with me link with predefined text : <a href="https://wa.me/15555555555?text=I%27d%20like%20to%20chat%20with%20you">Contact me on whatsapp</a>
Beauty of this wa.me
url is you don't need to check user agent as it works on both mobile and desktop (opens web.whatsapp.com)
Source : https://faq.whatsapp.com/en/general/26000030
More details in my answer on a similar question https://stackoverflow.com/a/51854282/2485420
I had a more specifc error message that stated to remove 'Office 16 Click-to-Run Extensibility Component'
I fixed it by following the steps in https://www.tecklyfe.com/fix-for-microsoft-office-setup-error-please-uninstall-all-32-bit-office-programs-office-15-click-to-run-extensibility-component/
string[0] = "";
"warning: assignment makes integer from pointer without a cast
Ok, let's dive into the expression ...
0
an int: represents the number of chars (assuming string
is (or decayed into) a char*) to advance from the beginning of the object string
string[0]
: the char
object located at the beginning of the object string
""
: string literal: an object of type char[1]
=
: assignment operator: tries to assign a value of type char[1]
to an object of type char
. char[1]
(decayed to char*
) and char
are not assignment compatible, but the compiler trusts you (the programmer) and goes ahead with the assignment anyway by casting the type char*
(what char[1]
decayed to) to an int
--- and you get the warning as a bonus. You have a really nice compiler :-)
Swift 4, iOS 10+
Static function which can apply for any entity to remove all of its data
protocol NSManagedObjectHelper {
}
extension NSManagedObject: NSManagedObjectHelper {
}
extension NSManagedObjectHelper where Self: NSManagedObject {
static func removeAllObjectsInContext(_ managedContext: NSManagedObjectContext) {
let request: NSFetchRequest = NSFetchRequest(entityName: String(describing: self))
let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
do {
deleteRequest.resultType = .resultTypeObjectIDs//to clear objects from memory
let result = try managedContext.execute(deleteRequest) as? NSBatchDeleteResult
if let objectIDArray = result?.result as? [NSManagedObjectID] {
let changes = [NSDeletedObjectsKey : objectIDArray]
/*By calling mergeChangesFromRemoteContextSave, all of the NSManagedObjectContext instances that are referenced will be notified that the list of entities referenced with the NSManagedObjectID array have been deleted and that the objects in memory are stale. This causes the referenced NSManagedObjectContext instances to remove any objects in memory that are loaded which match the NSManagedObjectID instances in the array.*/
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [managedContext])
}
try managedContext.save()
} catch let error {
print(error)
}
}
}
'Room' is an entity
Room.removeAllObjectsInContext(self.persistentContainer.viewContext)
Edited on 20191025: the "Self.fetchRequest()" instruction may cause issue if we use multiple target in same projects. So replaced with NSFetchRequest(entityName: String(describing: self))
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
<meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<style type="text/css" >
input.searcher
{
background-image: url(/images/search_back.png);
background-repeat: no-repeat;
background-attachment: scroll;
background-x-position: left;
background-y-position: center;
}
</style>
<script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
<input type="text" id="q" name="q" value="" />
<script type="text/javascript" language="JavaScript" >
// <![CDATA[
function f(e){
$('q').removeClassName('searcher');
}
function b(e){
if ( $F('q') == '' )
{
$('q').addClassName('searcher');
}
}
Event.observe( 'q', 'focus', f);
Event.observe( 'q', 'blur', b);
Event.observe( window, 'load', b);
// ]]>
</script>
</body>
</html>
I actually got this error because I was checking InnerHtml for some content that was generated dynamically - i.e. a control that is runat=server.
To solve this I had to remove the "static" keyword on my method, and it ran fine.
Is Powershell an option?
Start Powershell:
powershell
Create the VPN Connection: Add-VpnConnection
Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm]
Edit VPN connections: Set-VpnConnection
Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]
Lookup VPN Connections: Get-VpnConnection
Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]
Connect: rasdial [connectionName]
rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]
You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial
.
The results of Get-VpnConnection
can be a little verbose. This can be simplified with a simple Select-Object
filter:
Get-VpnConnection | Select-Object -Property Name
More information can be found here:
A practical explanation: By default, <p> </p>
will add line breaks before and after the enclosed text (so it creates a paragraph). <span>
does not do this, that is why it is called inline.
onInputChange(evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
var base64 = fr.result;
debugger;
}
fr.readAsDataURL(files[0]);
}
}
Also make sure there is not as JRE before your JDK in PATH on Windows. Oracle always stuffs its own JRE into the path before anything else (I had installed Oracle Lite after I installed the android sdk).
This is another way...(with limited range)
public static String numToWord(Integer i) {
final String[] units = { "Zero", "One", "Two", "Three",
"Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen" };
final String[] tens = { "", "", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
if (i < 20)
return units[i];
if (i < 100)
return tens[i / 10] + ((i % 10 > 0) ? " " + numToWord(i % 10) : "");
if (i < 1000)
return units[i / 100] + " Hundred"
+ ((i % 100 > 0) ? " and " + numToWord(i % 100) : "");
if (i < 1000000)
return numToWord(i / 1000) + " Thousand "
+ ((i % 1000 > 0) ? " " + numToWord(i % 1000) : "");
return numToWord(i / 1000000) + " Million "
+ ((i % 1000000 > 0) ? " " + numToWord(i % 1000000) : "");
}
Another way, There is check box Page Layout tab with Gridlines [ ] View which should be checked.
You can set an objects property this way:
var obj = {};_x000D_
obj.whateverVarName = 'yourVal';_x000D_
console.log(obj);
_x000D_
Update 2020: As baao notes, Object.fromEntries(arr)
now does this on all modern browsers.
You can use Object.assign, the spread operator, and destructuring assignment for an approach that uses map
instead of @royhowie’s reduce
, which may or may not be more intuitive:
Object.assign(...arr.map(([key, val]) => ({[key]: val})))
E.g.:
var arr = [ [ 'cardType', 'iDEBIT' ],
[ 'txnAmount', '17.64' ],
[ 'txnId', '20181' ],
[ 'txnType', 'Purchase' ],
[ 'txnDate', '2015/08/13 21:50:04' ],
[ 'respCode', '0' ],
[ 'isoCode', '0' ],
[ 'authCode', '' ],
[ 'acquirerInvoice', '0' ],
[ 'message', '' ],
[ 'isComplete', 'true' ],
[ 'isTimeout', 'false' ] ]
var obj = Object.assign(...arr.map(([key, val]) => ({[key]: val})))
console.log(obj)
_x000D_
is simple for me use base64_encode
$term = base64_encode($term)
$url = $youurl.'?term='.$term
after you decode the term
$term = base64_decode($['GET']['term'])
this way encode the "/" and "\"
Assuming your sm_id
and c_id
properties are public, you can access them by using a foreach
on the array:
$array = array(/* objects in an array here */);
foreach ($array as $obj) {
echo $obj->sm_id . '<br />' . $obj->c_id . '<br />';
}
<div id="item">show taille height</div>
<script>
alert(document.getElementById('item').offsetHeight);
</script>
For those who value short arrow function.
A arrow function version of David's Answer
const hex2rgb = h => [(x=parseInt(h,16)) >> 16 & 255,x >> 8 & 255, x & 255];
A more flexible solution that supports shortand hex or the hash #
const hex2rgb = h => {
if(h[0] == '#') {h = h.slice(1)};
if(h.length <= 3) {h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2]};
h = parseInt(h,16);
return [h >> 16 & 255,h >> 8 & 255, h & 255];
};
const rgb2hex = (r,g,b) => ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
I've found that experimenting with the various methods is a good sanity check even after having a good handle of what their various uses and capabilities are.
Towards that end I have found this website extremely useful to confirm my suspicions that I am doing something appropriately. It has also proven useful for decoding an encodeURIComponent'ed string which can be rather challenging to interpret. A great bookmark to have:
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/
You can also use EXIT_SUCCESS
instead of return 0;
. The macro EXIT_SUCCESS
is actually defined as zero, but makes your program more readable.
df = df[[col for col in df.columns if not ('Unnamed' in col)]]
Uncommenting extension=php_pgsql.dll
in the php.ini
configuration files does work but, you may have to also restart your XAMPP server to finally get it working. I had to do this.
You can achieve this using JQuery
HTML
<input type="file" id="FilUploader" />
JQuery
$("#FilUploader").change(function () {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only formats are allowed : "+fileExtension.join(', '));
}
});
For more info Click Here
I have never been a fan of closing blocks of PHP to output content to the browser, I prefer to have my output captured so if at some point within my logic I decide I want to change my output (after output has already been sent) I can just delete the current buffer.
But as Pekka said, the main reason you are having issues with your javascript inclusion is because your using href
to specify the location of the js file where as you should be using src
.
If you have a functions file with your functions inside then add something like:
function js_link($src)
{
if(file_exists("my/html/root/" . $src))
{
//we know it will exists within the HTTP Context
return sprintf("<script type=\"text/javascript\" src=\"%s\"></script>",$src);
}
return "<!-- Unable to load " . $src . "-->";
}
The n in your code without the need for closing your blocks with ?>
you can just use:
echo js_link("jquery/1.6/main.js");
If you wanna use a URL just you can use this code.
<link rel="shortcut icon" type="image/x-icon" href="https://..." />
Fastest way is to use MySQL bulk loader by "load data infile" statement. It is the fastest way by far than any way you can come up with in Python. If you have to use Python, you can call statement "load data infile" from Python itself.
You may want to create a subRepeater.
<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
<ItemTemplate>
<span><%# Eval("Name") %></span>
</ItemTemplate>
</asp:Repeater>
You can also cast your fields
<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>
Finally you could do a little CSV Function and write out your fields with a function
<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>
public string GetAsCsv(IEnumerable<Fields> fields)
{
var builder = new StringBuilder();
foreach(var f in fields)
{
builder.Append(f);
builder.Append(",");
}
builder.Remove(builder.Length - 1);
return builder.ToString();
}
XAMPP by default uses http://localhost/phpmyadmin
It also requires you start both Apache and MySQL from the control panel (or as a service).
In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.
If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)
You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:
string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(json);
StringBuilder sb = new StringBuilder();
sb.Append("<table>\n <thead>\n <tr>\n");
// Build the header based on the keys in the
// first data item.
foreach (string key in data["items"][0].Keys) {
sb.AppendFormat(" <th>{0}</th>\n", key);
}
sb.Append(" </tr>\n </thead>\n <tbody>\n");
foreach (Dictionary<string, object> item in data["items"]) {
sb.Append(" <tr>\n");
foreach (string val in item.Values) {
sb.AppendFormat(" <td>{0}</td>\n", val);
}
}
sb.Append(" </tr>\n </tbody>\n</table>");
string myTable = sb.ToString();
At the end, myTable
will hold a string that looks like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>22</td>
<td>PPP</td>
<tr>
<td>BBB</td>
<td>25</td>
<td>QQQ</td>
<tr>
<td>CCC</td>
<td>38</td>
<td>RRR</td>
</tr>
</tbody>
</table>
The problem is, SelectList works as designed. The bug is in the design. You may set the Selected Property in SelectedItem, but this will completely be ignored, if you traverse the list with the GetEnumerator() (or if Mvc does that for you). Mvc will create new SelectListItems instead.
You have to use the SelectList ctor with the SelectListItem[], the Text-Name, the Value-Name and the SelectedValue. Be aware to pass as SelectedValue the VALUE of SelectListItem, which you want to be selected, not the SelectListItem itself! Example:
SelectList sl = new SelectList( new[]{
new SelectListItem{ Text="one", Value="1"},
new SelectListItem{ Text="two", Value="2"},
new SelectListItem{ Text="three", Value="3"}
}, "Text", "Value", "2" );
(not tested this, but I had the same problem)
then the 2nd option will get the selected="selected" attribute. That looks like good old DataSets ;-)
This is non-sql method. Instructions are given on the image itself. Select the server that you want to find the info about and then follow the steps.
div hover background color change
Try like this:
.class_name:hover{
background-color:#FF0000;
}
Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.
$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. .. .den .hi .hidden a b c
$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c
$ shopt -s dotglob
$ ls *
.den .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c
It defaults to "off".
$ shopt dotglob
dotglob off
It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.
y = a + b * x
where:
b = ( sum(xi * yi) - n * xbar * ybar ) / sum((xi - xbar)^2)
a = ybar - b * xbar
# sample points
X = [0, 5, 10, 15, 20]
Y = [0, 7, 10, 13, 20]
# solve for a and b
def best_fit(X, Y):
xbar = sum(X)/len(X)
ybar = sum(Y)/len(Y)
n = len(X) # or len(Y)
numer = sum([xi*yi for xi,yi in zip(X, Y)]) - n * xbar * ybar
denum = sum([xi**2 for xi in X]) - n * xbar**2
b = numer / denum
a = ybar - b * xbar
print('best fit line:\ny = {:.2f} + {:.2f}x'.format(a, b))
return a, b
# solution
a, b = best_fit(X, Y)
#best fit line:
#y = 0.80 + 0.92x
# plot points and fit line
import matplotlib.pyplot as plt
plt.scatter(X, Y)
yfit = [a + b * xi for xi in X]
plt.plot(X, yfit)
The following format should work:
$.ajax({
type: "POST",
url: "@Url.Action("refresh", "group")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
myDate: '2011-04-02 17:15:45'
}),
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
On Snow Leopard (OS X 10.6.8), running 'man lsof' yields:
lsof -i 4 -a
(actual manual entry is 'lsof -i 4 -a -p 1234')
The previous answers didn't work on Snow Leopard, but I was trying to use 'netstat -nlp' until I saw the use of 'lsof' in the answer by pts.
After studying some jQuery at Codeacademy I found a solution to bind a key with the animate property. The whole idea was to animate without scrolling to jump from one section to another. The example from Codeacademy was to move Mario through the DOM but I applied this for my website sections (CSS with 100% height). Here is a part of the code:
$(document).keydown(function(key) {
switch(parseInt(key.which, 10)) {
case 39:
$('section').animate({top: "-=100%"}, 2000);
break;
case 37:
$('section').animate({top: "+=100%"}, 2000);
break;
default:
break;
}
});
I think you could use this for any letter and property.
Source: http://www.codecademy.com/forum_questions/50e85b2714bd580ab300527e
I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:
find . -type d -exec chmod 755 {} \+
but this also does the same thing:
chmod 755 `find . -type d`
and so does this:
chmod 755 $(find . -type d)
The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.
So I think in your case that the following will do what you want.
chmod 777 $(find "/Users/Test/Desktop/PATH")
As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data
with participants
.
The alternative to the solution they provided would be to prevent render until participants exist, something like this:
render: function() {
if (!this.props.data.participants) {
return null;
}
return (
<ul className="PlayerList">
// I'm the Player List {this.props.data}
// <Player author="The Mini John" />
{
this.props.data.participants.map(function(player) {
return <li key={player}>{player}</li>
})
}
</ul>
);
}
Use this function to remove specific arrays of keys without modifying the original array:
function array_except($array, $keys) {
return array_diff_key($array, array_flip((array) $keys));
}
First param pass all array, second param set array of keys to remove.
For example:
$array = [
'color' => 'red',
'age' => '130',
'fixed' => true
];
$output = array_except($array, ['color', 'fixed']);
// $output now contains ['age' => '130']
The accepted answer is the way to go and is actually what I am doing for simplicity. Most advantages of enumeration are offered (readable, fast, etc.). One concept is missing, however: type safety. In most languages, enumerations are also used to restrict allowed values. Below is an example of how type safety can also be obtained by using private constructors, static instantiation methods and type checking:
class DaysOfWeek{
const Sunday = 0;
const Monday = 1;
// etc.
private $intVal;
private function __construct($intVal){
$this->intVal = $intVal;
}
//static instantiation methods
public static function MONDAY(){
return new self(self::Monday);
}
//etc.
}
//function using type checking
function printDayOfWeek(DaysOfWeek $d){ //compiler can now use type checking
// to something with $d...
}
//calling the function is safe!
printDayOfWeek(DaysOfWeek::MONDAY());
We could even go further: using constants in the DaysOfWeek class might lead to misusage: e.g. one might mistakenly use it this way:
printDayOfWeek(DaysOfWeek::Monday); //triggers a compiler error.
which is wrong (calls integer constant). We can prevent this using private static variables instead of constants:
class DaysOfWeeks{
private static $monday = 1;
//etc.
private $intVal;
//private constructor
private function __construct($intVal){
$this->intVal = $intVal;
}
//public instantiation methods
public static function MONDAY(){
return new self(self::$monday);
}
//etc.
//convert an instance to its integer value
public function intVal(){
return $this->intVal;
}
}
Of course, it is not possible to access integer constants (this was actually the purpose). The intVal method allows to convert a DaysOfWeek object to its integer representation.
Note that we could even go further by implementing a caching mechanism in instantiation methods to save memory in the case enumerations are extensively used...
Hope this will help
Speaking of handling errors, it's even better listening to request errors too. I'd even validate by checking response code. Here it's considered success only for 200 response code, but other codes might be good.
const fs = require('fs');
const http = require('http');
const download = (url, dest, cb) => {
const file = fs.createWriteStream(dest);
const request = http.get(url, (response) => {
// check if response is success
if (response.statusCode !== 200) {
return cb('Response status was ' + response.statusCode);
}
response.pipe(file);
});
// close() is async, call cb after close completes
file.on('finish', () => file.close(cb));
// check for request error too
request.on('error', (err) => {
fs.unlink(dest);
return cb(err.message);
});
file.on('error', (err) => { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
return cb(err.message);
});
};
Despite the relative simplicity of this code, I would advise to use the request module as it handles many more protocols (hello HTTPS!) which aren't natively supported by http
.
That would be done like so:
const fs = require('fs');
const request = require('request');
const download = (url, dest, cb) => {
const file = fs.createWriteStream(dest);
const sendReq = request.get(url);
// verify response code
sendReq.on('response', (response) => {
if (response.statusCode !== 200) {
return cb('Response status was ' + response.statusCode);
}
sendReq.pipe(file);
});
// close() is async, call cb after close completes
file.on('finish', () => file.close(cb));
// check for request errors
sendReq.on('error', (err) => {
fs.unlink(dest);
return cb(err.message);
});
file.on('error', (err) => { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
return cb(err.message);
});
};
to_date
format worked for me. Please consider the date formats:
MON-
, MM
, .
, -
.
t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')
In Java class :-
toolbar = (Toolbar) findViewById(R.id.apptool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Snapdeal");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
In Manifest :-
<activity
android:name=".SubActivity"
android:label="@string/title_activity_sub"
android:theme="@style/AppTheme" >
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"></meta-data>
</activity>
It will help you
Maybe easy like this?
Compiled binaries of the PHP interpreter can be found at http://www.mamp.info/en/ downloads/index.html . Drop this downloaded folder into your /Applications/MAMP/bin/php! directory. Close and re-open your MAMP PRO application. Your new PHP version should now appear in the PHP drop down menu. MAMP PRO will only support PHP versions from the downloads page.
I have seen answers here and almost all did well. However, I have written my own version that utilizes a Dictionary for managing the bracket pairs and a stack to monitor the order of detected braces. I have also written a blog post for this.
Here is my class
public class FormulaValidator
{
// Question: Check if a string is balanced. Every opening bracket is matched by a closing bracket in a correct position.
// { [ ( } ] )
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{ ( [ ) ] }" is _not_ balanced
// Input: string, containing the bracket symbols only
// Output: true or false
public bool IsBalanced(string input)
{
var brackets = BuildBracketMap();
var openingBraces = new Stack<char>();
var inputCharacters = input.ToCharArray();
foreach (char character in inputCharacters)
{
if (brackets.ContainsKey(character))
{
openingBraces.Push(character);
}
if (brackets.ContainsValue(character))
{
var closingBracket = character;
var openingBracket = brackets.FirstOrDefault(x => x.Value == closingBracket).Key;
if (openingBraces.Peek() == openingBracket)
openingBraces.Pop();
else
return false;
}
}
return openingBraces.Count == 0;
}
private Dictionary<char, char> BuildBracketMap()
{
return new Dictionary<char, char>()
{
{'[', ']'},
{'(', ')'},
{'{', '}'}
};
}
}
Quick fix for the issue described by @Malachiasz
I've fixed the issue by adding custom support for this in the auto resize class:
public void setTextCompat(final CharSequence text) {
setTextCompat(text, BufferType.NORMAL);
}
public void setTextCompat(final CharSequence text, BufferType type) {
// Quick fix for Android Honeycomb and Ice Cream Sandwich which sets the text only on the first call
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 &&
Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
super.setText(DOUBLE_BYTE_WORDJOINER + text + DOUBLE_BYTE_WORDJOINER, type);
} else {
super.setText(text, type);
}
}
@Override
public CharSequence getText() {
String originalText = super.getText().toString();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 &&
Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
// We try to remove the word joiners we added using compat method - if none found - this will do nothing.
return originalText.replaceAll(DOUBLE_BYTE_WORDJOINER, "");
} else {
return originalText;
}
}
Just call yourView.setTextCompat(newTextValue)
instead of yourView.setText(newTextValue)
by creating an absolute-positioned link inside relative-positioned div.. You need set the link width & height as button dimensions, and left&top coordinates for the left-top corner of button within the wrapping div.
<div style="position:relative">
<img src="" width="??" height="??" />
<a href="#" style="display:block; width:247px; height:66px; position:absolute; left: 48px; top: 275px;"></a>
</div>
You have more static resources that the cache has room for. You can do one of the following:
For more details see the documentation for these configuration options.
An extremely simple way to auto-compile upon save is to type the following into the terminal:
tsc main --watch
where main.ts
is your file name.
Note, this will only run as long as this terminal is open, but it's a very simple solution that can be run while you're editing a program.
If you are using Swift 2, here is an example my colleague came up with, which adds isNilOrEmpty property on optional Strings:
protocol OptionalString {}
extension String: OptionalString {}
extension Optional where Wrapped: OptionalString {
var isNilOrEmpty: Bool {
return ((self as? String) ?? "").isEmpty
}
}
You can then use isNilOrEmpty on the optional string itself
func testNilOrEmpty() {
let nilString:String? = nil
XCTAssertTrue(nilString.isNilOrEmpty)
let emptyString:String? = ""
XCTAssertTrue(emptyString.isNilOrEmpty)
let someText:String? = "lorem"
XCTAssertFalse(someText.isNilOrEmpty)
}
There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.
Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.
__func__
is documented in the C++0x standard at section 8.4.1. In this case it's a predefined function local variable of the form:
static const char __func__[] = "function-name ";
where "function name" is implementation specfic. This means that whenever you declare a function, the compiler will add this variable implicitly to your function. The same is true of __FUNCTION__
and __PRETTY_FUNCTION__
. Despite their uppercasing, they aren't macros. Although __func__
is an addition to C++0x
g++ -std=c++98 ....
will still compile code using __func__
.
__PRETTY_FUNCTION__
and __FUNCTION__
are documented here http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/Function-Names.html#Function-Names. __FUNCTION__
is just another name for __func__
. __PRETTY_FUNCTION__
is the same as __func__
in C but in C++ it contains the type signature as well.
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
The easiest way to fix this is to add a new factor to your column. Use the levels function to determine how many factors you have and then add a new factor.
> levels(data$Fireplace.Qu)
[1] "Ex" "Fa" "Gd" "Po" "TA"
> levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
[1] "Ex" "Fa" "Gd" "Po" " TA" "None"
With Bootstrap 4:
if ($('#myModal').hasClass('show')) {
alert("Modal is visible")
}
I dont get it clearly, do you want to link an external css as the structure of files you defined above? If yes then just use the link tag :
<link rel="stylesheet" type="text/css" href="file.css">
so basically for files that are under your website folder (folder containing your index) you directly call it. For each successive folder use the "/" for example in your case :
<link rel="stylesheet" type="text/css" href="Fonts/Font1/file name">
<link rel="stylesheet" type="text/css" href="Fonts/Font2/file name">
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
If SDK folder is present in system, one can find in C:\Users\%USERNAME%\AppData\Local\Android
If Android/SDK folder is not found Once done with downloading and installing Android Studio, you need to launch studio. On launching Android studio for the first time, we get option to download further more components, in that we have SDK. On downloading components one can find SDK under Appdata (C:\Users\%USERNAME%\AppData\Local\Android)
Since others are suggesting 3rd party programs (Python, Perl, custom app, etc), another option is GNU CoreUtils for Windows available at http://gnuwin32.sourceforge.net/packages/coreutils.htm.
2 options for deployment:
One benefit of deploying CoreUtils is that you'll additionally get a host of other programs that are helpful for scripting (Windows batch leaves a lot to be desired).
delete from table where id <> 2
edit: to correct syntax for MySQL
Don't know another way of checking this, but this: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties()" implies "java.version" is a standard system property so I'd expect it to work with other JVMs.
xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
Here is the source of these column flags
http://dev.mysql.com/doc/workbench/en/wb-table-editor-columns-tab.html
You have to override the bootstrap default by being a bit more specific. Try this for a black background:
html body {
background-color: rgba(0,0,0,1.00);
}
Try this one it's easy.. to Pic a Image using UIImagePickerControllerDelegate
@objc func masterAction(_ sender: UIButton)
{
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
print("Button capture")
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
print("hello i'm touch \(sender.tag)")
}
func imagePickerControllerDidCancel(_ picker:
UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
print("Get Image \(chosenImage)")
ImageList.insert(chosenImage, at: 0)
ArrayList.insert("", at: 0)
Collection_Vw.reloadData()
} else{
print("Something went wrong")
}
self.dismiss(animated: true, completion: nil)
}
Try This
Write code in your service
import {Observable, of} from 'rxjs';
import json file
import Product from "./database/product.json";
getProduct(): Observable<any> {
return of(Product).pipe(delay(1000));
}
In component
get_products(){
this.sharedService.getProduct().subscribe(res=>{
console.log(res);
})
}
A simple answer to this question can be:
I Think It Will Help. I Used Simple Code Like:
#include <iostream>
using namespace std;
int main()
{int n,r;
cout<<"Enter Your Number:";
cin>>n;
while(n!=0)
{
r=n%10;
n=n/10;
cout<<r;
}
cout<<endl;
system("PAUSE");
return 0;
}
Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
var row_index = $(this).closest("tr").index();
var col_index = $(this).index();
});
This can be solved by the following step:
Please ensure "Windows Hypervisor Platform" is installed. If it's not installed, install it, restart your computer and you will be good to go.
Very old but I have just struggled with this, this is how I solved it in pure xml. In res/values/colors.xml I added three colours (the colour_...);
<resources>
<color name="black_overlay">#66000000</color>
<color name="colour_highlight_grey">#ff666666</color>
<color name="colour_dark_blue">#ff000066</color>
<color name="colour_dark_green">#ff006600</color>
</resources>
In the res/drawable folder I created listview_colours.xml which contained;
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/colour_highlight_grey" android:state_pressed="true"/>
<item android:drawable="@color/colour_dark_blue" android:state_selected="true"/>
<item android:drawable="@color/colour_dark_green" android:state_activated="true"/>
<item android:drawable="@color/colour_dark_blue" android:state_focused="true"/>
</selector>
In the main_activity.xml find the List View and add the drawable to listSelector;
<ListView
android:id="@+id/menuList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/listview_colours"
android:background="#ff222222"/>
</LinearLayout>
Play with the state_... items in the listview_colours.xml to get the effect you want.
There is also a method where you can set the style of the List View but I never managed to get it to work
To apply a stash and remove it from the stash list, run:
git stash pop stash@{n}
To apply a stash and keep it in the stash cache, run:
git stash apply stash@{n}
For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.
I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:
When no input has been given yet, I would advise:
touchUi = true
on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.
My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.
Edit: Result
<div fxLayout="row">
<div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
<mat-form-field>
<input matInput [ngxTimepicker]="endTime" [format]="24" placeholder="{{placeholderTime}}" formControlName="endTime" />
</mat-form-field>
<ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
</div>
<div>
<mat-form-field>
<input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
[min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
<mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
<mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
</mat-form-field>
</div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';
import * as moment_ from 'moment';
const moment = moment_;
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
class DateConfig {
startView: 'month' | 'year' | 'multi-year';
touchUi: boolean;
minDate: moment_.Moment;
maxDate: moment_.Moment;
}
@Component({
selector: 'cb-datetimepicker',
templateUrl: './cb-datetimepicker.component.html',
styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {
@Input() disabled: boolean;
@Input() placeholderDate: string;
@Input() placeholderTime: string;
@Input() model: Date;
@Input() purpose: string;
@Input() dateOnly: boolean;
@Output() dateUpdate = new EventEmitter<Date>();
public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);
public dateForm: FormControl;
public timeFormGroup: FormGroup;
public endTime: FormControl;
public momentDate: moment_.Moment;
public config: DateConfig;
//myGroup: FormGroup;
constructor(private adapter : DateAdapter<any>) { }
ngOnInit() {
this.adapter.setLocale("nl-NL");//todo: configurable
this.config = new DateConfig();
if (this.purpose === "birthday") {
this.config.startView = 'multi-year';
this.config.maxDate = moment().add('year', -15);
this.config.minDate = moment().add('year', -90);
this.dateOnly = true;
} //add more configurations
else {
this.config.startView = 'month';
this.config.maxDate = moment().add('year', 100);
this.config.minDate = moment().add('year', -100);
}
if (window.screen.width < 767) {
this.config.touchUi = true;
}
if (this.model) {
var mom = moment(this.model);
if (mom.isBefore(moment('1900-01-01'))) {
this.momentDate = moment();
} else {
this.momentDate = mom;
}
} else {
this.momentDate = moment();
}
this.dateForm = new FormControl(this.momentDate);
if (this.disabled) {
this.dateForm.disable();
}
this.endTime = new FormControl(this.momentDate.format("HH:mm"));
this.timeFormGroup = new FormGroup({
endTime: this.endTime
});
}
public dateChange(date: MatDatepickerInputEvent<any>) {
if (moment.isMoment(date.value)) {
this.momentDate = moment(date.value);
if (this.dateOnly) {
this.momentDate = this.momentDate.utc(true);
}
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
console.log("datechange",date);
}
public timeChange(time: string) {
var splitted = time.split(':');
var hour = splitted[0];
var minute = splitted[1];
console.log("time change", time);
this.momentDate = this.momentDate.set('hour', parseInt(hour));
this.momentDate = this.momentDate.set('minute', parseInt(minute));
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
}
One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126
I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).
Please note a trailing comma will be added if the tuple only has one item. e.g:
t = (1,)
print 'this is a tuple {}'.format(t)
and you'll get:
'this is a tuple (1,)'
in some cases e.g. you want to get a quoted list to be used in mysql query string like
SELECT name FROM students WHERE name IN ('Tom', 'Jerry');
you need to consider to remove the tailing comma use replace(',)', ')') after formatting because it's possible that the tuple has only 1 item like ('Tom',), so the tailing comma needs to be removed:
query_string = 'SELECT name FROM students WHERE name IN {}'.format(t).replace(',)', ')')
Please suggest if you have decent way of removing this comma in the output.
I used brute force and removed the remote and then added it
git remote rm <remote>
git remote add <url or ssh>
If you want to do this in VBA, then this is a shorter method:
Sub FillBlanksWithNull()
'This macro will fill all "blank" cells with the text "Null"
'When no range is selected, it starts at A1 until the last used row/column
'When a range is selected prior, only the blank cell in the range will be used.
On Error GoTo ErrHandler:
Selection.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "Null"
Exit Sub
ErrHandler:
MsgBox "No blank cells found", vbDefaultButton1, Error
Resume Next
End Sub
Regards,
Robert Ilbrink
Query to show a 3-variable boolean expression truth table :
;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
CASE WHEN
(A=1) OR (B=1) AND (C=1)
THEN 'True' ELSE 'False' END AS Result
FROM cteData
Results for (A=1) OR (B=1) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 True
1 0 1 True
1 1 0 True
1 1 1 True
Results for (A=1) OR ( (B=1) AND (C=1) )
are the same.
Results for ( (A=1) OR (B=1) ) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 False
1 0 1 True
1 1 0 False
1 1 1 True
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
As jzd says, you can use System.currentTimeMillis
. If you need it in a Date
object but don't want to create a new Date
object, you can use Date.setTime
to reuse an existing Date
object. Personally I hate the fact that Date
is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar
has a setTimeInMillis
method.
If possible though, it would probably be better just to keep it as a long
. If you only need a timestamp, effectively, then that would be the best approach.
values timestampdiff (16, char(
timestamp(current timestamp + 1 year + 2 month - 3 day)-
timestamp(current timestamp)))
1
=
422
values timestampdiff (16, char(
timestamp('2012-03-08-00.00.00')-
timestamp('2011-12-08-00.00.00')))
1
=
90
---------- EDIT BY galador
SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'
EDIT
As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:
SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00
WHERE CHSTAT = '05';
Using PowerShell, you can use the following
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name
This will show a list off all services which displayname starts with "NATION-".
You can also directly stop or start the services;
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service
or simply
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service
I solved this problem: Close Visual Studio, open it again and load the solution, Rebuild your solution. My problem occurred using TFS and VIsual Studio 2010.
This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);
Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).
You can always use the DATALENGTH Function to determine if you have extra white space characters in text fields. This won't make the text visible but will show you where there are extra white space characters.
SELECT DATALENGTH('MyTextData ') AS BinaryLength, LEN('MyTextData ') AS TextLength
This will produce 11 for BinaryLength and 10 for TextLength.
In a table your SQL would like this:
SELECT *
FROM tblA
WHERE DATALENGTH(MyTextField) > LEN(MyTextField)
This function is usable in all versions of SQL Server beginning with 2005.
Dear You have used two Intent launcher in your Manifest. Make only one Activity as launcher: Your manifest activity is :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.ALTERNATIVE" />
</intent-filter>
</activity>
</application>
</manifest>
now write code will be ( i have made your 'MyActivityBook' your default activity launcher. Copy and paste it on your manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
</activity>
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and Second error may be if you copy paste old code then please update com.example.packagename.FILE_NAME
hope this will work !
You can't from C#. From IL, this is actually supported. You can do a non-virt call to any of your parent classes... but please don't. :)
Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;