If it is not so relevant and since you're dealing with one element which is #elem
, you can change its id to something else and style it as you wish...
$('#elem').attr('id', 'cheaterId');
And in your CSS:
#cheaterId { width: 100px;}
Try this:
<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
$data = array_map("utf8_encode", $data); //added
$num = count ($data);
for ($c=0; $c < $num; $c++) {
// output data
echo "<td>$data[$c]</td>";
}
echo "</tr><tr>";
}
?>
If you know the maximum index in you object you can do the following:
var myObj = {_x000D_
1: ['c', 'd'],_x000D_
2: ['a', 'b']_x000D_
},_x000D_
myArr;_x000D_
_x000D_
myObj.length = 3; //max index + 1_x000D_
myArr = Array.prototype.slice.apply(myObj);_x000D_
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
_x000D_
Before going to answer read this Documentation once. Then you clearly understand the answer.
Try this It may work for you.
Object.keys(data.shareInfo[i]).length
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
I just wanted to mention that if speed is required, wrapping unutbu's code in scipy's weave.inline and passing an already existing matrix as a parameter yields a 20-fold decrease in the running time.
The code (in rotation_matrix_test.py):
import numpy as np
import timeit
from math import cos, sin, sqrt
import numpy.random as nr
from scipy import weave
def rotation_matrix_weave(axis, theta, mat = None):
if mat == None:
mat = np.eye(3,3)
support = "#include <math.h>"
code = """
double x = sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
double a = cos(theta / 2.0);
double b = -(axis[0] / x) * sin(theta / 2.0);
double c = -(axis[1] / x) * sin(theta / 2.0);
double d = -(axis[2] / x) * sin(theta / 2.0);
mat[0] = a*a + b*b - c*c - d*d;
mat[1] = 2 * (b*c - a*d);
mat[2] = 2 * (b*d + a*c);
mat[3*1 + 0] = 2*(b*c+a*d);
mat[3*1 + 1] = a*a+c*c-b*b-d*d;
mat[3*1 + 2] = 2*(c*d-a*b);
mat[3*2 + 0] = 2*(b*d-a*c);
mat[3*2 + 1] = 2*(c*d+a*b);
mat[3*2 + 2] = a*a+d*d-b*b-c*c;
"""
weave.inline(code, ['axis', 'theta', 'mat'], support_code = support, libraries = ['m'])
return mat
def rotation_matrix_numpy(axis, theta):
mat = np.eye(3,3)
axis = axis/sqrt(np.dot(axis, axis))
a = cos(theta/2.)
b, c, d = -axis*sin(theta/2.)
return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
[2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
[2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])
The timing:
>>> import timeit
>>>
>>> setup = """
... import numpy as np
... import numpy.random as nr
...
... from rotation_matrix_test import rotation_matrix_weave
... from rotation_matrix_test import rotation_matrix_numpy
...
... mat1 = np.eye(3,3)
... theta = nr.random()
... axis = nr.random(3)
... """
>>>
>>> timeit.repeat("rotation_matrix_weave(axis, theta, mat1)", setup=setup, number=100000)
[0.36641597747802734, 0.34883809089660645, 0.3459300994873047]
>>> timeit.repeat("rotation_matrix_numpy(axis, theta)", setup=setup, number=100000)
[7.180983066558838, 7.172032117843628, 7.180462837219238]
I have tried using http://ipinfo.io and this JSON API works perfectly. First, you need to add the below mentioned namespaces:
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;
For localhost it will give dummy data as AU
. You can try hardcoding your IP and get results:
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string VisitorsIPAddr = string.Empty;
//Users IP Address.
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
//To get the IP address of the machine and not the proxy
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;`enter code here`
}
string res = "http://ipinfo.io/" + VisitorsIPAddr + "/city";
string ipResponse = IPRequestHelper(res);
}
public string IPRequestHelper(string url)
{
string checkURL = url;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
string responseRead = responseStream.ReadToEnd();
responseRead = responseRead.Replace("\n", String.Empty);
responseStream.Close();
responseStream.Dispose();
return responseRead;
}
}
}
#pragma
is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.
The one I regularly use is #pragma pack(1)
where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.
Pity we don't have a #dogma
yet. That would be fun ;)
Sure you can:
Option Explicit
'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type
'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType
MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3
Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub
'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer
MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333
For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub
In addition to the keycodes supplied in other answers, there are also "usage IDs" used for key remapping in the newer APIs introduced in macOS Sierra:
Technical Note TN2450
Remapping Keys in macOS 10.12 Sierra
Under macOS Sierra 10.12, the mechanism for key remapping was changed. This Technical Note is for developers of key remapping software so that they can update their software to support macOS Sierra 10.12. We present 2 solutions for implementing key remapping functionality for macOS 10.12 in this Technical Note.
https://developer.apple.com/library/archive/technotes/tn2450/_index.html
Keyboard a and A - 0x04
Keyboard b and B - 0x05
Keyboard c and C - 0x06
Keyboard d and D - 0x07
Keyboard e and E - 0x08
...
Call it with subprocess
import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")
The error you are getting seems to be because there is no swap module on the server, you should install swap on the server then run the script again
There is no subquery needed with this statement, which is better written as
select u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
or
select u.*
from Users u inner join CompanyRolesToUsers c
on u.Id = c.UserId --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
That being said, in LINQ it would be
from u in Users
from c in CompanyRolesToUsers
where u.Id == c.UserId &&
u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
or
from u in Users
join c in CompanyRolesToUsers
on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is...
This should display 'Tue':
new SimpleDateFormat("EEE").format(new Date());
This should display 'Tuesday':
new SimpleDateFormat("EEEE").format(new Date());
This should display 'T':
new SimpleDateFormat("EEEEE").format(new Date());
So your specific example would be:
new SimpleDateFormat("yyyy-MM-EEE").format(new Date());
Sometimes you install Python on Windows and it doesn't configure the path correctly.
Make sure you enter [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
in PowerShell to configure it correctly.
You also have to either restart PowerShell or your whole computer to get it to really be fixed.
The below made sense for 2013. However, now, I would use the :not()
selector as described below.
CSS can be overwritten.
DEMO: http://jsfiddle.net/persianturtle/J4SUb/
Use this:
.parent {
padding: 50px;
border: 1px solid black;
}
.parent span {
position: absolute;
top: 200px;
padding: 30px;
border: 10px solid green;
}
.parent:hover span {
border: 10px solid red;
}
.parent span:hover {
border: 10px solid green;
}
_x000D_
<a class="parent">
Parent text
<span>Child text</span>
</a>
_x000D_
Create a new 640x480 image and fill it with purple (red+blue):
cv::Mat mat(480, 640, CV_8UC3, cv::Scalar(255,0,255));
Note:
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
Try using CSS.
body {
margin: 0 0 auto 0;
}
The order is clockwise from the top, so top right bottom left
.
In linux shell, many commands accept multiple parameters and therefore could be used with wild cards. So, for example if you want to move all files from folder A to folder B, you write:
mv A/* B
If you want to move all files with a certain "look" to it, you could do like this:
mv A/*.txt B
Which copies all files that are blablabla.txt to folder B
Star (*) can substitute any number of characters or letters while ? can substitute one. For example if you have many files in the shape file_number.ext and you want to move only the ones that have two digit numbers, you could use a command like this:
mv A/file_??.ext B
Or more complicated examples:
mv A/fi*_??.e* B
For files that look like fi<-something->_<-two characters->.e<-something->
Unlike many commands in shell that require -R to (for example) copy or remove subfolders, mv does that itself.
Remember that mv overwrites without asking (unless the files being overwritten are read only or you don't have permission) so make sure you don't lose anything in the process.
For your future information, if you have subfolders that you want to copy, you could use the -R option, saying you want to do the command recursively. So it would look something like this:
cp A/* B -R
By the way, all I said works with rm (remove, delete) and cp (copy) too and beware, because once you delete, there is no turning back! Avoid commands like rm * -R
unless you are sure what you are doing.
I know this is ages old, but upon searching for something similar this morning, and reading up on Atømix' response (as this is what we're aiming on achieving), I found this: http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div.
Just putting that there in case anyone else needs a solution. :)
A char
represents a character in Java (*). It is 2 bytes large (at least that's what the valid value range suggests).
That doesn't necessarily mean that every representation of a character is 2 bytes long. In fact many encodings only reserve 1 byte for every character (or use 1 byte for the most common characters).
When you call the String(byte[])
constructor you ask Java to convert the byte[]
to a String
using the platform default encoding. Since the platform default encoding is usually a 1-byte encoding such as ISO-8859-1 or a variable-length encoding such as UTF-8, it can easily convert that 1 byte to a single character.
If you run that code on a platform that uses UTF-16 (or UTF-32 or UCS-2 or UCS-4 or ...) as the platform default encoding, then you will not get a valid result (you'll get a String
containing the Unicode Replacement Character instead).
That's one of the reasons why you should not depend on the platform default encoding: when converting between byte[]
and char[]
/String
or between InputStream
and Reader
or between OutputStream
and Writer
, you should always specify which encoding you want to use. If you don't, then your code will be platform-dependent.
(*) that's not entirely true: a char
represents a UTF-16 codepoint. Either one or two UTF-16 codepoints represent a Unicode codepoint. A Unicode codepoint usually represents a character, but sometimes multiple Unicode codepoints are used to make up a single character. But the approximation above is close enough to discuss the topic at hand.
SELECT field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) AS TBL
ORDER BY TBL.field1
(use ALIAS)
Here's what you can do:
return View("another view name", anotherviewmodel);
String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
StringTokenizer st = new StringTokenizer(s, "|");
String community = st.nextToken();
String helpDesk = st.nextToken();
String localEmbassy = st.nextToken();
String referenceDesk = st.nextToken();
String siteNews = st.nextToken();
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
PostgreSQL supports windowing functions as defined by the SQL standard, but they're awkward, so most people use (the non-standard) LIMIT
/ OFFSET
:
SELECT
*
FROM
mytable
ORDER BY
somefield
LIMIT 1 OFFSET 20;
This example selects the 21st row. OFFSET 20
is telling Postgres to skip the first 20 records. If you don't specify an ORDER BY
clause, there's no guarantee which record you will get back, which is rarely useful.
For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.
$s = '1234.13';
$double = bcadd($s,'0',2);
How about like this
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
return HiddenFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
return htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
}
Use it like this
@Html.HiddenFor(customerId => reviewModel.CustomerId, Site.LoggedInCustomerId, null)
MonoDevelop from: http://monodevelop.com/
There is no equivalent to Visual Studio. However, for writing C# on Mac or Linux, you can't get better than MonoDevelop.
The Mac build is pre beta. From the MonoDevelop site on Mac:
The Mac OS X port of MonoDevelop is under active development and has not seen a stable release yet. Recent work described by Michael Hutchinson has focussed on improving the usability and stability of Monodevelop on the Mac. This work will be released in MonoDevelop 2.2. Right now it's not finished, and is very much an alpha.
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
'Push' is for arrays.
You can do something like this:
app.js:
(function() {
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', function($scope) {
$scope.myText = "Let's go";
$scope.arrayText = [
'Hello',
'world'
];
$scope.addText = function() {
$scope.arrayText.push(this.myText);
}
}]);
})();
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
<form ng-controller="myController" ng-submit="addText()">
<input type="text" ng-model="myText" value="Lets go">
<input type="submit" id="submit"/>
<pre>list={{arrayText}}</pre>
</form>
</div>
</body>
</html>
It will look like this
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
If you are using jQuery you can use $('#mydiv').append('html content')
and it will keep the existing content.
Use JSON.
In the following example $php_variable
can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..)
like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);
You need to use Concat operation
Here's a typical simple example in the Unity milieu
using UnityEngine;
public class Launch : MonoBehaviour
{
void Start()
{
Debug.Log("today " + System.DateTime.Now.ToString("MM/dd/yyyy"));
// don't allow the app to be run after June 10th
System.DateTime lastDay = new System.DateTime(2020, 6, 10);
System.DateTime today = System.DateTime.Now;
if (lastDay < today) {
Debug.Log("quit the app");
Application.Quit();
}
UnityEngine.SceneManagement.SceneManager.LoadScene("Welcome");
}
}
If you do "git status" while having a merge conflict, the first thing git shows you is how to abort the merge.
char p[3] = "hello"
? should be char p[6] = "hello"
remember there is a '\0' char in the end of a "string" in C.
anyway, array in C is just a pointer to the first object of an adjust objects in the memory. the only different s are in semantics. while you can change the value of a pointer to point to a different location in the memory an array, after created, will always point to the same location.
also when using array the "new" and "delete" is automatically done for you.
you can also use this code...
datePicker = (DatePicker) findViewById(R.id.schedule_datePicker);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy");
Date d = new Date(year, month, day);
String strDate = dateFormatter.format(d);
I have fixed the error.
Follow the steps:
Configure Control Panel : a. Control Panel b. Administrator Tools c. Data Source (ODBC)
right click on it change the target to \sysWOW64\odbcad32.exe
change the start in to r%\SysWOW64
Execute it and Best Luck. Works in windows 7 as well as 8
Remove Newer version of MS-Office and install only MS-Office 2007 if problem still persists
Six years on, this is still at the top for some searches. Things have changed a lot since then. Now the defacto standard is more or less to use Volley and the NetworkImageView which takes care of the heavy lifting for you.
Assuming that you already have your Apaters, Loaders and ListFragments setup properly, this official google tutorial explains how to use NetworkImageView to load the images. Images are automatically loaded in a background thread and the view updated on the UI thread. It even supports caching.
const isEmpty = (value) => (
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0)
)
module.exports = isEmpty;
You could just put the letter X in the HTML inside the div and then style it with css.
See JSFiddle: http://jsfiddle.net/uSwbN/
HTML:
<div id="orangeBox">
<span id="x">X</span>
</div>
CSS:
#orangeBox {
background: #f90;
color: #fff;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 2em;
font-weight: bold;
text-align: center;
width: 40px;
height: 40px;
border-radius: 5px;
}
This worked for me:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&])([a-zA-Z0-9@$!%*?&]{8,})$
In your INSERT statements:
INSERT INTO employee(hans,germany) values(?,?)
You've got your values where your field names belong. Change it to be:
INSERT INTO employee(emp_name,emp_address) values(?,?)
If you were to run that statement from a SQL prompt, it would look like this:
INSERT INTO employee(emp_name,emp_address) values('hans','germany');
Note that you'd need to put single quotes around the string/varchar values.
Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();
Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.
This test shows that the string in VBA can be at least 10^8 characters long. But if you change it to 10^9 you will fail.
Sub TestForStringLengthVBA()
Dim text As String
text = Space(10 ^ 8) & "Hello world"
Debug.Print Len(text)
text = Right(text, 5)
Debug.Print text
End Sub
So do not be mislead by Intermediate window editor or MsgBox output.
I had a similar issue to this. My error needs to be an instanceof
both Error
and NotImplemented
, and it also needs to produce a coherent backtrace in the console.
My solution:
var NotImplemented = (function() {
var NotImplemented, err;
NotImplemented = (function() {
function NotImplemented(message) {
var err;
err = new Error(message);
err.name = "NotImplemented";
this.message = err.message;
if (err.stack) this.stack = err.stack;
}
return NotImplemented;
})();
err = new Error();
err.name = "NotImplemented";
NotImplemented.prototype = err;
return NotImplemented;
}).call(this);
// TEST:
console.log("instanceof Error: " + (new NotImplemented() instanceof Error));
console.log("instanceof NotImplemented: " + (new NotImplemented() instanceofNotImplemented));
console.log("message: "+(new NotImplemented('I was too busy').message));
throw new NotImplemented("just didn't feel like it");
Result of running with node.js:
instanceof Error: true
instanceof NotImplemented: true
message: I was too busy
/private/tmp/t.js:24
throw new NotImplemented("just didn't feel like it");
^
NotImplemented: just didn't feel like it
at Error.NotImplemented (/Users/colin/projects/gems/jax/t.js:6:13)
at Object.<anonymous> (/Users/colin/projects/gems/jax/t.js:24:7)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:487:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
The error passes all 3 of my criteria, and although the stack
property is nonstandard, it is supported in most newer browsers which is acceptable in my case.
If you are converting a varchar to int make sure you do not have decimal places.
For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.
CONVERT(int, replace(FIELD_NAME,'.0',''))
Mind you that this is a highly opinion based question, so I stopped making fjords and made a quick table
Now library comparison is hard because on many parameters, all the four pretty much do the same thing, except possibly for Fresco because there is a whole bunch of new memory level optimizations in it.So let me know if certain parameters you'd like to see a comparison for based on my experience.
Having used Fresco the least, the answer might evolve as I continue to use and understand it for current exploits. The used personally
is having used the library atleast once in a completed app.
*Note - Fresco now supports GIF as well as WebP animations
Your dot is matching all characters. Escape it (and the other special characters), like this:
preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);
You can use triggers.
Also check this introduction guide to triggers.
You need to tell scp
where to send the file. In your command that is not working:
scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~
You have not mentioned a remote server. scp
uses :
to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c
from the host C
to your local home directory.
The correct upload command, based on your comments, should be something like:
C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:
If you are running the command from your home directory, you can use a relative path:
C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:
You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:
C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/
if($('#leftmenu').val() == "") {
// statement
}
The script manager must be put onto the page before it is used. This would be directly on the page itself, or alternatively, if you are using them, on the Master Page.
The markup would be;
<asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"
EnablePartialRendering="true" />
jasonmp85 is right about passing a different array to String.format
. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.
Object newArgs = new Object[args.length+1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = extraVar;
String.format(format, extraVar, args);
based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200
works centered like that:
.imageContainer {
height: 100px;
overflow: hidden;
position: relative;
}
.imageCenter {
width: auto;
position: absolute;
left: -10%;
top: 0;
margin-left: -500px;
}
.imageCenter img {
display: block;
margin: 0 auto;
}
I Hope this helps others to finish faster the task :)
Using HTML5 mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base>
tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application. For more information, see AngularJS Developer Guide - Using $location HTML5 mode Server Side.
When you have html5Mode enabled, the #
character will no longer be used in your urls. The #
symbol is useful because it requires no server side configuration. Without #
, the url looks much nicer, but it also requires server side rewrites. Here are some examples:
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
server {
server_name my-app;
index index.html;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
app.listen(3006); //the port you want to use
See also
Does this work without alternation?
^((part)1(, \22)?)?(part2)?$
or why not this?
^((part)1(, (\22))?)?(\4)?$
The first works for all conditions the second for all but part2
(using GNU sed 4.1.5)
If you're just checking before trying to add a new value, use the ContainsKey
method:
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
}
If you're checking that the value exists, use the TryGetValue
method as described in Jon Skeet's answer.
Update using NuGet Package Manager
Console in your Visual Studio
Update-Package -reinstall Microsoft.AspNet.Mvc
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
We have it so the first click selects all, and another click goes to cursor (our application is designed for use on tablets with pens).
You might find it useful.
public class ClickSelectTextBox : TextBox
{
public ClickSelectTextBox()
{
AddHandler(PreviewMouseLeftButtonDownEvent,
new MouseButtonEventHandler(SelectivelyIgnoreMouseButton), true);
AddHandler(GotKeyboardFocusEvent,
new RoutedEventHandler(SelectAllText), true);
AddHandler(MouseDoubleClickEvent,
new RoutedEventHandler(SelectAllText), true);
}
private static void SelectivelyIgnoreMouseButton(object sender,
MouseButtonEventArgs e)
{
// Find the TextBox
DependencyObject parent = e.OriginalSource as UIElement;
while (parent != null && !(parent is TextBox))
parent = VisualTreeHelper.GetParent(parent);
if (parent != null)
{
var textBox = (TextBox)parent;
if (!textBox.IsKeyboardFocusWithin)
{
// If the text box is not yet focussed, give it the focus and
// stop further processing of this click event.
textBox.Focus();
e.Handled = true;
}
}
}
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
}
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw
always interrupt the execution flow of the current method. a try
/catch
block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.
Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/
Here's another suggestion:
public interface Service<T> {
T execute();
}
using this simple interface you can pass arguments via constructor in the concrete service classes:
public class FooService implements Service<String> {
private final String input1;
private final int input2;
public FooService(String input1, int input2) {
this.input1 = input1;
this.input2 = input2;
}
@Override
public String execute() {
return String.format("'%s%d'", input1, input2);
}
}
Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's
SELECT distinct 1 products.id FROM products WHERE products.id = ?;
Hashing algorithms are usually cryptographic in nature, but the principal difference is that encryption is reversible through decryption, and hashing is not.
An encryption function typically takes input and produces encrypted output that is the same, or slightly larger size.
A hashing function takes input and produces a typically smaller output, typically of a fixed size as well.
While it isn't possible to take a hashed result and "dehash" it to get back the original input, you can typically brute-force your way to something that produces the same hash.
In other words, if a authentication scheme takes a password, hashes it, and compares it to a hashed version of the requires password, it might not be required that you actually know the original password, only its hash, and you can brute-force your way to something that will match, even if it's a different password.
Hashing functions are typically created to minimize the chance of collisions and make it hard to just calculate something that will produce the same hash as something else.
How do time zones factor in this analysis. Does a card expire in New York before California? Does it depend on the billing or shipping addresses?
That will almost work.
When pushing to a non-default branch, you need to specify the source ref and the target ref:
git push origin branch1:branch2
Or
git push <remote> <branch with new changes>:<branch you are pushing to>
Don't know why @Janos deleted his answer, but it's correct: your data frame Train
doesn't have a column named pre
. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train
has columns called residual.sugar
, total.sulfur
, alcohol
and quality
. You need to change either your formula or your data frame so they're consistent with each other.
And just to clarify: Pre
is an object containing a formula. That formula contains a reference to the variable pre
. It's the latter that has to be consistent with the data frame.
If you want to do this in jQuery instead of CSS, you basically follow the same process.
Assuming you have some <div id="target"></div>
, you can use the following code:
$("#target").hover(function() {
$(this).css('cursor','pointer');
}, function() {
$(this).css('cursor','auto');
});
and that should do it.
The following works:
sudo apt-get --purge remove mysql-client mysql-server mysql-common
sudo apt-get autoremove
From the Documentation
As with components, you can add as many directive property bindings as you need by stringing them along in the template.
Add an input property to
HighlightDirective
calleddefaultColor
:@Input() defaultColor: string;
Markup
<p [myHighlight]="color" defaultColor="violet"> Highlight me too! </p>
Angular knows that the
defaultColor
binding belongs to theHighlightDirective
because you made it public with the@Input
decorator.Either way, the
@Input
decorator tells Angular that this property is public and available for binding by a parent component. Without@Input
, Angular refuses to bind to the property.
For your example
With many parameters
Add properties into the Directive
class with @Input()
decorator
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('first') f;
@Input('second') s;
...
}
And in the template pass bound properties to your li
element
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[first]='YourParameterHere'
[second]='YourParameterHere'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
Here on the li
element we have a directive with name selectable
. In the selectable
we have two @Input()
's, f
with name first
and s
with name second
. We have applied these two on the li
properties with name [first]
and [second]
. And our directive will find these properties on that li
element, which are set for him with @Input()
decorator. So selectable
, [first]
and [second]
will be bound to every directive on li
, which has property with these names.
With single parameter
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('params') params;
...
}
Markup
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
The best answer here is too long. I cannot comment so I added my answer.
This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();
I use this - it never fails:
startingpoint = 'blah'
if sys.argv[1:]:
startingpoint = sys.argv[1]
In case this is of use to some newer dev's because its not specified above. Just to be very explicit:
You need two things if using onConfigurationChanged:
An onConfigurationChanged
method in your Activity Class
Specify in your manifest which configuration changes will be handled by your onConfigurationChanged
method
The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
In the above manifest entry, there are various Android actions for android:configChanges=""
which can trigger the onCreate in your Activity lifecycle.
This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged
method in your Activity Class.
So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.
<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>
Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.
Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged
is not working. You must put all relevant ones into your manifest.
I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize
. So test on a selection of platforms.
<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>
So my suggestion, although I'm sure someone can poke holes in this:
Add your onConfigurationChanged
method in your Activity Class with a TOAST or LOG so you can see when its working.
Add all possible configuration options to your manifest.
Confirm your onConfigurationChanged
method is working by testing your app.
Remove each config option from your manifest file one at a time, testing your app after each.
Test on as large a variety of devices as possible.
Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.
I hope this saves someone some time.
My onConfigurationChanged
method just for info below. onConfigurationChanged
is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if
to check the orientation works correctly, and then the 2nd nested if
to look at the visibility of my UI ImageView also works correctly.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
}
}
NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.
NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];
You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.
Have a read of these articles:
I don't know MSSQL but would it not be:
alter table company drop **constraint** Company_CountryID_FK;
The answer is correct, but you don't need to declare a variable. A string can contain your character:
"This string contains omega, that looks like this: \u03A9"
Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.
You could add the default rule with the alter table,
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
then immediately set to null all the current existing rows:
UPDATE mytable SET created_at = NULL
Then from this point on the DEFAULT
will take effect.
In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.
It seems strange that you would write arrays without commas (is that a MATLAB syntax?)
Have you tried going through NumPy's documentation on multi-dimensional arrays?
It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:
>>> p = np.array([[1,2],[3,4]])
>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)
>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])
It has also been answered already...
From the documentation for MATLAB users:
You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:
mat("1 2 3; 4 5 6")
or
matrix("[1 2 3; 4 5 6]")
Please give it a try and tell me how it goes.
Gradle is actually included with Android Studio (at least on the Mac OS X version.) I had to point it to the installed location, inside the Android Studio application "package contents" (can view by control/right-clicking on the application icon.)
Ruby's just the same, btw, offering both #length
and #size
as synonyms for the number of items in arrays and hashes (C++ only does it for strings).
Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).
Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:
^[a-zA-Z ._-]*$
If you use the case-insensitive modifier, you can shorten this to
^[a-z ._-]*$
Note that the space is significant (it is just a character like any other).
I had an issue where I was pushing to my remote repo from a local repo that didn't match up with history of remote. This is what worked for me.
I cloned my repo locally so I knew I was working with fresh copy of repo:
git clone Your_REPO_URL_HERE.git
Switch to the branch you are trying to get into the remote:
git checkout Your_BRANCH_NAME_HERE
Add the remote of the original:
git remote add upstream Your_REMOTE_REPO_URL_HERE.git
Do a git fetch and git pull:
git fetch --all
git pull upstream Your_BRANCH_NAME_HERE
If you have merge conflicts, resolve them with
git mergetool kdiff3
or other merge tool of your choice.
Once conflicts are resolved and saved. Commit and push changes.
Now go to the gitub.com repo of the original and attempt to create a pull request. You should have option to create pull request and not see the "Nothing to compare, branches are entirely different commit histories" Note: You may need to choose compare across forks for your pull request.
My case was different. I'm hosting a site behind a firewall. The error was caused by pfSense.
Network layout: |Web Server 10.x.x.x| <-> |pfSense 49.x.x.x| <-> |Open Internet|
I accidentally found the cause, thanks to this answer.
All is well when I accessed my site from WAN.
However, when the site was accessed from inside LAN (e.g. when Wordpress made a curl
request to its own server, despite using the WAN IP 49.x.x.x
), it was served the pfSense login page.
I identified the certificate as pfSense webConfigurator Self-Signed Certificate
. No wonder curl
threw an error.
Cause: What happened was that curl
was using the site's WAN IP address 49.x.x.x
. But, in the context of the web server, the WAN IP was the firewall.
Debug: I found that I was getting the pfSense certificate.
Solution: On the server hosting the site, point its own domain name to 127.0.0.1
By applying the solution, curl
's request was properly handled by the web server, and not forwarded to the firewall which responded by sending the login page.
<import resource="classpath*:spring-config.xml" />
This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.
You can use the build in classes sun.misc.Base64Decoder and sun.misc.Base64Encoder to convert the binary data of the serialize to a string. You das not need additional classes because it are build in.
if(checkBox.getAttribute("checked") != null) // if Checked
checkBox.click(); //to Uncheck it
You can also add an and
statement to be sure if checked is true.
Try this it works
<ul class="sub-menu" type="none">
<li class="sub-menu-list" ng-repeat="menu in list.components">
<a class="sub-menu-link">
{{ menu.component }}
</a>
</li>
</ul>
if (set no count== off)
{ then it will keep data of how many records affected so reduce performance } else { it will not track the record of changes hence improve perfomace } }
There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.
If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.
Check for missing folders that are required by the server, in my case it was UPLOADS folder in programData which was deleted by empty folder cleaner utility that I used earlier.
How did I find out:
run the server config file my.ini(in my case it was in programData) as the defaults-file param for mysqld (don't forget to use --console option to view error log on screen) 'mysqld --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" --console'
Error:
mysqld: Can't read dir of 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\' (OS errno 2 - No such file or directory)
Solution:
Once I manually created the Uploads folder the server started successfully.
Working syntax for multiple optional params:
<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />
Now, url can be:
You can use:
GLfloat coordinates[8] = {1.0f, ..., 0.0f};
but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).
The other two ways that spring to mind are to blat the contents if they're fixed:
GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));
or provide a function that looks like your initialisation code anyway:
void setCoords (float *p0, float p1, ..., float p8) {
p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);
keeping in mind those ellipses (...
) are placeholders, not things to literally insert in the code.
If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.
To prevent the dialog from being dismissed automatically you have to set the OnClickListener
after the ProgressDialog
is shown, like so:
connectingDialog = new ProgressDialog(this);
connectingDialog.setCancelable(false);
connectingDialog.setCanceledOnTouchOutside(false);
// Create the button but set the listener to a null object.
connectingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
(DialogInterface.OnClickListener) null )
// Show the dialog so we can then get the button from the view.
connectingDialog.show();
// Get the button from the view.
Button dialogButton = connectingDialog.getButton( DialogInterface.BUTTON_NEGATIVE);
// Set the onClickListener here, in the view.
dialogButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick ( View v ) {
// Dialog will not get dismissed until you call dismiss() explicitly.
}
});
You could use the Count method
var count = mystring.Count(x => x == '$')
Try this (its work in Chrome, Firefox and IE):
... content in page 1 ...
<p style="page-break-after: always;"> </p>
<p style="page-break-before: always;"> </p>
... content in page 2 ...
UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.
In Cygwin:
$cmp -bl <file1> <file2>
diffs binary offsets and values are in decimal and octal respectively.. Vladi.
On debian where bsd-mailx
is installed by default, the -r
option does not work. However you can use mailx -s subject [email protected] -- -f [email protected]
instead. According to man page, you can specify sendmail options after --
.
If you'd like to get a graphical, searchable representation of the dependency tree (including all modules from your project, transitive dependencies and eviction information), check out UpdateImpact: https://app.updateimpact.com (free service).
Disclaimer: I'm one of the developers of the site
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CoursesComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
The case class construct in Scala can also be seen as a convenience to remove some boilerplate.
When constructing a case class Scala gives you the following.
apply
method that you are able to use as a factory method. You get the syntactic sugar advantage of not having to use the new keyword.
Because the class is immutable you get accessors, which are just the variables (or properties) of the class but no mutators (so no ability to change the variables). The constructor parameters are automatically available to you as public read only fields. Much nicer to use than Java bean construct.
hashCode
, equals
, and toString
methods by default and the equals
method compares an object structurally. A copy
method is generated to be able to clone an object (with some fields having new values provided to the method). The biggest advantage as has been mentioned previously is the fact that you can pattern match on case classes. The reason for this is because you get the unapply
method which lets you deconstruct a case class to extract its fields.
In essence what you are getting from Scala when creating a case class (or a case object if your class takes no arguments) is a singleton object which serves the purpose as a factory and as an extractor .
I think the following way you can do it,
typedef struct
{
int flag : 3;
} MyStruct;
To skip the test case during maven clean install i used -DskipTests paramater in following command
mvn clean install -DskipTests
into terminal window
ianhanniballake is right. You can get all the functionality of Activity
from FragmentActivity
. In fact, FragmentActivity
has more functionality.
Using FragmentActivity
you can easily build tab and swap
format. For each tab you can use different Fragment
(Fragments
are reusable). So for any FragmentActivity
you can reuse the same Fragment
.
Still you can use Activity
for single pages like list down something and edit element of the list in next page.
Also remember to use Activity
if you are using android.app.Fragment
; use FragmentActivity
if you are using android.support.v4.app.Fragment
. Never attach a android.support.v4.app.Fragment
to an android.app.Activity
, as this will cause an exception to be thrown.
Based on Charles Clayton's answer, but slightly simplified...
' add item to array
Sub ArrayAdd(arr, val)
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = val
End Sub
Used like so
a = Array()
AddItem(a, 5)
AddItem(a, "foo")
For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)
Multiples of 5 or x can be done simply by dividing before and multiplying after the round.
If you want to round and keep decimal places, Math.round(n, d) would work.
Omit the where
clause:
update mytable set
column1 = value1,
column2 = value2,
-- other column values etc
;
This will give all rows the same values.
This might not be what you want - consider truncate
then a mass insert
:
truncate mytable; -- delete all rows efficiently
insert into mytable (column1, column2, ...) values
(row1value1, row1value2, ...), -- row 1
(row2value1, row2value2, ...), -- row 2
-- etc
;
Are you looking for the root folder of the application? Then I would use
String path = getClass().getClassLoader().getResource(".").getPath();
to actually "find out where I am".
'nunique' is an option for .agg() since pandas 0.20.0, so:
df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.
Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).
When you do spam = "green"
, you have bound the name spam
to the string object "green"
; if you then do eggs = spam
you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs
, to the same object ("green"
in this case). If you then bind spam
to something else (spam = 3.14159
) eggs
will still be bound to "green"
.
When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).
With for-loops utilizing lists, there are two basic ways to assign back to the list:
for i, item in enumerate(some_list):
some_list[i] = process(item)
or
new_list = []
for item in some_list:
new_list.append(process(item))
some_list[:] = new_list
Notice the [:]
on that last some_list
-- it is causing a mutation of some_list
's elements (setting the entire thing to new_list
's elements) instead of rebinding the name some_list
to new_list
. Is this important? It depends! If you have other names besides some_list
bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list
.
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
step-1) On Notepad++ Toolbar:
Plugins -> Plugin Manager -> Show Plugin Manager -> Available . Then select the Explorer. And click Install.
(Note: As in above comments some people like SherloXplorer. Pls, note that this requires .Net v2 )
step-2) Again on Notepad++ Toolbar:
Explorer->Explorer
Now you can view files with tree view.
Update: After adding Explorer, right click to edit a file in Notepad++ may stop working. To make it work again, restart Notepad++ afresh.
Just in case you're using xcode beta:
sudo xcode-select -s /Applications/Xcode-Beta.app/Contents/Developer
You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:
{ cat notify-finished | while read line; do
read -u 3 input
echo "$input"
done; } 3<&0
BTW, if you really are using cat
this way, replace it with a redirect and things become even easier:
while read line; do
read -u 3 input
echo "$input"
done 3<&0 <notify-finished
Or, you can swap stdin and unit 3 in that version -- read the file with unit 3, and just leave stdin alone:
while read line <&3; do
# read & use stdin normally inside the loop
read input
echo "$input"
done 3<notify-finished
there are 6 ways to do this in React,
number 1 and 2 and 3 are the best:
1-config CORS in the Server-Side
2-set headers manually like this:
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
3-config NGINX for proxy_pass which is explained here.
4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)
5-bypass the cross-origin-policy with URL bellow(only for development)
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
6-use proxy
in your package.json
file:(only for development)
if this is your API: http://45.456.200.5:7000/api/profile/
add this part in your package.json
file:
"proxy": "http://45.456.200.5:7000/",
and then make your request with the next parts of the api:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
*first html page*
<form action="display.jsp" >
<input type="text" name="serialNumber" />
<input type="submit" value="Submit" />
</form>
*Second html page*
<body>
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>
</body>
you will get the value of the textbox on another page.
Assume that you need to launch ps script from shared folder
copy \\\server\script.ps1 c:\tmp.ps1 /y && PowerShell.exe -ExecutionPolicy Bypass -File c:\tmp.ps1 && del /f c:\tmp.ps1
P.S. Reduce googling)
I am adding some of the important concern about ng directives:-
Check out the below example:-
<div ng-if="data.type == 'FirstValue' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'SecondValue' ">
//different template with story data
</div>
<div ng-if="data.type == 'ThirdValue' ">
//different template with article data
</div>
As per datatype it is going to render any one of the div.
Introduced in numpy 1.8:
Return a new array of given shape and type, filled with fill_value.
Examples:
>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf, inf],
[ inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
[10, 10]])
%run YourNotebookfile.ipynb is working fine;
if you want to import a specific module then just add the import command after the ipynb i.e YourNotebookfile.ipynb having def Add()
then you can just use it
%run YourNotebookfile.ipynb import Add
First click show all files. Then in the bin folder choose any xml file and then right click and by selecting 'browse with' select your desired browser.
just change the default folder for your R libraries in a directory with no Administrator rights, e.g.
.libPaths("C:/R/libs")
I don't know about javax.media.j3d, so I might be mistaken, but you usually want to investigate whether there is a memory leak. Well, as others note, if it was 64MB and you are doing something with 3d, maybe it's obviously too small...
But if I were you, I'll set up a profiler or visualvm, and let your application run for extended time (days, weeks...). Then look at the heap allocation history, and make sure it's not a memory leak.
If you use a profiler, like JProfiler or the one that comes with NetBeans IDE etc., you can see what object is being accumulating, and then track down what's going on.. Well, almost always something is incorrectly not removed from a collection...
Keep your code clean and stylesheets logically separated per screen 'media' type config...
1) Using himansu's answer from above as a reference: Common CSS Media Queries Break Points
AND
2) https://www.w3schools.com/css/css3_mediaqueries.asp
your answer would be:
<link rel="stylesheet" media="@media only screen and (min-width : 320px) and (max-width : 480px)" href="mobilePortrait.css">
<link rel="stylesheet" media="@media only screen and (min-width : 481px) and (max-width : 595px)" href="mobileLandscape.css">
Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)
You can use rake db:reset
when you want to drop the local database and start fresh with data loaded from db/seeds.rb
. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.
Once the reset command is used it will do the following:
Drop the database: rake db:drop
Load the schema: rake db:schema:load
Seed the data: rake db:seed
But if you want to completely drop your database you can use rake db:drop
. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.
This is a detailed article about the most important rake database commands.
The following also seems to work :
for (vector<int>::iterator it = res.begin(); it != res.end(); it++)
{
res.erase(it--);
}
Not sure if there's any flaw in this ?
No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()
) but it is not guaranteed to run.
First try increasing the memory by setting -Xmx256m
Try this:
.navbar {
position: relative;
}
.brand {
position: absolute;
left: 50%;
margin-left: -50px !important; /* 50% of your logo width */
display: block;
}
Centering your logo by 50% and minus half of your logo width so that it won't have problem when zooming in and out.
See fiddle
For .meta
files while using Unity3D, I found the best pattern for hiding is:
"files.exclude": {
"*/**/**.meta": true
}
This captures all folders and subfolders, and will pick up foo.cs.meta
in addition to foo.meta
The accepted answer is correct as asked, below answers the opposite question of developing Android on VS Code.
Extensions
Ultimately you can automate building and running your app on a device emulator by adding the function below to your $PATH
and running runDebugApp <module> <start activity>
from the integrated terminal:
# run android app
# usage runDebugApp [module] [fully qualified start activity com.package/com.package.MainActivity]
function runDebugApp(){
./gradlew -offline :"$1":installDebug && adb shell am start "$2" && adb logcat -d > logcat.log
}
OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.
OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.
But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.
So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).
The reference for the user-specific configuration for Maven is available on-line and it doesn't make much sense to share a settings.xml
with you since these settings are user specific.
If you need to configure a proxy, have a look at the section about Proxies.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> ... <proxies> <proxy> <id>myproxy</id> <active>true</active> <protocol>http</protocol> <host>proxy.somewhere.com</host> <port>8080</port> <username>proxyuser</username> <password>somepassword</password> <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts> </proxy> </proxies> ... </settings>
id
: The unique identifier for this proxy. This is used to differentiate between proxy elements.active
: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.protocol, host, port
: The protocol://host:port of the proxy, seperated into discrete elements.username, password
: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.nonProxyHosts
: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited - comma delimited is also common
There is no equivalent in VB.NET that I could find. For this piece of code you are probably going to want to open it in Reflector and change the output type to VB to get the exact copy of the code that you need. For instance when I put the following in to Reflector:
switch (args[0])
{
case "UserID":
Console.Write("UserID");
break;
case "PackageID":
Console.Write("PackageID");
break;
case "MVRType":
if (args[1] == "None")
Console.Write("None");
else
goto default;
break;
default:
Console.Write("Default");
break;
}
it gave me the following VB.NET output.
Dim CS$4$0000 As String = args(0)
If (Not CS$4$0000 Is Nothing) Then
If (CS$4$0000 = "UserID") Then
Console.Write("UserID")
Return
End If
If (CS$4$0000 = "PackageID") Then
Console.Write("PackageID")
Return
End If
If ((CS$4$0000 = "MVRType") AndAlso (args(1) = "None")) Then
Console.Write("None")
Return
End If
End If
Console.Write("Default")
As you can see you can accomplish the same switch case statement with If statements. Usually I don't recommend this because it makes it harder to understand, but VB.NET doesn't seem to support the same functionality, and using Reflector might be the best way to get the code you need to get it working with out a lot of pain.
Update:
Just confirmed you cannot do the exact same thing in VB.NET, but it does support some other useful things. Looks like the IF statement conversion is your best bet, or maybe some refactoring. Here is the definition for Select...Case
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
If you get the error after installation: Find the .lax file with the matching exe name and update current vm path from:
lax.nl.current.vm=C:\ProgramData\Oracle\Java\javapath\java.exe
to
lax.nl.current.vm=C:\Program Files\Java\jre1.8.0_144\bin\java.exe
You can use np.where()
to set values based on a specified condition:
#df
c1 c2 c3
0 4 2 1
1 8 7 9
2 1 5 8
3 3 3 5
4 3 6 8
Now change values (or set) in column ['c2']
based on your condition.
df['c2'] = np.where(df.c1 == 8,'X', df.c3)
c1 c3 c4
0 4 1 1
1 8 9 X
2 1 8 8
3 3 5 5
4 3 8 8
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
I use a (maybe) much simpler option of pdf2image:
cd $dir
for f in *.pdf
do
if [ -f "${f}" ]; then
n=$(echo "$f" | cut -f1 -d'.')
pdftoppm -scale-to 1440 -png $f $conv/$n
rm $f
mv $conv/*.png $dir
fi
done
This is a small part of a bash script in a loop for the use of a narrow casting device. Checks every 5 seconds on added pdf files (all) and processes them. This is for a demo device, at the end converting will be done at a remote server. Converting to .PNG now, but .JPG is possible too.
This converting, together with transitions on A4 format, displaying a video, two smooth scrolling texts and a logo (with transition in three versions) sets the Pi3 to allmost 4x 100% cpu-load ;-)
My utils function for get view location, it will return a Point
object with x value
and y value
public static Point getLocationOnScreen(View view){
int[] location = new int[2];
view.getLocationOnScreen(location);
return new Point(location[0], location[1]);
}
Using
Point viewALocation = getLocationOnScreen(viewA);
I hope this will be help you
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
Object obj2 =null;
ArrayList al1 = (ArrayList) obj2;
al1 = (ArrayList) obj2;
System.out.println("List2 Value: " + al1);
}
}
obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.
Had the same problem hosting Go Git Server behind nginx and cloning:
remote: Enumerating objects: 103, done. remote: Counting objects: 100% (103/103), done. remote: Compressing objects: 100% (47/47), done. remote: Total 103 (delta 52), reused 99 (delta 51), pack-reused 0 Receiving objects: 100% (103/103), 11.56 KiB | 1.16 MiB/s, done. Resolving deltas: 100% (52/52), done. error: RPC failed; curl 56 GnuTLS recv error (-110): The TLS connection was non-properly terminated.
After searching RPC based issues, there appears to he a requirement to use HTTP2
Therefore this line in my nginx site configuration:
listen 443 ssl; # managed by Certbot
Was changed to this, to enable http2 - which is not a default:
listen 443 ssl http2; # managed by Certbot
And TLS in general seems happier (i.e. I had other errors regarding curl and TLS, when inspecting verbose output)
I have verified this as a root cause by removing http2, which reproduces the error and reinstating http2 resolves the problem.
I've found that using OnTime
can be painful, particularly when:
This article by Chip Pearson was very illuminating. I prefer to use the Windows Timer now, instead of OnTime
.
There may be situations when df.reset_index()
cannot be used (e.g., when you need the index, too). In this case, use index.get_level_values()
to access index values directly:
df['Trial'] = df.index.get_level_values(0)
df['measurement'] = df.index.get_level_values(1)
This will assign index values to individual columns and keep the index.
See the docs for further info.
From: http://www.csharp-examples.net/string-format-datetime/
string.Format("{0:t tt}", datetime); // -> "P PM" or "A AM"
Most important
Keep in mind that relative URLs are resolved from the URL of your stylesheet.
So it will work if folder images
is inside the stylesheets
folder.
From you description you would need to change it to either
url("../images/plaid.jpg")
or
url("/images/plaid.jpg")
Additional 1
Also you cannot have no selector..
CSS is applied through selectors..
Additional 2
You should use either the shorthand background
to pass multiple values like this
background: url("../images/plaid.jpg") no-repeat;
or the verbose syntax of specifying each property on its own
background-image: url("../images/plaid.jpg");
background-repeat:no-repeat;
wait until this call is finish its executing
You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground
execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
To get result back in UI Thread start AsyncTask
as :
String str_result= new RunInBackGround().execute().get();
Changes to be committed: (use "git reset HEAD ..." to unstage)
If you want to get value from a mapped select input then you can refer to this example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fruit: "banana",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log("Fruit Selected!!");
this.setState({ fruit: e.target.value });
}
render() {
return (
<div id="App">
<div className="select-container">
<select value={this.state.fruit} onChange={this.handleChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div>
</div>
);
}
}
export default App;
Two ways I know of:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
Another Way is to get a observable as a localVariable.
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
Hope it helps
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
how is this
=((?:(?:(?:http)s?:)?\/\/)?(?:(?:[a-zA-Z0-9]+)\.?)*(?:(?:[a-zA-Z0-9]+))\.[a-zA-Z0-9]{2,3})
(you may want to add "\/" to end of pattern
if your goal is to rid url's passed in as a param you may add the equal sign as the first char, like:
=((?:(?:(?:http)s?:)?//)?(?:(?:[a-zA-Z0-9]+).?)*(?:(?:[a-zA-Z0-9]+)).[a-zA-Z0-9]{2,3}/)
and replace with "/"
The goal of this example to get rid of any domain name regardless of the form it appears in. (i.e. to ensure url parameters don't incldue domain names to avoid xss attack)
UPDATE - for an example of this working, I used this technique in the Carota editor.
Following on from ellisbben's answer, here is an enhanced version to get the ascent and descent from the baseline, i.e. same as tmAscent
and tmDescent
returned by Win32's GetTextMetric API. This is needed if you want to do a word-wrapped run of text with spans in different fonts/sizes.
The above image was generated on a canvas in Safari, red being the top line where the canvas was told to draw the text, green being the baseline and blue being the bottom (so red to blue is the full height).
Using jQuery for succinctness:
var getTextHeight = function(font) {
var text = $('<span>Hg</span>').css({ fontFamily: font });
var block = $('<div style="display: inline-block; width: 1px; height: 0px;"></div>');
var div = $('<div></div>');
div.append(text, block);
var body = $('body');
body.append(div);
try {
var result = {};
block.css({ verticalAlign: 'baseline' });
result.ascent = block.offset().top - text.offset().top;
block.css({ verticalAlign: 'bottom' });
result.height = block.offset().top - text.offset().top;
result.descent = result.height - result.ascent;
} finally {
div.remove();
}
return result;
};
In addition to a text element, I add a div with display: inline-block
so I can set its vertical-align
style, and then find out where the browser has put it.
So you get back an object with ascent
, descent
and height
(which is just ascent
+ descent
for convenience). To test it, it's worth having a function that draws a horizontal line:
var testLine = function(ctx, x, y, len, style) {
ctx.strokeStyle = style;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + len, y);
ctx.closePath();
ctx.stroke();
};
Then you can see how the text is positioned on the canvas relative to the top, baseline and bottom:
var font = '36pt Times';
var message = 'Big Text';
ctx.fillStyle = 'black';
ctx.textAlign = 'left';
ctx.textBaseline = 'top'; // important!
ctx.font = font;
ctx.fillText(message, x, y);
// Canvas can tell us the width
var w = ctx.measureText(message).width;
// New function gets the other info we need
var h = getTextHeight(font);
testLine(ctx, x, y, w, 'red');
testLine(ctx, x, y + h.ascent, w, 'green');
testLine(ctx, x, y + h.height, w, 'blue');
If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:
[HttpPost]
public JsonResult KeepSessionAlive() {
return new JsonResult {Data = "Success"};
}
, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):
var keepSessionAlive = false;
var keepSessionAliveUrl = null;
function SetupSessionUpdater(actionUrl) {
keepSessionAliveUrl = actionUrl;
var container = $("#body");
container.mousemove(function () { keepSessionAlive = true; });
container.keydown(function () { keepSessionAlive = true; });
CheckToKeepSessionAlive();
}
function CheckToKeepSessionAlive() {
setTimeout("KeepSessionAlive()", 5*60*1000);
}
function KeepSessionAlive() {
if (keepSessionAlive && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function () { keepSessionAlive = false; }
});
}
CheckToKeepSessionAlive();
}
, and initialize this functionality by calling a JavaScript function:
SetupSessionUpdater('/Home/KeepSessionAlive');
Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).
Update 07/07/2014 - The answer based on my answer, by Grim..., is a better solution as it improves on my solution below, so I'd suggest using that.
You can do this without listing all the columns with the following syntax:
CREATE TEMPORARY TABLE tmptable SELECT * FROM table WHERE primarykey = 1;
UPDATE tmptable SET primarykey = 2 WHERE primarykey = 1;
INSERT INTO table SELECT * FROM tmptable WHERE primarykey = 2;
You may decide to change the primary key in another way.
The problem with editing JavaScript like you can CSS and HTML is that there is no clean way to propagate the changes. JavaScript can modify the DOM, send Ajax requests, and dynamically modify existing objects and functions at runtime. So, once you have loaded a page with JavaScript, it might be completely different after the JavaScript has run. The browser would have to keep track of every modification your JavaScript code performs so that when you edit the JS, it rolls back the changes to a clean page.
But, you can modify JavaScript dynamically a few other ways:
javascript: alert (1);
The first two options are great because you can modify any JavaScript variables and functions currently in scope. However, you won't be able to modify the code and run it with a "just-served" page like you can with the third option.
Other than that, as far as I know, there is no edit-and-run JavaScript editor in the browser. Hope this helps,
If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html
I got the same issue here using Docker, I've tried every single step and didn't work well, always getting locale error, so I decided to use BABEL, and everything worked well.
An expression of non-boolean type specified in a context where a condition is expected
I also got this error when I forgot to add ON condition when specifying my join clause.
Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div>
tag first. then you have something to modify. if you load the js first then that function is looking your HTML
to do what you asked to do, but when that time your HTML
is loading and your function cant find the HTML
. So you can put the script in the bottom of the page. inside <body>
tag then the function can access the <div>
Because DOM is already loaded the time you hit the script.
Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.
Posting this answer here since I think this is the intended question
So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.
How to pull from the repo without using the credentials of the old user ?
You edit the .git/config file of your repo.
and change
url = https://<old-username>@github.com/abc/repo.git/
to
url = https://<new-username>@github.com/abc/repo.git/
After saving the changes, from now onwards git pull will pull data while using credentials of the new user.
I hope this helps anyone with a similar problem
I couldn't find how to specify the application tag either, but after a lot of Googling, it became obvious from the manifest file docs: use android:name, in addition to the default icon and label in the application stanza.
android:name The fully qualified name of an Application subclass implemented for the application. When the application process is started, this class is instantiated before any of the application's components.
The subclass is optional; most applications won't need one. In the absence of a subclass, Android uses an instance of the base Application class.
You're looking for UPDATE not insert.
UPDATE mytable
SET table_column = 'test';
UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).
Yes, it is possible. You will need to define 2 FKs for 3rd table. Each FK pointing to the required field(s) of one table (ie 1 FK per foreign table).
kill $(lsof -t -i :PORT_TO_KILL)
simplified version. Simple copy paste with the port to kill ex.5000
What is row?
Either of these could be correct.
1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.
var result=row.split('|');
alert(result[2]);
otherwise
2) Use this where $(row)
is a jQuery
object.
var result=$(row).val().split('|');
alert(result[2]);
[As mentioned in the other answer, you may have to use $(row).val()
or $(row).text()
or $(row).html()
etc. depending on what $(row) is.]
Convert it back to datetime after converting to date in order to keep same datatime if needed
select Convert(datetime, Convert(date, getdate()) )
If anyone wants to build a viewPager
with thumbnails as indicators, using this library could be an option:
ThumbIndicator for viewPager that works also with image links as resources.
var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:
ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then
ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
HTH, -ft
According to MDN, the
split()
method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.
var str = 'Hello my friend'
var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]
var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]
console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
I believe that, if you need to use the %20
variant, you could perhaps use rawurlencode()
.
It is most accurate to say that methods with a Bang! are the more dangerous or surprising version. There are many methods that mutate without a Bang such as .destroy
and in general methods only have bangs where a safer alternative exists in the core lib.
For instance, on Array we have .compact
and .compact!
, both methods mutate the array, but .compact!
returns nil instead of self if there are no nil's in the array, which is more surprising than just returning self.
The only non-mutating method I've found with a bang is Kernel
's .exit!
which is more surprising than .exit
because you cannot catch SystemExit
while the process is closing.
Rails and ActiveRecord continues this trend in that it uses bang for more 'surprising' effects like .create!
which raises errors on failure.
How about just using
void feedInputToOutput(InputStream in, OutputStream out) {
IOUtils.copy(in, out);
}
and be done with it?
from jakarta apache commons i/o library which is used by a huge amount of projects already so you probably already have the jar in your classpath already.
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
ADD
(docs)The ADD
command can accept as a <src>
parameter:
ADD folder /path/inside/your/container
or
tar -cvzf newArchive.tar.gz /path/to/your/folder
You would then add a line to your Dockerfile like this:
ADD /path/to/archive/newArchive.tar.gz /path/inside/your/container
Notes:
ADD
will automatically extract your archive.using jQuery:
$(function() {
function unifyHeights() {
var maxHeight = 0;
$('#container').children('#navigation, #content').each(function() {
var height = $(this).outerHeight();
// alert(height);
if ( height > maxHeight ) {
maxHeight = height;
}
});
$('#navigation, #content').css('height', maxHeight);
}
unifyHeights();
});
Acked Unseen sample
Hi guys! Just some observations from what I just found in my capture:
On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client
Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC
In the capture example above, frame 67795 sends an ACK for 10384
Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194
Here is my implementation for python 3 and pycrypto
from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())
x = key.encrypt(b"dddddd",32)
print(x)
z = key1.decrypt(x)
print(z)
Be careful with the select()
function, because it's used both in the dplyr and MASS packages, so if MASS is loaded, select() may not work properly. To find out what packages are loaded, type sessionInfo()
and look for it in the "other attached packages:" section. If it is loaded, type detach( "package:MASS", unload = TRUE )
, and your select()
function should work again.
In my case I didnt need to disable it , rather I had to put this code on top of my class : (and this solved my issue)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)//this is what was added
@Value //this was there already
@Builder//this was there already
public class NameOfClass {
//some code in here.
}
Assuming you were in your own topic branch. If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2).
git checkout -b temp_branch HEAD~2
Then squash commit the other branch in this new branch:
git merge branch_with_two_commits --squash
That will bring in the changes but not commit them. So just commit them and you're done.
git commit -m "my message"
Now you can merge this new topic branch back into your main branch.
It is because Ajax is asynchronous, the success
or the error
function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
successmessage = 'Data was succesfully captured';
$("label#successmessage").text(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("label#successmessage").text(successmessage);
},
});
$(":input").val('');
return false;
Here's some options that keep the file self-contained without retastering the image:
div
tags<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
Instance methods are defined inside a class definition block. Class methods are defined as singleton methods on the singleton class of a class, also informally known as the "metaclass" or "eigenclass". private
is not a keyword, but a method (Module#private).
This is a call to method self#private
/A#private
which "toggles" private access on for all forthcoming instance method definitions until toggled otherwise:
class A
private
def instance_method_1; end
def instance_method_2; end
# .. and so forth
end
As noted earlier, class methods are really singleton methods defined on the singleton class.
def A.class_method; end
Or using a special syntax to open the definition body of the anonymous, singleton class of A:
class << A
def class_method; end
end
The receiver of the "message private" - self - inside class A
is the class object A. self inside the class << A
block is another object, the singleton class.
The following example is in reality calling two different methods called private, using two different recipients or targets for the call. In the first part, we define a private instance method ("on class A"), in the latter we define a private class method (is in fact a singleton method on the singleton class object of A).
class A
# self is A and private call "A.private()"
private def instance_method; end
class << self
# self is A's singleton class and private call "A.singleton_class.private()"
private def class_method; end
end
end
Now, rewrite this example a bit:
class A
private
def self.class_method; end
end
Can you see the mistake [that Ruby language designers] made? You toggle on private access for all forthcoming instance methods of A, but proceed to declare a singleton method on a different class, the singleton class.
Here you go:
$(document).ready(function(){
$('#submenu li').hover(function(){
$('#carousel').css('background-position', '10px 10px');
}, function(){
$('#carousel').css('background-position', '');
});
});
I've just written a library called jsPDF which generates PDFs using Javascript alone. It's still very young, and I'll be adding features and bug fixes soon. Also got a few ideas for workarounds in browsers that do not support Data URIs. It's licensed under a liberal MIT license.
I came across this question before I started writing it and thought I'd come back and let you know :)
Example create a "Hello World" PDF file.
// Default export is a4 paper, portrait, using milimeters for units_x000D_
var doc = new jsPDF()_x000D_
_x000D_
doc.text('Hello world!', 10, 10)_x000D_
doc.save('a4.pdf')
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
_x000D_
It's useful to work with Deferred Object in this case, and return promise:
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr= new FileReader();
fr.onload = function(e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL( files[0] );
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
And above function could be used in this way:
var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
alert(base64Data);
});
Or in your case:
$(input).on('change',function(){
readImage($(this)).done(function(base64Data){ alert(base64Data); });
});