in my case
my service has function to Upload Files
and this error just shown up on trying to upload Big Files
so I found this answer to Increase maxRequestLength
to needed value in web.config
and problem solved
if you don't make any upload or download operations maybe this answer will not help you
First, go to c:\mongodb\bin>
to turn on mongoDB, if you see in console that mongo is listening in port 27017, it is OK
If not, close console and create folder c:\data\db
and start mongod again
The diffrence is very simple:
Long version
If you want to have better readability, use Math.floor
. But if you want to minimize it, use tilde ~~
.
There are a lot of sources on the internet saying Math.floor
is faster, but sometimes ~~
. I would not recommend you think about speed because it is not going to be noticed when running the code. Maybe in tests etc, but no human can see a diffrence here. What would be faster is to use ~~
for a faster load time.
Short version
~~
is shorter/takes less space. Math.floor
improves the readability. Sometimes tilde is faster, sometimes Math.floor
is faster, but it is not noticeable.
As all the above answers have suggested it will throw a NullPointerException.
Please initialise it with some value(s) and then you can use the length property correctly. For example:
String[] str = { "plastic", "paper", "use", "throw" };
System.out.println("Length is:::" + str.length);
The array 'str' is now defined, and so it's length also has a defined value.
You could maybe create a component that determines the offset between System.nanoTime() and System.currentTimeMillis() and effectively get nanoseconds since epoch.
public class TimerImpl implements Timer {
private final long offset;
private static long calculateOffset() {
final long nano = System.nanoTime();
final long nanoFromMilli = System.currentTimeMillis() * 1_000_000;
return nanoFromMilli - nano;
}
public TimerImpl() {
final int count = 500;
BigDecimal offsetSum = BigDecimal.ZERO;
for (int i = 0; i < count; i++) {
offsetSum = offsetSum.add(BigDecimal.valueOf(calculateOffset()));
}
offset = (offsetSum.divide(BigDecimal.valueOf(count))).longValue();
}
public long nowNano() {
return offset + System.nanoTime();
}
public long nowMicro() {
return (offset + System.nanoTime()) / 1000;
}
public long nowMilli() {
return System.currentTimeMillis();
}
}
Following test produces fairly good results on my machine.
final Timer timer = new TimerImpl();
while (true) {
System.out.println(timer.nowNano());
System.out.println(timer.nowMilli());
}
The difference seems to oscillate in range of +-3ms. I guess one could tweak the offset calculation a bit more.
1495065607202174413
1495065607203
1495065607202177574
1495065607203
...
1495065607372205730
1495065607370
1495065607372208890
1495065607370
...
The Wikipedia newline article might help you out. Here is an excerpt:
The different newline conventions often cause text files that have been transferred between systems of different types to be displayed incorrectly. For example, files originating on Unix or Apple Macintosh systems may appear as a single long line on some programs running on Microsoft Windows. Conversely, when viewing a file originating from a Windows computer on a Unix system, the extra CR may be displayed as ^M or at the end of each line or as a second line break.
ComponentWillReceiveProps()
is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate()
and ShouldComponentUpdate()
.
ComponentDidUpdate()
is called whenever the component updates AND if ShouldComponentUpdate()
returns true (If ShouldComponentUpdate()
is not defined it returns true
by default).
shouldComponentUpdate(nextProps){
return nextProps.changedProp !== this.state.changedProp;
}
componentDidUpdate(props){
// Desired operations: ex setting state
}
This same behavior can be accomplished using only the ComponentDidUpdate()
method by including the conditional statement inside of it.
componentDidUpdate(prevProps){
if(prevProps.changedProp !== this.props.changedProp){
this.setState({
changedProp: this.props.changedProp
});
}
}
If one attempts to set the state without a conditional or without defining ShouldComponentUpdate()
the component will infinitely re-render
[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.
Roughly (untested):
app.get('/users/:email/messages/unread', function(req, res, next) {
var firstItem=true, query=MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
query.each(function(docs) {
// Start the JSON array or separate the next element.
res.write(firstItem ? (firstItem=false,'[') : ',');
res.write(JSON.stringify({ msgId: msg.fileName }));
});
res.end(']'); // End the JSON array and response.
});
Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:
// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));
Well, all the answers already given seem to explain which tools you can use to detect merge conflicts or how to initiate merge reqests...
The answer to your question however is both simple and frustrating. Merge conflicts are almost always to solve by hand manually. If you use a tool like e.g. GitLab, the GUI might help you to find differences in two code versions but at the end of the day, you have to decide which line should be kept and which should be erased.
A simple example: Programmer A and programmer B both push the same - differently modified - file to a remote repository. Programmer A opens a merge request and GitLab highlights several lines of code where conflicts occur between the two versions. Now it is up to Programmer A and B to decide, who wrote better code in these specific lines. They have to make compromises.
If you want to fake a $_GET (or a $_POST) when including a file, you can use it like you would use any other var, like that:
$_GET['key'] = 'any get value you want';
include('your_other_file.php');
Like @Lo Juego said, read the article
a, a:active, a:focus {
outline: none;
}
One possible C loop would be:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
/*
** Do something with c, such as check against '\n'
** and increment a line counter.
*/
}
}
For now, I would ignore feof
and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.
Pitfall to avoid: using char
for the type of c. getchar
returns the next character cast to an unsigned char
and then to an int
. This means that on most [sane] platforms the value of EOF
and valid "char
" values in c
don't overlap so you won't ever accidentally detect EOF
for a 'normal' char
.
I will translate John La Rooy's list comprehension to nested for's, just in case anyone else has trouble understanding it.
result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]
Should be equivalent to:
import glob
import os
result = []
for x in os.walk(PATH):
for y in glob.glob(os.path.join(x[0], '*.txt')):
result.append(y)
Here's the documentation for list comprehension and the functions os.walk and glob.glob.
I think you are looking for below code changes:
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php if($options=="PHP") echo 'selected="selected"'; ?> >PHP</option>
<option value="ASP" <?php if($options=="ASP") echo 'selected="selected"'; ?> >ASP</option>
</select>
To clone a branch without fetching other branches:
mkdir $BRANCH
cd $BRANCH
git init
git remote add -t $BRANCH -f origin $REMOTE_REPO
git checkout $BRANCH
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
You can get all keys / values and preserve the hierarchy with this
// get keys of an object or array
function getkeys(z){
var out=[];
for(var i in z){out.push(i)};
return out;
}
// print all inside an object
function allInternalObjs(data, name) {
name = name || 'data';
return getkeys(data).reduce(function(olist, k){
var v = data[k];
if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
else { olist.push(name + '.' + k + ' = ' + v); }
return olist;
}, []);
}
// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
This is a modification on (https://stackoverflow.com/a/25063574/1484447)
I'm a PostgreSQL DBA, as far as I could understand the difference between outer or not outer joins difference is a topic that has considerable discussion all around the internet. Until today I never saw a difference between those two; So I went further and I try to find the difference between those. At the end I read the whole documentation about it and I found the answer for this,
So if you look on documentation (at least in PostgreSQL) you can find this phrase:
In another words,
LEFT JOIN
and LEFT OUTER JOIN
ARE THE SAME
RIGHT JOIN
and RIGHT OUTER JOIN
ARE THE SAME
I hope it can be a contribute for those who are still trying to find the answer.
There is a very simple way to remove NULL values from JSON object. By default JSON object includes NULL values. Following can be used to remove NULL from JSON string
JsonConvert.SerializeObject(yourClassObject, new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore}))
I know this has been answered, but this issue confused me so many times I've put up a small reference website to help me remember: https://nitaym.github.io/ourstheirs/
Here are the basics:
$ git checkout master
$ git merge feature
If you want to select the version in master
:
$ git checkout --ours codefile.js
If you want to select the version in feature
:
$ git checkout --theirs codefile.js
$ git checkout feature
$ git rebase master
If you want to select the version in master
:
$ git checkout --ours codefile.js
If you want to select the version in feature
:
$ git checkout --theirs codefile.js
(This is for complete files, of course)
Fixed - My .eslintrc.js looks like this:
module.exports = {
root: true,
extends: '@react-native-community',
rules: {'prettier/prettier': ['error', {endOfLine: 'auto'}]},
};
You can/should set your parameter to value to DBNull.Value;
if (variable == "")
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}
Or you can leave your server side set to null and not pass the param at all.
Extract From Jettison:
public static String quote(String string) {
if (string == null || string.length() == 0) {
return "\"\"";
}
char c = 0;
int i;
int len = string.length();
StringBuilder sb = new StringBuilder(len + 4);
String t;
sb.append('"');
for (i = 0; i < len; i += 1) {
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
// if (b == '<') {
sb.append('\\');
// }
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ') {
t = "000" + Integer.toHexString(c);
sb.append("\\u" + t.substring(t.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
There is no explicit analogue - i think you are expected to use string concatenations(likely optimized as said before) or third-party class(i doubt that they are a lot more efficient - lists in python are dynamic-typed so no fast-working char[] for buffer as i assume). Stringbuilder-like classes are not premature optimization because of innate feature of strings in many languages(immutability) - that allows many optimizations(for example, referencing same buffer for slices/substrings). Stringbuilder/stringbuffer/stringstream-like classes work a lot faster than concatenating strings(producing many small temporary objects that still need allocations and garbage collection) and even string formatting printf-like tools, not needing of interpreting formatting pattern overhead that is pretty consuming for a lot of format calls.
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Or, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as
.
This is how I got it working on httpClient 4.5 (as per Olive Tree request):
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(this.user, this.password));
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1", "TLSv1.1"},
null,
new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setSSLSocketFactory(sslsf)
.build();
return httpclient;
You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.
But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:
preventDefault
method)First, you'll have to cancel the form submit action like so:
$("#myform").submit(function(event) {
// Cancels the form's submit action.
event.preventDefault();
});
And then, grab the value of the data. Let's just assume you have one text box.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
});
And then fire off a request. Let's just assume it's a POST request.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
// I like to use defers :)
deferred = $.post("http://somewhere.com", { val: val });
deferred.success(function () {
// Do your stuff.
});
deferred.error(function () {
// Handle any errors here.
});
});
And this should about do it.
Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.
Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.
$.post("http://somewhere.com", { val: val }, function () {
// Start partying here.
}, function () {
// Handle the bad news here.
});
Use YAML files for properties, this supports properties as an array.
Quick glance about YAML:
A superset of JSON, it can do everything JSON can + more
I tryed what hgmnz saids on SQL Server 2012.
Management created to me:
EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'MyDataBase'
GO
USE [master]
GO
/****** Object: Database [MyDataBase] Script Date: 09/09/2014 15:58:46 ******/
DROP DATABASE [MyDataBase]
GO
You can use jQuery.children property.
var numItems = $('.wrapper').children('div').length;
for more information refer http://api.jquery.com/
Jenkins has a 'Replay' feature, which enables you to quickly replay a job without updating sources:
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
This is what I wrote using recursive methods:
public static int[] BubbleSort(int[] input)
{
bool isSorted = true;
for (int i = 0; i < input.Length; i++)
{
if (i != input.Length - 1 && input[i] > input[i + 1])
{
isSorted = false;
int temp = input[i];
input[i] = input[i + 1];
input[i + 1] = temp;
}
}
return isSorted ? input : BubbleSort(input);
}
Look up the man page for getcwd
.
private boolean isOnlyLetters(String s){
char c=' ';
boolean isGood=false, safe=isGood;
int failCount=0;
for(int i=0;i<s.length();i++){
c = s.charAt(i);
if(Character.isLetter(c))
isGood=true;
else{
isGood=false;
failCount+=1;
}
}
if(failCount==0 && s.length()>0)
safe=true;
else
safe=false;
return safe;
}
I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.
Use Time YYYYDDDD
(Year + Day of Year) as prefix. This decreases database fragmentation in tables and indexes. This method returns byte[40]
. I used it in a hybrid environment where the Active Directory SID (varbinary(85)
) is the key for LDAP users and an application auto-generated ID is used for non-LDAP Users. Also the large number of transactions per day in transactional tables (Banking Industry) cannot use standard Int
types for Keys
private static final DecimalFormat timeFormat4 = new DecimalFormat("0000;0000");
public static byte[] getSidWithCalendar() {
Calendar cal = Calendar.getInstance();
String val = String.valueOf(cal.get(Calendar.YEAR));
val += timeFormat4.format(cal.get(Calendar.DAY_OF_YEAR));
val += UUID.randomUUID().toString().replaceAll("-", "");
return val.getBytes();
}
call below method on div or body tag onclick="show(event);" function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
You can also use a transparent color:
android:background="@android:color/transparent"
The test
thing may count too. It worked for me (based on Bash Shell: Check File Exists or Not):
test -e FILENAME && echo "File exists" || echo "File doesn't exist"
Solution working with different types and with upper and lower cases.
For example, without the toLowerCase
statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.
JSON DATA:
var people = [
{
"f_name" : "john",
"l_name" : "doe", // lower case
"sequence": 0 // int
},
{
"f_name" : "michael",
"l_name" : "Goodyear", // upper case
"sequence" : 1 // int
}];
JSON Sort Function:
function sortJson(element, prop, propType, asc) {
switch (propType) {
case "int":
element = element.sort(function (a, b) {
if (asc) {
return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);
} else {
return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);
}
});
break;
default:
element = element.sort(function (a, b) {
if (asc) {
return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);
} else {
return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);
}
});
}
}
Usage:
sortJson(people , "l_name", "string", true);
sortJson(people , "sequence", "int", true);
var people = [{_x000D_
"f_name": "john",_x000D_
"l_name": "doe",_x000D_
"sequence": 0_x000D_
}, {_x000D_
"f_name": "michael",_x000D_
"l_name": "Goodyear",_x000D_
"sequence": 1_x000D_
}, {_x000D_
"f_name": "bill",_x000D_
"l_name": "Johnson",_x000D_
"sequence": 4_x000D_
}, {_x000D_
"f_name": "will",_x000D_
"l_name": "malone",_x000D_
"sequence": 2_x000D_
}, {_x000D_
"f_name": "tim",_x000D_
"l_name": "Allen",_x000D_
"sequence": 3_x000D_
}];_x000D_
_x000D_
function sortJsonLcase(element, prop, asc) {_x000D_
element = element.sort(function(a, b) {_x000D_
if (asc) {_x000D_
return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);_x000D_
} else {_x000D_
return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
function sortJson(element, prop, propType, asc) {_x000D_
switch (propType) {_x000D_
case "int":_x000D_
element = element.sort(function(a, b) {_x000D_
if (asc) {_x000D_
return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);_x000D_
} else {_x000D_
return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);_x000D_
}_x000D_
});_x000D_
break;_x000D_
default:_x000D_
element = element.sort(function(a, b) {_x000D_
if (asc) {_x000D_
return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);_x000D_
} else {_x000D_
return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);_x000D_
}_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
function sortJsonString() {_x000D_
sortJson(people, 'l_name', 'string', $("#chkAscString").prop("checked"));_x000D_
display();_x000D_
}_x000D_
_x000D_
function sortJsonInt() {_x000D_
sortJson(people, 'sequence', 'int', $("#chkAscInt").prop("checked"));_x000D_
display();_x000D_
}_x000D_
_x000D_
function sortJsonUL() {_x000D_
sortJsonLcase(people, 'l_name', $('#chkAsc').prop('checked'));_x000D_
display();_x000D_
}_x000D_
_x000D_
function display() {_x000D_
$("#data").empty();_x000D_
$(people).each(function() {_x000D_
$("#data").append("<div class='people'>" + this.l_name + "</div><div class='people'>" + this.f_name + "</div><div class='people'>" + this.sequence + "</div><br />");_x000D_
});_x000D_
}
_x000D_
body {_x000D_
font-family: Arial;_x000D_
}_x000D_
.people {_x000D_
display: inline-block;_x000D_
width: 100px;_x000D_
border: 1px dotted black;_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
}_x000D_
.buttons {_x000D_
border: 1px solid black;_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
float: left;_x000D_
width: 20%;_x000D_
}_x000D_
ul {_x000D_
margin: 5px 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
Sort the JSON array <strong style="color: red;">with</strong> toLowerCase:_x000D_
<ul>_x000D_
<li>Type: string</li>_x000D_
<li>Property: lastname</li>_x000D_
</ul>_x000D_
<button onclick="sortJsonString(); return false;">Sort JSON</button>_x000D_
Asc Sort_x000D_
<input id="chkAscString" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(255, 214, 215, 1);">_x000D_
Sort the JSON array <strong style="color: red;">without</strong> toLowerCase:_x000D_
<ul>_x000D_
<li>Type: string</li>_x000D_
<li>Property: lastname</li>_x000D_
</ul>_x000D_
<button onclick="sortJsonUL(); return false;">Sort JSON</button>_x000D_
Asc Sort_x000D_
<input id="chkAsc" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
Sort the JSON array:_x000D_
<ul>_x000D_
<li>Type: int</li>_x000D_
<li>Property: sequence</li>_x000D_
</ul>_x000D_
<button onclick="sortJsonInt(); return false;">Sort JSON</button>_x000D_
Asc Sort_x000D_
<input id="chkAscInt" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<br />_x000D_
<br />_x000D_
<div id="data" style="float: left; border: 1px solid black; width: 60%; margin: 5px;">Data</div>
_x000D_
Below solution help to find out no of character present from a string with a limitation:
1) using SELECT LEN(REPLACE(myColumn, 'N', '')), but limitation and wrong output in below condition:
SELECT LEN(REPLACE('YYNYNYYNNNYYNY', 'N', ''));
--8 --CorrectSELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --WrongSELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong
2) Try with below solution for correct output:
select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correctselect dbo.vj_count_char_from_string('123a123a12','a');
--2 --Correct
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: VIKRAM JAIN
-- Create date: 20 MARCH 2019
-- Description: Count char from string
-- =============================================
create FUNCTION vj_count_char_from_string
(
@string nvarchar(500),
@find_char char(1)
)
RETURNS integer
AS
BEGIN
-- Declare the return variable here
DECLARE @total_char int; DECLARE @position INT;
SET @total_char=0; set @position = 1;
-- Add the T-SQL statements to compute the return value here
if LEN(@string)>0
BEGIN
WHILE @position <= LEN(@string) -1
BEGIN
if SUBSTRING(@string, @position, 1) = @find_char
BEGIN
SET @total_char+= 1;
END
SET @position+= 1;
END
END;
-- Return the result of the function
RETURN @total_char;
END
GO
In PostMan we have ->Pre-request Script. Paste the Below snippet.
const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());
And now we are ready to use.
{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}
If you are using JPA Entity classes then use the below snippet
@JsonFormat(pattern="MM/dd/yyyy")
@Column(name = "creation_date")
private Date creationDate;
According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date
methods and formatting to accomplish your goal:
function dateToString (date) {
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[date.getMonth()];
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[date.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
alert(dateToString(date));
You could even take it one step further and override the Date.toString()
method:
function dateToString () { // No date argument this time
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[*this*.getMonth()];
var day = *this*.getDate();
var year = *this*.getFullYear();
var hours = *this*.getHours();
var minutes = *this*.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[*this*.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;
alert(date.toString());
If Model.update
statement does not work for you, you can try like this:
try{
await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
}
catch(err){
console.log(err)
}
openssl rsa -in privkey.pem -pubout > key.pub
That writes the public key to key.pub
If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:
ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;
Although there are several ways to do this the most efficient solution to your problem would probably be to use one of the fstream's predefined method such as good(). With this method you can check whether the file you've specified exist or not.
fstream file("file_name.txt");
if (file.good())
{
std::cout << "file is good." << endl;
}
else
{
std::cout << "file isnt good" << endl;
}
I hope you find this useful.
DISCLAIMER: The code below reportedly casued some crashes! Use with care.
according to THIS answer in Excel 2010 and above
CalculateUntilAsyncQueriesDone
halts macros until refresh is done
ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone
In order to use nslookup
, host
or gethostbyname()
then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.
Update (2017/01/05):
GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.
I had the same question and contacted someone GitHub yesterday:
Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.
Unfortunately there's no release date for that function right now.
Run the CMD as admin.
to find more about the instance type : SqlLocalDB info instanceName
now from VS you can setup your connection In VS, View/Server Explorer/(Right click) Data Connections/Add Connection Data Source: Microsoft SQL Server (SqlClient) Server name: (localdb)\MSSQLLocalDB Log on to the server: Use Windows Authentication Press "Test Connection", Then OK.
job done
This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.
def forceAspect(ax,aspect=1):
#aspect is width/height
scale_str = ax.get_yaxis().get_scale()
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
if scale_str=='linear':
asp = abs((xmax-xmin)/(ymax-ymin))/aspect
elif scale_str=='log':
asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
ax.set_aspect(asp)
Obviously you can use any version of log
you want, I've used scipy
, but numpy
or math
should be fine.
You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.
Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.
You can get your package name like so:
$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp
Here are the options:
$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android
-a - directs adb to listen on all interfaces for a connection
-d - directs command to the only connected USB device
returns an error if more than one USB device is present.
-e - directs command to the only running emulator.
returns an error if more than one emulator is running.
-s <specific device> - directs command to the device or emulator with the given
serial number or qualifier. Overrides ANDROID_SERIAL
environment variable.
-p <product name or path> - simple product name like 'sooner', or
a relative/absolute path to a product
out directory like 'out/target/product/sooner'.
If -p is not specified, the ANDROID_PRODUCT_OUT
environment variable is used, which must
be an absolute path.
-H - Name of adb server host (default: localhost)
-P - Port of adb server (default: 5037)
devices [-l] - list all connected devices
('-l' will also list device qualifiers)
connect <host>[:<port>] - connect to a device via TCP/IP
Port 5555 is used by default if no port number is specified.
disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.
Port 5555 is used by default if no port number is specified.
Using this command with no additional arguments
will disconnect from all connected TCP/IP devices.
device commands:
adb push [-p] <local> <remote>
- copy file/dir to device
('-p' to display the transfer progress)
adb pull [-p] [-a] <remote> [<local>]
- copy file/dir from device
('-p' to display the transfer progress)
('-a' means copy timestamp and mode)
adb sync [ <directory> ] - copy host->device only if changed
(-l means list but don't copy)
adb shell - run remote shell interactively
adb shell <command> - run remote shell command
adb emu <command> - run emulator console command
adb logcat [ <filter-spec> ] - View device log
adb forward --list - list all forward socket connections.
the format is a list of lines with the following format:
<serial> " " <local> " " <remote> "\n"
adb forward <local> <remote> - forward socket connections
forward specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
dev:<character device name>
jdwp:<process pid> (remote only)
adb forward --no-rebind <local> <remote>
- same as 'adb forward <local> <remote>' but fails
if <local> is already forwarded
adb forward --remove <local> - remove a specific forward socket connection
adb forward --remove-all - remove all forward socket connections
adb reverse --list - list all reverse socket connections from device
adb reverse <remote> <local> - reverse socket connections
reverse specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
adb reverse --norebind <remote> <local>
- same as 'adb reverse <remote> <local>' but fails
if <remote> is already reversed.
adb reverse --remove <remote>
- remove a specific reversed socket connection
adb reverse --remove-all - remove all reversed socket connections from device
adb jdwp - list PIDs of processes hosting a JDWP transport
adb install [-lrtsdg] <file>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-g: grant all runtime permissions)
adb install-multiple [-lrtsdpg] <file...>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-p: partial application install)
(-g: grant all runtime permissions)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
adb bugreport - return all information from the device
that should be included in a bug report.
adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
- write an archive of the device's data to <file>.
If no -f option is supplied then the data is written
to "backup.ab" in the current directory.
(-apk|-noapk enable/disable backup of the .apks themselves
in the archive; the default is noapk.)
(-obb|-noobb enable/disable backup of any installed apk expansion
(aka .obb) files associated with each application; the default
is noobb.)
(-shared|-noshared enable/disable backup of the device's
shared storage / SD card contents; the default is noshared.)
(-all means to back up all installed applications)
(-system|-nosystem toggles whether -all automatically includes
system applications; the default is to include system apps)
(<packages...> is the list of applications to be backed up. If
the -all or -shared flags are passed, then the package
list is optional. Applications explicitly given on the
command line will be included even if -nosystem would
ordinarily cause them to be omitted.)
adb restore <file> - restore device contents from the <file> backup archive
adb disable-verity - disable dm-verity checking on USERDEBUG builds
adb enable-verity - re-enable dm-verity checking on USERDEBUG builds
adb keygen <file> - generate adb public/private key. The private key is stored in <file>,
and the public key is stored in <file>.pub. Any existing files
are overwritten.
adb help - show this help message
adb version - show version num
scripting:
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-serialno - prints: <serial-number>
adb get-devpath - prints: <device-path>
adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
adb reboot [bootloader|recovery]
- reboots the device, optionally into the bootloader or recovery program.
adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).
adb reboot sideload-auto-reboot
- reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
adb sideload <file> - sideloads the given package
adb root - restarts the adbd daemon with root permissions
adb unroot - restarts the adbd daemon without root permissions
adb usb - restarts the adbd daemon listening on USB
adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port
networking:
adb ppp <tty> [parameters] - Run PPP over USB.
Note: you should not automatically start a PPP connection.
<tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns
adb sync notes: adb sync [ <directory> ]
<localdir> can be interpreted in several ways:
- If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.
- If it is "system", "vendor", "oem" or "data", only the corresponding partition
is updated.
environment variables:
ADB_TRACE - Print debug information. A comma separated list of the following values
1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.
ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.
Strings are immutable, so you need to say
sInputString = sInputString("\"","");
not just the right side of the =
This is a solution suggested by the MySQl manual:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL); mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1); mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.
You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.
It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split()
can do the correct tokenization for args (I'm using Blender's example of the call):
import shlex
from subprocess import Popen, PIPE
command = shlex.split('swfdump /tmp/filename.swf/ -d')
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
I'm assuming that your container element is probably position:relative;
. This is will mean that the dialog box will be positioned accordingly to the container, not the page.
Can you change the markup to this?
<html>
<body>
<!-- Need to place this div at the top right of the page-->
<div class="ajax-message">
<div class="row">
<div class="span9">
<div class="alert">
<a class="close icon icon-remove"></a>
<div class="message-content">
Some message goes here
</div>
</div>
</div>
</div>
</div>
<div class="container">
<!-- Page contents starts here. These are dynamic-->
<div class="row">
<div class="span12 inner-col">
<h2>Documents</h2>
</div>
</div>
</div>
</body>
</html>
With the dialog box outside the main container then you can use absolute positioning relative to the page.
As the other answer correctly notes, you cannot use dynamic functions as a default value. You could use TIMESTAMP
with the CURRENT_TIMESTAMP
attribute, but this is not always possible, for example if you want to keep both a creation and updated timestamp, and you'd need the only allowed TIMESTAMP
column for the second.
In this case, use a trigger instead.
The only way that I have found to do this is VIM or Notepad++.
A reproducible example:
the_plot <- function()
{
x <- seq(0, 1, length.out = 100)
y <- pbeta(x, 1, 10)
plot(
x,
y,
xlab = "False Positive Rate",
ylab = "Average true positive rate",
type = "l"
)
}
James's suggestion of using pointsize
, in combination with the various cex
parameters, can produce reasonable results.
png(
"test.png",
width = 3.25,
height = 3.25,
units = "in",
res = 1200,
pointsize = 4
)
par(
mar = c(5, 5, 2, 2),
xaxs = "i",
yaxs = "i",
cex.axis = 2,
cex.lab = 2
)
the_plot()
dev.off()
Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,
library(ggplot2)
ggplot_alternative <- function()
{
the_data <- data.frame(
x <- seq(0, 1, length.out = 100),
y = pbeta(x, 1, 10)
)
ggplot(the_data, aes(x, y)) +
geom_line() +
xlab("False Positive Rate") +
ylab("Average true positive rate") +
coord_cartesian(0:1, 0:1)
}
ggsave(
"ggtest.png",
ggplot_alternative(),
width = 3.25,
height = 3.25,
dpi = 1200
)
The Runtime.getRuntime().exec()
approach is quite troublesome, as you'll find out shortly.
Take a look at the Apache Commons Exec project. It abstracts you way of a lot of the common problems associated with using the Runtime.getRuntime().exec()
and ProcessBuilder
API.
It's as simple as:
String line = "myCommand.exe";
CommandLine commandLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
int exitValue = executor.execute(commandLine);
public String removeDuplicateChar(String nonUniqueString) {
String uniqueString = "";
for (char currentChar : nonUniqueString.toCharArray()) {
if (!uniqueString.contains("" + currentChar)) {
uniqueString += currentChar;
}
}
return uniqueString;
}
Use df.to_dict('records')
-- gives the output without having to transpose externally.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
var str1 = "150:05:05",
var str2 = "80:04:59";
function compareTime(str1, str2){
if(str1 === str2){
return 0;
}
var time1 = str1.split(':');
var time2 = str2.split(':');
for (var i = 0; i < time1.length; i++) {
if(time1[i] > time2[i]){
return 1;
} else if(time1[i] < time2[i]) {
return -1;
}
}
}
You can do like
$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));
Replace [ADDRESS TO CONTROLLER FUNCTION]
by the way we use in site_url();
You need to echo output
in controller function instead of return
.
No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.
sys.executable
contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documented here
Since I cannot add this as a comment
, I will leave it here for anyone who finds backticks to be easier to read. Its basically @Reigel answer but with backticks
var numbers = [1, 2, 3, 4, 5];
var option = ``;
for (var i=0;i<numbers.length;i++){
option += `<option value=${numbers[i]}>${numbers[i]}</option>`;
}
$('#items').append(option);
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.
For display references on the top of method you have to enabled the CodeLens option in Visual Studio Professional and Visual Studio Enterprise.
Use below steps to enabled it.
1. Go to Tools and then select Options :
2. Then Select Text Editor -> All Languages -> CodeLens
3. Click on check box to Enable Code Lens:
Now you can see the references on the top of methods.
This will not work for VS - Community Edition.
Cheers!
It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:
String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";
Something like this would
String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
// s = "58757843950000120465875468465874567456745674000004000"
For hints, look closer at the class name name that throws an error and the line number, example: Compilation failure [ERROR] \applications\xxxxx.java:[44,30] error: cannot find symbol
One other cause is unsupported method of for java version say jdk7 vs 8. Check your %JAVA_HOME%
In case anyone else wants to achieve this while using binding. If the id of your view is button_save then this code can be written, taking advantage of the kotlin apply syntax
binding.apply {
button_save.setOnClickListener {
//dosomething
}
}
Take note binding is the name of the binding instance created for an xml file . Full code is below if you are writing the code in fragment. Activity works similarly
private lateinit var binding: FragmentProfileBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentProfileBinding.inflate(inflater, container, false)
return binding.root
}
// onActivityCreated is deprecated in fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
button_save.setOnClickListener {
//dosomething
}
}
}
Write your own:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
return container.find(elem) != container.end();
}
Just print out the embed after construction graph (ops) without running:
import tensorflow as tf
...
train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
print (embed)
This will show the shape of the embed tensor:
Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)
Usually, it's good to check shapes of all tensors before training your models.
You might need a bit more background on what a Materialized View actually is. In Oracle these are an object that consists of a number of elements when you try to build it elsewhere.
An MVIEW is essentially a snapshot of data from another source. Unlike a view the data is not found when you query the view it is stored locally in a form of table. The MVIEW is refreshed using a background procedure that kicks off at regular intervals or when the source data changes. Oracle allows for full or partial refreshes.
In SQL Server, I would use the following to create a basic MVIEW to (complete) refresh regularly.
First, a view. This should be easy for most since views are quite common in any database Next, a table. This should be identical to the view in columns and data. This will store a snapshot of the view data. Then, a procedure that truncates the table, and reloads it based on the current data in the view. Finally, a job that triggers the procedure to start it's work.
Everything else is experimentation.
MSDN: Header: Winbase.h (include Windows.h)
You can use the setsockopt function to set a timeout on receive operations:
SO_RCVTIMEO
Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.
// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
Reportedly on Windows this should be done before calling bind
. I have verified by experiment that it can be done either before or after bind
on Linux and OS X.
There is another solution by lord.garbage to run GUI apps in a container without using VNC, SSH and X11 forwarding. It is mentioned here too.
Here's a lightweight library simple-date-format I've written, works both on node.js and in the browser
Install
npm install @riversun/simple-date-format
or
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>
Load Library
import SimpleDateFormat from "@riversun/simple-date-format";
const SimpleDateFormat = require('@riversun/simple-date-format');
Usage1
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"
Usage2
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"
Patterns for formatting
https://github.com/riversun/simple-date-format#pattern-of-the-date
Considering all of your API requests located with a url pattern of /api/..
you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
I know, a lot has been answered to this question but wanted to share where I had the issue of:
curl -X POST http://your-server-end-point -H "Content-Type: application/json" -d @path-of-your-json-file.json
See, I did everything right, Only one thing - "@" I missed before the JSON file path.
I found one relevant go-to document on internet - https://gist.github.com/subfuzion/08c5d85437d5d4f00e58
Hope that might help the few. thanks
You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.
import io
print (io.DEFAULT_BUFFER_SIZE)
In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx
For those of us who this above valid solution didnt work, there's another workaround here
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocused) {
if(!isFocused)
{
Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();
}
}
});
One reason could be, that your activity'name is not defined in the manifest
<activity
android:name=""
...>
</activity>
above code was creating the same issue with me
In case you use MVC to accomplish it - you will have to do something like this
<form action="/ControllerName/ActionName" method="post">
<a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
I just went through some examples here and did not see the MVC one figured it won't hurt to post it.
Then on your Action in the Controller I would just put <HTTPPost>
On the top of it.
I believe if you don't have <HTTPGET>
on the top of it it would still work but explicitly putting it there feels a bit safer.
I tried many suggestions to read in a textfile with German special characters (ä,ö,ü). In the end:
$.ajax({
async:false,
type: "GET",
url: "data/FileName.txt",
dataType: "text",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
alert(data);
}
});
let me read in the special characters, but only AFTER I explicitly saved FileName.txt in the UTF-8 format. The standard format for saving text files in the Windows Editor is ANSI and not UTF-8, but it can be changed if you "Save as" and use the dropbox next to the Save-Button or use a better Editor to start with.
Add !important
rule to display: table
of your .v-center
class.
.v-center {
display:table !important;
border:2px solid gray;
height:300px;
}
Your display property is being overridden by bootstrap to display: block
.
You can also use the join command (dplyr).
For example:
new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))
Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);
This line in your app.php
, 'key' => env('APP_KEY', 'SomeRandomString'),
, is saying that the key for your application can be found in your .env
file on the line APP_KEY
.
Basically it tells Laravel to look for the key in the .env
file first and if there isn't one there then to use 'SomeRandomString'
.
When you use the php artisan key:generate
it will generate the new key to your .env
file and not the app.php
file.
As kotapeter said, your .env
will be inside your root Laravel directory and may be hidden; xampp/htdocs/laravel/blog
Its work perfectly
ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;
But if you want more precise in table then you can try AFTER
.
ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;
It will add LastUpdate
column after specified column name (column_name).
In order to verify a client certificate is being sent to the server, you need to analyze the output from the combination of the -state
and -debug
flags.
First as a baseline, try running
$ openssl s_client -connect host:443 -state -debug
You'll get a ton of output, but the lines we are interested in look like this:
SSL_connect:SSLv3 read server done A
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03 .........
000c - <SPACES/NULS>
SSL_connect:SSLv3 write client certificate A
What's happening here:
The -state
flag is responsible for displaying the end of the previous section:
SSL_connect:SSLv3 read server done A
This is only important for helping you find your place in the output.
Then the -debug
flag is showing the raw bytes being sent in the next step:
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03 .........
000c - <SPACES/NULS>
Finally, the -state
flag is once again reporting the result of the step that -debug
just echoed:
SSL_connect:SSLv3 write client certificate A
So in other words: s_client
finished reading data sent from the server, and sent 12 bytes to the server as (what I assume is) a "no client certificate" message.
If you repeat the test, but this time include the -cert
and -key
flags like this:
$ openssl s_client -connect host:443 \
-cert cert_and_key.pem \
-key cert_and_key.pem \
-state -debug
your output between the "read server done" line and the "write client certificate" line will be much longer, representing the binary form of your client certificate:
SSL_connect:SSLv3 read server done A
write to 0x7bd970 [0x86d890] (1576 bytes => 1576 (0x628))
0000 - 16 03 01 06 23 0b 00 06-1f 00 06 1c 00 06 19 31 ....#..........1
(*SNIP*)
0620 - 95 ca 5e f4 2f 6c 43 11- ..^%/lC.
SSL_connect:SSLv3 write client certificate A
The 1576 bytes
is an excellent indication on its own that the cert was transmitted, but on top of that, the right-hand column will show parts of the certificate that are human-readable: You should be able to recognize the CN and issuer strings of your cert in there.
You can use get() as well as all()
ModelName::where('a', 1)->get(['column1','column2']);
if anyone else has this situation: i am creating an email verification to log in to my app so my users arent signed in yet, however i used the below to check for an email entered on the login which is a variation of @firecape solution
ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);
you will also need the following:
using Microsoft.AspNet.Identity;
and
using Microsoft.AspNet.Identity.Owin;
Using WinRAR command line interface, you can copy the file names and/or file types to an archive. Then you can extract that archive to whatever location you like. This preserves the original file structure.
I needed to add missing album picture files to my mobile phone without having to recopy the music itself. Fortunately the directory structure was the same on my computer and mobile!
I used:
rar a -r C:\Downloads\music.rar X:\music\Folder.jpg
This created an archive with all the Folder.jpg files in the proper subdirectories.
This technique can be used to copy file types as well. If the files all had different names, you could choose to extract all files to a single directory. Additional command line parameters can archive multiple file types.
More information in this very helpful link http://cects.com/using-the-winrar-command-line-tools-in-windows/
Update for Python 3.9
In python 3.9
you could remove suffix using str.removesuffix('suffix')
From the docs,
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string:
set1 = {'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
set2 = set()
for s in set1:
set2.add(s.removesuffix(".good").removesuffix(".bad"))
or using set comprehension:
set2 = {s.removesuffix(".good").removesuffix(".bad") for s in set1}
print(set2)
Output:
{'Orange', 'Pear', 'Apple', 'Banana', 'Potato'}
Use:
ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
Cursor a = System.Windows.Forms.Cursor.Current;
if (a == Cursors.Hand)
{
Point p = richTextBox1.Location;
tip.Show(
GetWord(richTextBox1.Text,
richTextBox1.GetCharIndexFromPosition(e.Location)),
this,
p.X + e.X,
p.Y + e.Y + 32,
1000);
}
}
Use the GetWord function from my other answer to get the hovered word. Use timer logic to disable reshow the tooltip as in prev. example.
In this example right above, the tool tip shows the hovered word by checking the mouse pointer.
If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on. If you want it for bolded word, please tell me.
Java and Kotlin runs on Java Virtual Machine (JVM).
Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.
Steps to convert your Kotlin source file to Java source file:
If you use Homebrew on OS X, then you have a simpler solution:
$ brew install go --with-cc-common # Linux, Darwin, and Windows
or..
$ brew install go --with-cc-all # All the cross-compilers
Use reinstall
if you already have go
installed.
I had the same issue, luckily I found the below code
@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )
If someone used this:
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
PreferenceManager is now depricated, refactor to this:
val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)
Given:
String[] a = new String[] { "Hello", "World", "!" };
Then as an alternative to coobird's answer, where the glue is ", ":
Arrays.asList(a).toString().replaceAll("^\\[|\\]$", "")
Or to concatenate with a different string, such as " & ".
Arrays.asList(a).toString().replaceAll(", ", " & ").replaceAll("^\\[|\\]$", "")
However... this one ONLY works if you know that the values in the array or list DO NOT contain the character string ", ".
Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.
The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.
Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).
The primary benefits of Python Eggs are:
They enable tools like the "Easy Install" Python package manager
.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)
They can include package metadata, such as the other eggs they depend on
They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)
They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.
They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).
There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.
Now, copy the following content in a script file (like: /backup/mysql-backup.sh) and save on your Linux system.
#!/bin/bash
export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=`date +"%d%b%Y"`
DB_BACKUP_PATH='/backup/dbbackup'
MYSQL_HOST='localhost'
MYSQL_PORT='3306'
MYSQL_USER='root'
MYSQL_PASSWORD='mysecret'
DATABASE_NAME='mydb'
BACKUP_RETAIN_DAYS=30
mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "Backup started for database - ${DATABASE_NAME}"
mysqldump -h ${MYSQL_HOST} \
-P ${MYSQL_PORT} \
-u ${MYSQL_USER} \
-p${MYSQL_PASSWORD} \
${DATABASE_NAME} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DATABASE_NAME}-${TODAY}.sql.gz
if [ $? -eq 0 ]; then
echo "Database backup successfully completed"
else
echo "Error found during backup"
exit 1
fi
##### Remove backups older than {BACKUP_RETAIN_DAYS} days #####
DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
if [ ! -z ${DB_BACKUP_PATH} ]; then
cd ${DB_BACKUP_PATH}
if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
rm -rf ${DBDELDATE}
fi
fi
After creating or downloading script make sure to set execute permission to run properly.
$ chmod +x /backup/mysql-backup.sh
Edit crontab on your system with crontab -e command. Add following settings to enable backup at 3 in the morning.
0 3 * * * root /backup/mysql-backup.sh
scanf
uses any whitespace as a delimiter, so if you just say scanf("%d", &var)
it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.
Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.
A diagram
The main difference between static nested
and non-static nested
classes is that static nested
does not have an access to non-static outer class members
It looks to me like the UIWebView has a UIScrollView. You can use documented APIs for this, but bouncing is set for both directions, not individually. This is in the API docs. UIScrollView has a bounce property, so something like this works (don't know if there's more than one scrollview):
NSArray *subviews = myWebView.subviews;
NSObject *obj = nil;
int i = 0;
for (; i < subviews.count ; i++)
{
obj = [subviews objectAtIndex:i];
if([[obj class] isSubclassOfClass:[UIScrollView class]] == YES)
{
((UIScrollView*)obj).bounces = NO;
}
}
Use position: fixed
instead of position: absolute
.
See here.
You could try to replace the metadata:
metadata=res:///conString.csdl|res:///conString.ssdl|res://*/conString.msl
to:
metadata=res://*/;
I have just given width to Label and input type were aligned automatically.
input[type="text"] {_x000D_
width:100px;_x000D_
height:30px;_x000D_
border-radius:5px;_x000D_
background-color: lightblue;_x000D_
margin-left:2px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
label{_x000D_
position:relative;_x000D_
width:300px;_x000D_
border:2px dotted black;_x000D_
margin:20px;_x000D_
padding:5px;_x000D_
font-family:AR CENA;_x000D_
font-size:20px;_x000D_
_x000D_
}
_x000D_
<label>First Name:</label><input type="text" name="fname"><br>_x000D_
<label>Last Name:</label><input type="text" name="lname"><br>
_x000D_
Sorry, read the question wrong the first time. You can do something like this:
declare @result varchar(max)
--must "initialize" result for this to work
select @result = ''
select @result = @result + alias
FROM aliases
WHERE username='Bob'
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', '');
It will return 5.98 without rounding the number.
You are replacing the starting tag and then putting that back in innerHTML
, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
They are different things. The Forms Authentication Timeout value sets the amount of time in minutes that the authentication cookie is set to be valid, meaning, that after value
number of minutes, the cookie will expire and the user will no longer be authenticated—they will be redirected to the login page automatically. The slidingExpiration=true
value is basically saying that as long as the user makes a request within the timeout value, they will continue to be authenticated (more details here). If you set slidingExpiration=false
the authentication cookie will expire after value
number of minutes regardless of whether the user makes a request within the timeout value or not.
The SessionState
timeout value sets the amount of time a Session State provider is required to hold data in memory (or whatever backing store is being used, SQL Server, OutOfProc, etc) for a particular session. For example, if you put an object in Session using the value in your example, this data will be removed after 30 minutes. The user may still be authenticated but the data in the Session may no longer be present. The Session Timeout
value is always reset after every request.
To return true or false depending on whether a checkbox is checked or not, I use this in JQuery
let checkState = $("#checkboxId").is(":checked") ? "true" : "false";
If you set
android:inputType="textPassword"
this property and if you provide number as password example "1234567" it will take it as "123456/" the seventh character is not taken. Thats why instead of this approach use
android:password="true"
property which allows you to enter any type of password without any restriction.
If you want to provide hint use
android:hint="hint text goes here"
example:
android:hint="password"
(source: jfrog.com)
or
Just use Maven repository servers like Sonatype Nexus http://www.sonatype.org/nexus/ or JFrog Artifactory https://www.jfrog.com/artifactory/.
After one developer builds a project, build by next developers or Jenkins CI will not require Internet access.
Maven repository server also can have proxies configured to access Maven Central (or more needed public repositories), and they can have cynch'ed list of artifacts in remote repositories.
Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.
There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.
PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.
You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.
Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!
At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.
In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!
Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?>
on your site and look for the Server API
entry. This could say something like CGI/FastCGI
or Apache 2.0 Handler
.
If you also look at the command-line version of PHP -- thread safety does not matter.
Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!
Here is an example of iterating over a pd.DataFrame
grouped by the column atable
. For this sample, "create" statements for an SQL database are generated within the for
loop:
import pandas as pd
df1 = pd.DataFrame({
'atable': ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
'column': ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
'is_null': ['No', 'No', 'Yes', 'No', 'Yes'],
})
df1_grouped = df1.groupby('atable')
# iterate over each group
for group_name, df_group in df1_grouped:
print('\nCREATE TABLE {}('.format(group_name))
for row_index, row in df_group.iterrows():
col = row['column']
column_type = row['column_type']
is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
print('\t{} {} {},'.format(col, column_type, is_null))
print(");")
Internet Explorer 8 and older don't support the proper MIME type for XHTML, application/xhtml+xml
. If you're serving XHTML as text/html
, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the HTML 4.01 Specification.
The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.
IE9 and later support XHTML 5 served with application/xhtml+xml
.
>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()
where a is your x data b is your y data c is your y error if any
note that c is the error in each direction already
Just add the unique key to the your Components
data.map((marker)=>{
return(
<YourComponents
key={data.id} // <----- unique key
/>
);
})
The English language word assert here is used in the sense of swear, affirm, avow. It doesn't mean "check" or "should be". It means that you as a coder are making a sworn statement here:
# I solemnly swear that here I will tell the truth, the whole truth,
# and nothing but the truth, under pains and penalties of perjury, so help me FSM
assert answer == 42
If the code is correct, barring Single-event upsets, hardware failures and such, no assert will ever fail. That is why the behaviour of the program to an end user must not be affected. Especially, an assert cannot fail even under exceptional programmatic conditions. It just doesn't ever happen. If it happens, the programmer should be zapped for it.
You can use a regular expression for that pretty easily…
Allowing spaces around the word (but not keeping them):
str.match(/< ?([^>]+) ?>\Z/)[1]
Or without the spaces allowed:
str.match(/<([^>]+)>\Z/)[1]
In your particular example you'd do the following routerLink
:
[routerLink]="['user', user.id, 'details']"
To do so in a controller, you can inject Router
and use:
router.navigate(['user', user.id, 'details']);
More info in the Angular docs Link Parameters Array section of Routing & Navigation
You can define a static constructor for the class that will check that the type T is an enum and throw an exception if it is not. This is the method mentioned by Jeffery Richter in his book CLR via C#.
internal sealed class GenericTypeThatRequiresAnEnum<T> {
static GenericTypeThatRequiresAnEnum() {
if (!typeof(T).IsEnum) {
throw new ArgumentException("T must be an enumerated type");
}
}
}
Then in the parse method, you can just use Enum.Parse(typeof(T), input, true) to convert from string to the enum. The last true parameter is for ignoring case of the input.
Since your subdateshow is a VARCHAR column instead of the proper DATE, TIMESTAMP or DATETIME column you have to convert the string to date before you can use YEAR on it:
SELECT YEAR(STR_TO_DATE(subdateshow, "%m/%d/%Y")) from table
See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
You could use a small table to improve speed1. Similar techniques are useful in the embedded world, for example, to invert a byte:
const char *bit_rep[16] = {
[ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
[ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
[ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
[12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};
void print_byte(uint8_t byte)
{
printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}
1 I'm mostly referring to embedded applications where optimizers are not so aggressive and the speed difference is visible.
Your code is creating an array of function pointers. Try
char* a[size];
or
char a[size1][size2];
instead.
you can do:
<div style="float: left;"></div>
or
<div style="display: inline;"></div>
Either one will cause the divs to tile horizontally.
I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.
If you want to execute multiple commands in a for loop, you can save the result of find
with mapfile
(bash >= 4) as an variable and go through the array with ${dirlist[@]}
. It also works with directories containing spaces.
The find
command is based on the answer by Boldewyn. Further information about the find
command can be found there.
IFS=""
mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
echo ">${dir}<"
# more commands can go here ...
done
In my case my column was a datetime it kept giving me all records. What I did is to include time, see below example
SELECT * FROM my_table where start_date > '2011-01-01 01:01:01';
A Java String
is an Object
. (String
extends Object
.)
So you can get an Object
reference via assignment/initialisation:
String a = "abc";
Object b = a;
You can call a reset function before appending. Something like this:
function resetNewReviewBoardForm() {
$("#Description").val('');
$("#PersonName").text('');
$("#members").empty(); //this one what worked in my case
$("#EmailNotification").val('False');
}
Based on the value of this.props.showBulkActions
you can switch classes dynamically as follows.
<div ...{...this.props.showBulkActions
? { className: 'btn-group pull-right show' }
: { className: 'btn-group pull-right hidden' }}>
"The Practice of programming" by Brian W.Kerninghan & Rob Pike.
The language is easy and also the subject matter is interesting.
There is no solution in ANSI SQL to use joins in deletes, AFAIK.
DELETE FROM Table1
WHERE Table1.id IN (SELECT Table2.id FROM Table2)
Later edit
Other solution (sometimes performing faster):
DELETE FROM Table1
WHERE EXISTS( SELECT 1 FROM Table2 Where Table1.id = Table2.id)
The merge()
method on the Collection
does not modify the collection on which it was called. It returns a new collection with the new data merged in. You would need:
$related = $related->merge($tag->questions);
However, I think you're tackling the problem from the wrong angle.
Since you're looking for questions that meet a certain criteria, it would probably be easier to query in that manner. The has()
and whereHas()
methods are used to generate a query based on the existence of a related record.
If you were just looking for questions that have any tag, you would use the has()
method. Since you're looking for questions with a specific tag, you would use the whereHas()
to add the condition.
So, if you want all the questions that have at least one tag with either 'Travel', 'Trains', or 'Culture', your query would look like:
$questions = Question::whereHas('tags', function($q) {
$q->whereIn('name', ['Travel', 'Trains', 'Culture']);
})->get();
If you wanted all questions that had all three of those tags, your query would look like:
$questions = Question::whereHas('tags', function($q) {
$q->where('name', 'Travel');
})->whereHas('tags', function($q) {
$q->where('name', 'Trains');
})->whereHas('tags', function($q) {
$q->where('name', 'Culture');
})->get();
Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.
>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}
Is Perl easily available to you?
$ perl -n -e 'if ($. == 7) { print; exit(0); }'
Obviously substitute whatever number you want for 7.
You have just to enter:
First a IBOutlet:
@IBOutlet var appsTableView : UITableView
Then in a Action func:
self.appsTableView.reloadData()
Here is an example of getting the bounds using svg.getBox()
:
https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44
At the end you get numbers that you can plug into the svg to set the viewbox properly. Then use any css on the parent div and you're done.
// get all SVG objects in the DOM
var svgs = document.getElementsByTagName("svg");
var svg = svgs[0],
box = svg.getBBox(), // <- get the visual boundary required to view all children
viewBox = [box.x, box.y, box.width, box.height].join(" ");
// set viewable area based on value above
svg.setAttribute("viewBox", viewBox);
You can bypass X-Frame-Options in an using YQL.
var iframe = document.getElementsByTagName('iframe')[0];
var url = iframe.src;
var getData = function (data) {
if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
else if (data && data.error && data.error.description) loadHTML(data.error.description);
else loadHTML('Error: Cannot load ' + url);
};
var loadURL = function (src) {
url = src;
var script = document.createElement('script');
script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
document.body.appendChild(script);
};
var loadHTML = function (html) {
iframe.src = 'about:blank';
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
iframe.contentWindow.document.close();
}
loadURL(iframe.src);
<iframe src="http://www.google.co.in" width="500" height="300"></iframe>
Run it here: http://jsfiddle.net/2gou4yen/
Code from here: How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?
// Two different dates
var date1 = new Date(2013, 05, 13);
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate);
I had exactly the same issue: was cleaning up my folders, rearranging and moving files. I entered: git rm . and hit enter; and then felt my bowels loosen a bit. Luckily, I didn't type in git commit -m "" straightaway.
However, the following command
git checkout .
restored everything, and saved my life.
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
For simplicity I am reducing the vector a and b:
Let :
a : [1, 1, 0]
b : [1, 0, 1]
Then cosine similarity (Theta):
(Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5
then inverse of cos 0.5 is 60 degrees.
I had the same problem. It was because I had accidentally used a relative path with the symbolic link.
Are you sure you used full paths, e.g.:
ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf
Given:
A_1 = [10 200 7 150]';
A_2 = [0.001 0.450 0.007 0.200]';
(As others have already pointed out) There are tools to simply compute correlation, most obviously corr
:
corr(A_1, A_2); %Returns 0.956766573975184 (Requires stats toolbox)
You can also use base Matlab's corrcoef
function, like this:
M = corrcoef([A_1 A_2]): %Returns [1 0.956766573975185; 0.956766573975185 1];
M(2,1); %Returns 0.956766573975184
Which is closely related to the cov
function:
cov([condition(A_1) condition(A_2)]);
As you almost get to in your original question, you can scale and adjust the vectors yourself if you want, which gives a slightly better understanding of what is going on. First create a condition function which subtracts the mean, and divides by the standard deviation:
condition = @(x) (x-mean(x))./std(x); %Function to subtract mean AND normalize standard deviation
Then the correlation appears to be (A_1 * A_2)/(A_1^2), like this:
(condition(A_1)' * condition(A_2)) / sum(condition(A_1).^2); %Returns 0.956766573975185
By symmetry, this should also work
(condition(A_1)' * condition(A_2)) / sum(condition(A_2).^2); %Returns 0.956766573975185
And it does.
I believe, but don't have the energy to confirm right now, that the same math can be used to compute correlation and cross correlation terms when dealing with multi-dimensiotnal inputs, so long as care is taken when handling the dimensions and orientations of the input arrays.
You can still use the textmode and force the linefeed-newline with the keyword argument newline
f = open("./foo",'w',newline='\n')
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
Try to enter the full-path of the dll. If it doesn't work, try to copy the dll into the system32 folder.
To expand on Alan's answer, you can create a <Route/>
that redirects all <Link/>
's with "to" attributes containing 'http:' or 'https:' to the correct external resource.
Below is a working example of this which can be placed directly into your <Router>
.
<Route path={['/http:', '/https:']} component={props => {
window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
return null
}}/>
This Solved my problem: Open your VS Project
Double click on Package.appxmanifest
Go to Packaging tab
click choose certificate
click configure certificate
select from file and use example.pfx that unity or anything else created
Just my take on the matter, three months later:
Jenkins has continued the path well-trodden by the original Hudson with frequent releases including many minor updates.
Oracle seems to have largely delegated work on the future path for Hudson to the Sonatype team, who has performed some significant changes, especially with respect to Maven. They have jointly moved it to the Eclipse foundation.
I would suggest that if you like the sound of:
, then I would suggest Hudson.
Conversely, if you prefer:
then I would suggest Jenkins. (and as a commenter noted, Jenkins now also has "LTS" releases which are maintained on a more "stable" branch)
The conservative course would be to choose Hudson now and migrate to Jenkins if must-have features are unavailable. The dynamic course would be to choose Jenkins now and migrate to Hudson if chasing updates becomes too time-consuming to justify.
You can use the Array.prototype.filter
method:
var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});
Live Example:
var obj = {_x000D_
'homes': [{_x000D_
"home_id": "1",_x000D_
"price": "925",_x000D_
"sqft": "1100",_x000D_
"num_of_beds": "2",_x000D_
"num_of_baths": "2.0",_x000D_
}, {_x000D_
"home_id": "2",_x000D_
"price": "1425",_x000D_
"sqft": "1900",_x000D_
"num_of_beds": "4",_x000D_
"num_of_baths": "2.5",_x000D_
},_x000D_
// ... (more homes) ... _x000D_
]_x000D_
};_x000D_
// (Note that because `price` and such are given as strings in your object,_x000D_
// the below relies on the fact that <= and >= with a string and number_x000D_
// will coerce the string to a number before comparing.)_x000D_
var newArray = obj.homes.filter(function (el) {_x000D_
return el.price <= 1000 &&_x000D_
el.sqft >= 500 &&_x000D_
el.num_of_beds >= 2 &&_x000D_
el.num_of_baths >= 1.5; // Changed this so a home would match_x000D_
});_x000D_
console.log(newArray);
_x000D_
This method is part of the new ECMAScript 5th Edition standard, and can be found on almost all modern browsers.
For IE, you can include the following method for compatibility:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i];
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
This is the simplest possible algorithm to find out directory size irrespective of the programming language you are using. For PHP specific implementation. go to: Calculate Directory Size in PHP | Explained with Algorithm | Working Code
Just check connectivity between SQL And your App (if you used SQL)
According to the source code located here, starting at line 850, PostgreSQL doesn't explicitly limit the number of arguments.
The following is a code comment from line 870:
/*
* We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
* possible if the inputs are all scalars (no RowExprs) and there is a
* suitable array type available. If not, we fall back to a boolean
* condition tree with multiple copies of the lefthand expression.
* Also, any IN-list items that contain Vars are handled as separate
* boolean conditions, because that gives the planner more scope for
* optimization on such clauses.
*
* First step: transform all the inputs, and detect whether any are
* RowExprs or contain Vars.
*/
If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location.replace or location.href, etc.) to redirect to whatever URL you want. Of course, that depends on what HTML has already been sent down.
Another option is regex:
>>> import re
>>> re.sub("\n|\r", "", "Foo\n\rbar\n\rbaz\n\r")
'Foobarbaz'
This error comes when there is error in your query syntax check field names table name, mean check your query syntax.
Well that's very interesting, Here is quick and working code:
index.php
/**
* Define APP_URL Dynamically
* Write this at the bottom of index.php
*
* Automatic base url
*/
define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']));
config.php
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = APP_URL;
CodeIgniter ROCKS!!! :)
Another option would be to use the if
with a colon and an endif
instead of the brackets:
<?php if ( has_post_thumbnail() ): ?>
<div class="gridly-image">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) )); ?>
</a>
</div>
<?php endif; ?>
<div class="date">
<span class="day"><?php the_time('d'); ?></span>
<div class="holder">
<span class="month"><?php the_time('M'); ?></span>
<span class="year"><?php the_time('Y'); ?></span>
</div>
</div>
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The
CHECK
clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
Hope that helps.
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
If you have only one level and you use bootstrap 3 add pull-right
to the ul
element
<ul class="dropdown-menu pull-right" role="menu">
It is a bug in IE8.
Starting with your second question: “margin: 0 auto” centers a block, but only when width of the block is set to be less that width of parent. Usually, they get to be the same. That is why text in the example below is not centered.
<div style="height: 100px; width: 500px; background-color: Yellow;">
<b style="display: block; margin: 0 auto; ">text</b>
</div>
Once the display style of the b element is set to block, its width defaults to the parents width. CSS spec 10.3.3 Block-level, non-replaced elements in normal flow describes how: “If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.” The equality mentioned there is
'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
So, normally all autos result in a block width being equal to the width of containing block.
However, this calculation should not be applied to INPUT, which is a replaced element. Replaced elements are covered by 10.3.4 Block-level, replaced elements in normal flow. Text there says: “The used value of 'width' is determined as for inline replaced elements.” The relevant part of 10.3.2 Inline, replaced elements is: “if 'width' has a computed value of 'auto', and the element has an intrinsic width, then that intrinsic width is the used value of 'width'”.
I guess that the scenario CSS cares about is IMG element. Stackoverflow logo in this example will be centered by all browsers.
<div style="height: 100px; width: 500px; background-color: Yellow;">
<img style="display: block; margin: 0 auto; " border="0" src="http://stackoverflow.com/content/img/so/logo.png" alt="">
</div>
INPUT element should behave the same way.
This site uses the method isEmpty()
.
Edit: content grabbed from site, before the url will going to be invalid.
Worksheets("Sheet1").Range("A1").Sort _
key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
Set nextCell = currentCell.Offset(1, 0)
If nextCell.Value = currentCell.Value Then
currentCell.EntireRow.Delete
End If
Set currentCell = nextCell
Loop
In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.
The hottest - and arguably most scalable - approach to overcoming these challenges with large datasets is embodied by the approach of Ionic's collectionRepeat directive and of other implementations like it. A fancy term for this is 'occlusion culling', but you can sum it up as: don't just limit the count of rendered DOM elements to an arbitrary (but still high) paginated number like 50, 100, 500... instead, limit only to as many elements as the user can see.
If you do something like what's commonly known as "infinite scrolling", you're reducing the initial DOM count somewhat, but it bloats quickly after a couple refreshes, because all those new elements are just tacked on at the bottom. Scrolling comes to a crawl, because scrolling is all about element count. There's nothing infinite about it.
Whereas, the collectionRepeat
approach is to use only as many elements as will fit in viewport, and then recycle them. As one element rotates out of view, it's detached from the render tree, refilled with data for a new item in the list, then reattached to the render tree at the other end of the list. This is the fastest way known to man to get new information in and out of the DOM, making use of a limited set of existing elements, rather than the traditional cycle of create/destroy... create/destroy. Using this approach, you can truly implement an infinite scroll.
Note that you don't have to use Ionic to use/hack/adapt collectionRepeat
, or any other tool like it. That's why they call it open-source. :-) (That said, the Ionic team is doing some pretty ingenious things, worthy of your attention.)
There's at least one excellent example of doing something very similar in React. Only instead of recycling the elements with updated content, you're simply choosing not to render anything in the tree that's not in view. It's blazing fast on 5000 items, although their very simple POC implementation allows a bit of flicker...
Also... to echo some of the other posts, using track by
is seriously helpful, even with smaller datasets. Consider it mandatory.
Just wanted to re-emphasize that ++x is expected to be faster than x++, (especially if x is an object of some arbitrary type), so unless required for logical reasons, ++x should be used.
example:
c++ -Wall filefork.cpp -lrt -O2
For gcc
version 4.6.1, -lrt
must be after filefork.cpp otherwise you get a link error.
Some older gcc
version doesn't care about the position.
Have you tried url-encoding the data ? cURL can take care of that for you :
curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/
That Problem is because:- The folder or file you pasted to your product downloaded from the firebase console is not named as google-services.json. so now click it then right mouse click in all the options open refractor and rename it to google-services.json. because this worked for me
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
$env:USERPROFILE = "C:\\Documents and Settings\\[USER]\\"
The Eclipse (software) page on Wikipedia summarizes it pretty well:
Releases
Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.
So far, each Simultaneous Release has occurred at the end of June.
Release Main Release Platform version Projects Photon 27 June 2018 4.8 Oxygen 28 June 2017 4.7 Neon 22 June 2016 4.6 Mars 24 June 2015 4.5 Mars Projects Luna 25 June 2014 4.4 Luna Projects Kepler 26 June 2013 4.3 Kepler Projects Juno 27 June 2012 4.2 Juno Projects Indigo 22 June 2011 3.7 Indigo projects Helios 23 June 2010 3.6 Helios projects Galileo 24 June 2009 3.5 Galileo projects Ganymede 25 June 2008 3.4 Ganymede projects Europa 29 June 2007 3.3 Europa projects Callisto 30 June 2006 3.2 Callisto projects Eclipse 3.1 28 June 2005 3.1 Eclipse 3.0 28 June 2004 3.0
To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier). My suggestion would be to use the latest version, i.e. Eclipse Oxygen (4.7) (in the original version of this answer, it said "Helios (3.6.1)").
On top of the "platform", Eclipse then distributes various Packages (i.e. the "platform" with a default set of plugins to achieve specialized tasks), such as Eclipse IDE for Java Developers, Eclipse IDE for Java EE Developers, Eclipse IDE for C/C++ Developers, etc (see this link for a comparison of their content).
To develop Java Desktop applications, the Helios release of Eclipse IDE for Java Developers should suffice (you can always install "additional plugins" if required).
This is my Java code. Basically comparing the the first and last value of the string and next inner value pair and so forth.
/*Palindrome number*/
String sNumber = "12321";
int l = sNumber.length(); // getting the length of sNumber. In this case its 5
boolean flag = true;
for (int i = 0; i <= l; ++i) {
if (sNumber.charAt(i) != sNumber.charAt((l--) -1)) { //comparing the first and the last values of the string
System.out.println(sNumber +" is not a palindrome number");
flag = false;
break;
}
//l--; // to reducing the length value by 1
}
if (flag) {
System.out.println(sNumber +" is a palindrome number");
}
You'll have to do 2 things to make a Bootstrap label (or anything really) adjust sizes based on screen size:
.label { font-size: 75% }
. So any extra selector on your CSS rule will make it more specific.Here's an example CSS listing to accomplish what you are asking, using the default 4 sizes in Bootstrap:
@media (max-width: 767) {
/* your custom css class on a parent will increase specificity */
/* so this rule will override Bootstrap's font size setting */
.autosized .label { font-size: 14px; }
}
@media (min-width: 768px) and (max-width: 991px) {
.autosized .label { font-size: 16px; }
}
@media (min-width: 992px) and (max-width: 1199px) {
.autosized .label { font-size: 18px; }
}
@media (min-width: 1200px) {
.autosized .label { font-size: 20px; }
}
Here is how it could be used in the HTML:
<!-- any ancestor could be set to autosized -->
<div class="autosized">
...
...
<span class="label label-primary">Label 1</span>
</div>
Just use the existing method.. .ToList();
List<int> listArray = array.ToList();
KISS(KEEP IT SIMPLE SIR)
Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.
The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.
A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.
Link: here for further reading. Hope it helps.
For anyone who must use the ssh keys (for a corporate server).
Just add -i /.ssh/id_rsa
at the end.
$ ssh -N -f -L localhost:8211:localhost:6007 myname@servername -i /.ssh/id_rsa
You can use XML Literals to achieve a similar effect:
Imports System.XML
Imports System.XML.Linq
Imports System.Core
Dim s As String = <a>Hello
World</a>.Value
Remember that if you have special characters, you should use a CDATA block:
Dim s As String = <![CDATA[Hello
World & Space]]>.Value
Multi-line string literals were introduced in Visual Basic 14 (in Visual Studio 2015). The above example can be now written as:
Dim s As String = "Hello
World & Space"
MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.
Details are added to the Roslyn New-Language-Features-in-VB-14 Github repository.
Your currently selected backend, 'agg' does not support show().
AGG
backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site.
ImportError: No module named _backend_gdk
For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it.
Do you call the show()
method inside a terminal or application that has access to a graphical environment?
Try other GUI backends, in this order:
TkAgg
WX
QTAgg
QT4Agg
"title" is widely implemented in browsers. Try:
<a href="#" title="hello">asf</a>
The difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.
For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).
this.$('#datepicker').datepicker({minDate: 1});
minDate:0
- Enable dates in the calender from the current date. MinDate:1
enable dates in the calender currentDate+1
To Restrict date between from tomorrow and the same day next month u need to give something like
$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });
Some things to check:
Can you change to unrestricted?
Set-ExecutionPolicy Unrestricted
Is the group policy set?
Computer Configuration\Administrative Templates\Windows Components\Windows PowerShell
User Configuration\Administrative Templates\Windows Components\Windows PowerShell
Also, how are you calling Script.ps1?
Does this allow it to run?
powershell.exe -executionpolicy bypass -file .\Script.ps1
You need something like this: https://github.com/axkibe/lsyncd It is a tool which combines rsync and inotify - the former is a tool that mirrors, with the correct options set, a directory to the last bit. The latter tells the kernel to notify a program of changes to a directory ot file. It says:
It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes.
But - according to Digital Ocean at https://www.digitalocean.com/community/tutorials/how-to-mirror-local-and-remote-directories-on-a-vps-with-lsyncd - it ought to be in the Ubuntu repository!
I have similar requirements, and this tool, which I have yet to try, seems suitable for the task.
It can also mean that the server is completely inaccessible - I was getting this when trying to hit a server that was offline
My client was configured to connect to localhost:3000, but no server was running on that port.
from PIL import Image
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')
yields
This simple function extracted from Datacamp could help:
replace_missings <- function(x, replacement) {
is_miss <- is.na(x)
x[is_miss] <- replacement
message(sum(is_miss), " missings replaced by the value ", replacement)
x
}
Then
replace_missings(df, replacement = 0)
A quick summary of the concepts:
Example:
Say you've got a button like this:
[ Click Me ]
and you've pinned the edges to a larger superview with priority 500.
Then, if Hugging priority > 500 it'll look like this:
[Click Me]
If Hugging priority < 500 it'll look like this:
[ Click Me ]
If the superview now shrinks then, if the Compression Resistance priority > 500, it'll look like this
[Click Me]
Else if Compression Resistance priority < 500, it could look like this:
[Cli..]
If it doesn't work like this then you've probably got some other constraints going on that are messing up your good work!
E.g. you could have it pinned to the superview with priority 1000. Or you could have a width priority. If so, this can be helpful:
Editor > Size to Fit Content
You can do the following steps:
First isolate the column (by inserting a blank column before and/or after the column you want to count the unique values if there are any adjacent columns;
Then select the whole column, go to 'Data' > 'Advanced Filter' and check the checkbox 'Unique records only'. This will hide all non-unique records so you can count the unique ones by selecting the whole column.
The universal tool for string formatting, sprintf
:
$stamp = sprintf('%s%02s', $year, $month);
function compareIsEqualArray(array $array1,array $array):bool
{
return (array_diff($array1,$array2)==[] && array_diff($array2,$array1)==[]);
}
For those using Visual Studio + Git and wanting to keep the file history (works renaming both projects and/or solutions):
Close Visual Studio
In the .gitignore file, duplicate all ignore paths of the project you want to rename with renamed versions of those paths.
Use the Git move command like this:
git mv <old_folder_name> <new_folder_name>
See documentation for additional options: https://git-scm.com/docs/git-mv
In your .sln file: Find the line defining your project and change the folder name in path. The line should look something like:
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "<Project name>", "<path-to-project>\<project>.csproj"
Open Visual Studio, and right click on project → Rename
Afterwards, rename the namespaces.
I read that ReSharper has some options for this. But simple find/replace did the job for me.
Remove old .gitignore paths.