When is lexing enough, when do you need EBNF?
EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:
S --> A | B
you can achieve in CNF by just listing each alternative production separately:
S --> A // `S` can be `A`,
S --> B // or it can be `B`.
The optional element from EBNF:
S --> X?
you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):
S --> B // `S` can be `B`,
B --> X // and `B` can be just `X`,
B --> // or it can be empty.
A production in a form like the last one B
above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).
Zero-or-more repetiton from EBNF:
S --> A*
you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):
S --> S A // `S` is just itself ended with `A` (which can be done many times),
S --> // or it can begin with empty-string, which stops the recursion.
Knowing that it generates just an empty string (ultimately) followed by zero or more A
s, the same string (but not the same language!) can be expressed using right-recursion:
S --> A S // `S` can be `A` followed by itself (which can be done many times),
S --> // or it can be just empty-string end, which stops the recursion.
And when it comes to +
for one-or-more repetition from EBNF:
S --> A+
it can be done by factoring out one A
and using *
as before:
S --> A A*
which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):
S --> A S // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A // or it could be just one single `A`.
Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:
A --> // Empty (nullable) production (AKA erasure).
B --> x // Single terminal symbol.
C --> y D // Simple state change from `C` to `D` when seeing input `y`.
E --> F z // Simple state change from `E` to `F` when seeing input `z`.
G --> G u // Left recursion.
H --> v H // Right recursion.
That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.
But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:
S --> a S b // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S --> // or it could be (ultimately) empty, which ends recursion.
then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S
indefinitely, which will always add another a
s and b
s on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many a
s were there to match them evenly with so many b
s. Grammars like this are called context-free grammars (at the very least), and they require a parser.
Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:
A R B --> A S B
You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R
into S
, but only when it's in between A
and B
, leaving those A
and B
themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.
Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of sorted()
:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
As you may have noticed, that's not Python code, but C code.
String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationvar newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
this.parentElement.removeChild(this);
};
var table = document.getElementById('content');
table.appendChild(newTH);
Working example: http://jsfiddle.net/23tBM/
You can also just hide with this.style.display = 'none'
.
g++ -print-search-dirs
gcc -print-search-dirs
I would go for checking if it has at least one key. That would suffice to tell me that it's not empty.
Boolean(Object.keys(obj || {})[0]) // obj || {} checks for undefined
--~ print a table
function printTable(list, i)
local listString = ''
--~ begin of the list so write the {
if not i then
listString = listString .. '{'
end
i = i or 1
local element = list[i]
--~ it may be the end of the list
if not element then
return listString .. '}'
end
--~ if the element is a list too call it recursively
if(type(element) == 'table') then
listString = listString .. printTable(element)
else
listString = listString .. element
end
return listString .. ', ' .. printTable(list, i + 1)
end
local table = {1, 2, 3, 4, 5, {'a', 'b'}, {'G', 'F'}}
print(printTable(table))
Hi man, I wrote a siple code that do this in pure Lua, it has a bug (write a coma after the last element of the list) but how i wrote it quickly as a prototype I will let it to you adapt it to your needs.
This may be a really late response but here is a solution that works. This line only recognizes th existance of files! It will not give you a false positive if directories exist.
if find /path/to/check/* -maxdepth 0 -type f | read
then echo "Files Exist"
fi
I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.
Edit
The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.
I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.
CSS
@media(min-width: 1400px){
.my-modal > .modal-lg {
width: 1308px;
}
}
JS is the same:
var modal = $modal.open({
animation: true,
templateUrl: 'modalTemplate.html',
controller: 'modalController',
size: 'lg',
windowClass: 'my-modal'
});
This solution
a) is only MySQL, no other language needed, and
b) returns SQL results, ready for processing!
#Search multiple database tables and/or columns
#Version 0.1 - JK 2014-01
#USAGE: 1. set the search term @search, 2. set the scope by adapting the WHERE clause of the `information_schema`.`columns` query
#NOTE: This is a usage example and might be advanced by setting the scope through a variable, putting it all in a function, and so on...
#define the search term here (using rules for the LIKE command, e.g % as a wildcard)
SET @search = '%needle%';
#settings
SET SESSION group_concat_max_len := @@max_allowed_packet;
#ini variable
SET @sql = NULL;
#query for prepared statement
SELECT
GROUP_CONCAT("SELECT '",`TABLE_NAME`,"' AS `table`, '",`COLUMN_NAME`,"' AS `column`, `",`COLUMN_NAME`,"` AS `value` FROM `",TABLE_NAME,"` WHERE `",COLUMN_NAME,"` LIKE '",@search,"'" SEPARATOR "\nUNION\n") AS col
INTO @sql
FROM `information_schema`.`columns`
WHERE TABLE_NAME IN
(
SELECT TABLE_NAME FROM `information_schema`.`columns`
WHERE
TABLE_SCHEMA IN ("my_database")
&& TABLE_NAME IN ("my_table1", "my_table2") || TABLE_NAME LIKE "my_prefix_%"
);
#prepare and execute the statement
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
If you can deal with not supporting old browsers (that is, MSIE 9 or older), you can do this with Flexible Box Layout Module which is already W3C CR. That module allows other nice tricks, too, such as re-ordering content.
Unfortunately, MSIE 9 or lesser do not support this and you have to use vendor prefix for the CSS property for every browser other than Firefox. Hopefully other vendors drop the prefix soon, too.
An another choice would be CSS Grid Layout but that has even less support from stable versions of browsers. In practice, only MSIE 10 supports this.
Update year 2020: All modern browsers support both display: flex
and display: grid
. The only one missing is support for subgrid
which in only supported by Firefox. Note that MSIE does not support either by the spec but if you're willing to add MSIE specific CSS hacks, it can be made to behave. I would suggest simply ignoring MSIE because even Microsoft says it should not be used anymore.
You can't install Integration Services with it. Express does not support Integration Services. So if you want build say SSIS-packages you'll need at least Standard Edition.
See more here.
This is done using the REPLACE function
To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:
SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn] FROM [SomeTable]
To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"
UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
I just had a look at the source - Protractor is waiting for Angular only in a few cases (like when element.all
is invoked, or setting / getting location).
So Protractor won't wait for Angular to stabilise after every command.
Also, it looks like sometimes in my tests I had a race between Angular digest cycle and click event, so sometimes I have to do:
elm.click();
browser.driver.sleep(1000);
browser.waitForAngular();
using sleep to wait for execution to enter AngularJS context (triggered by click
event).
If you want to get client key from request header, u can try following:
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from apps.authentication.models import CerebroAuth
class CerebroAuthentication(BaseAuthentication):
def authenticate(self, request):
client_id = request.META.get('HTTP_AUTHORIZATION')
if not client_id:
raise exceptions.AuthenticationFailed('Client key not provided')
client_id = client_id.split()
if len(client_id) == 1 or len(client_id) > 2:
msg = ('Invalid secrer key header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
try:
client = CerebroAuth.objects.get(client_id=client_id[1])
except CerebroAuth.DoesNotExist:
raise exceptions.AuthenticationFailed('No such client')
return (client, None)
JObjects can be enumerated via JProperty objects by casting it to a JToken:
foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
string name = x.Name;
JToken value = x.Value;
}
If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:
foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
string name = x.Name;
JToken value = x.Value;
}
I had the same behaviour, and fixed it by running Code::Blocks as administrator.
I am not sure about Python but most languages have push/append function for arrays.
cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:
https://jsfiddle.net/vtL5x0wh/
And the code:
<body ng-app="checkboxExample">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value0 = "none";
$scope.value1 = "none";
$scope.value2 = "none";
$scope.value3 = "none";
$scope.checkboxModel = {
critical1: {selected: true, id: 'C1', error:'critical' , score:20},
critical2: {selected: false, id: 'C2', error:'critical' , score:30},
critical3: {selected: false, id: 'C3', error:'critical' , score:40},
myClick : function($event) {
$scope.value0 = $event.selected;
$scope.value1 = $event.id;
$scope.value2 = $event.error;
$scope.value3 = $event.score;
}
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>
Value1:
<input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
</label><br/>
<label>Value3:
<input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
</label><br/><br/><br/><br/>
<tt>selected = {{value0}}</tt><br/>
<tt>id = {{value1}}</tt><br/>
<tt>error = {{value2}}</tt><br/>
<tt>score = {{value3}}</tt><br/>
</form>
I gave up trying to fix this issue.
My IIS web.config had the relevant "Access-Control-Allow-Methods
" in it, I experimented adding config settings to my Angular code, but after burning a few hours trying to get Chrome to call a cross-domain JSON web service, I gave up miserably.
In the end, I added a dumb ASP.Net handler webpage, got that to call my JSON web service, and return the results. It was up and running in 2 minutes.
Here's the code I used:
public class LoadJSONData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string URL = "......";
using (var client = new HttpClient())
{
// New code:
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic AUTHORIZATION_STRING");
HttpResponseMessage response = client.GetAsync(URL).Result;
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
context.Response.Write("Success: " + content);
}
else
{
context.Response.Write(response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
And in my Angular controller...
$http.get("/Handlers/LoadJSONData.ashx")
.success(function (data) {
....
});
I'm sure there's a simpler/more generic way of doing this, but life's too short...
This worked for me, and I can get on with doing normal work now !!
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
git rebase -i
allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.
# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`
# switch to a new branch pointing at the first commit
git checkout -b new-root root
# make any edits and then commit them with:
git commit --amend
# check out the previous branch (i.e. master)
git checkout @{-1}
# replace old root with amended version
git rebase --onto new-root root
# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue
# delete the branch "new-root"
git branch -d new-root
# delete the tag "root"
git tag -d root
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
res.setHeader('Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
Blockquote : you have to add OPTIONS & Authorization to the setHeader()
this change has fixed my problem, just give a try!
#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);
^wp.*\.php$
Should do the trick.
The .*
means "any character, repeated 0 or more times". The next .
is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.
If you do have a legitimate need to run some js
from a partial
, here's how you could do it, jQuery
is required:
<script type="text/javascript">
function scriptToExecute()
{
//The script you want to execute when page is ready.
}
function runWhenReady()
{
if (window.$)
scriptToExecute();
else
setTimeout(runWhenReady, 100);
}
runWhenReady();
</script>
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
You have an array of L.Marker:
let markers = [marker1, marker2, marker3]
let latlngs = markers.map(marker => marker.getLatLng())
let latlngBounds = L.latLngBounds(latlngs)
map.fitBounds(latlngBounds)
// OR with a smooth animation
// map.flyToBounds(latlngBounds)
For me to work I had to explicitly provide the type although it is contained in the blob by doing so:
const file = new File([blob], 'untitled', { type: blob.type })
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader
module. If you have used create-react-app
to scaffold your project, the module is already included, you just need to import your json:
import Profile from './components/profile';
This answer explains more.
browser does scrolling automatically to an element that gets focus, so what you can also do it to wrap the element that you need to be scrolled to into <a>...</a>
and then when you need scroll just set the focus on that a
Go to the project explorer block ... right click on project name select "Build Path"-----------> "Configuration Build Path"
then the pop up window will get open.
in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export
Click on 1) Source
select the project (under which that file is present which you want to compile)
and then click on ok....
Go to the workspace location of the project open a bin folder and search that class file ...
you will get that java file compiled...
just to cross verify check the changed timing.
hope this will help.
Thanks.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeYou can use git config
command to write a new rule to .git/config
to fetch pull requests from the repository:
$ git config --local --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*'
And then just:
$ git fetch origin
Fetching origin
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/container-images/memcached
* [new ref] refs/pull/2/head -> origin/pr/2
* [new ref] refs/pull/3/head -> origin/pr/3
Should work in all cases:
SELECT regexp_replace(0.1234, '^(-?)([.,])', '\10\2') FROM dual
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
Yes its possible! and you can use as many colors and images as you desire, here is the right way:
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image: _x000D_
/* 1) An image */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position */ 0 0, _x000D_
/* 2) Gradient position */ 0 100px,_x000D_
/* 3) Color position */ 0 130px;_x000D_
_x000D_
background-size: _x000D_
/* 1) Image size */ 640px 100px,_x000D_
/* 2) Gradient size */ 100% 30px, _x000D_
/* 3) Color size */ 100% 30px;_x000D_
}
_x000D_
You should pass length into fwrite instead of sizeof(buffer).
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);
}
}
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
Every number from 1,2,5,6,9,10... is divisible by 4 with remainder 1 or 2.
>>> ','.join(str(i) for i in xrange(100) if i % 4 in (1,2))
'1,2,5,6,9,10,13,14,...'
Here are some high level thoughts and info that might help, aside from the other answers.
Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.
It kind of depends on the requirements of what your app/website needs to be compatible with.
You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/
Got it. Add the following within the DataGrid.Resources section:
<DataGrid.Resources>
<Style TargetType="{x:Type dg:DataGridCell}">
<Style.Triggers>
<Trigger Property="dg:DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="#CCDAFF" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
Using Integer.toHexString(...)
is a good answer. But personally prefer to use String.format(...)
.
Try this sample as a test.
byte[] values = new byte[64];
Arrays.fill(values, (byte)8); //Fills array with 8 just for test
String valuesStr = "";
for(int i = 0; i < values.length; i++)
valuesStr += String.format("0x%02x", values[i] & 0xff) + " ";
valuesStr.trim();
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
Here's a south migration version of @peter-g's answer.
I often fiddle with raw sql, so this comes in handy as 0001_initial.py for any befuddled apps. It will only work on DBs that support SHOW TABLES
(like mysql). Substitute something like SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
if you use PostgreSQL. Also, I often do this exact same thing for both the forwards
and backwards
migrations.
from south.db import db
from south.v2 import SchemaMigration
from django.db.utils import DatabaseError
from os import path
from logging import getLogger
logger = getLogger(__name__)
class Migration(SchemaMigration):
def forwards(self, orm):
app_name = path.basename(path.split(path.split(path.abspath(__file__))[0])[0])
table_tuples = db.execute(r"SHOW TABLES;")
for tt in table_tuples:
table = tt[0]
if not table.startswith(app_name + '_'):
continue
try:
logger.warn('Deleting db table %s ...' % table)
db.delete_table(table)
except DatabaseError:
from traceback import format_exc
logger.error("Error running %s: \n %s" % (repr(self.forwards), format_exc()))
Coworker/cocoders would kill me if they knew I did this, though.
Modify your CSS like this:
.vertical_banner {_x000D_
border: 1px solid #E9E3DD;_x000D_
float: left;_x000D_
height: 210px;_x000D_
margin: 2px;_x000D_
padding: 4px 2px 10px 10px;_x000D_
text-align: left;_x000D_
width: 117px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
position:absolute; /* added */_x000D_
bottom:0; /* added */_x000D_
left:0; /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
<div id="bottom_link">_x000D_
<input type="submit" value="Continue">_x000D_
</div>_x000D_
</div>
_x000D_
I disagree with the accepted answer being "the easiest", particularly if you want to use virtualenv.
You can use the Unofficial Windows Binaries instead. Download the appropriate wheel from there, and install it with pip
:
pip install pywin32-219-cp27-none-win32.whl
(Make sure you pick the one for the right version and bitness of Python).
You might be able to get the URL and install it via pip
without downloading it first, but they're made it a bit harder to just grab the URL. Probably better to download it and host it somewhere yourself.
Or if you still want to use formatter created from pattern you can just use LocalDateTime instead of Instant:
LocalDateTime datetime = LocalDateTime.now();
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(datetime)
axios signature for post is axios.post(url[, data[, config]])
. So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...
@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.
Start to Create a Pull Request via the git hosting service you're using. If the branch has been fully merged into the base branch, you'll be unable to create the new PR.
You don't need to actually make the pull request, just use the first step where you pick branches.
For example, on GitHub:
There isn't anything to compare
This doesn't use git on the command line, but I often find it's helpful to use the other tools at your disposal with a clear mental model rather than attempt to remember another arcane git command.
I had the component name wrong(it is case sensitive) in either app.rounting.ts or app.module.ts.
The only test for NULL is IS NULL or IS NOT NULL. Testing for equality is nonsensical because by definition one doesn't know what the value is.
Here is a wikipedia article to read:
its a block element, and you need to use none
document.getElementById("test").style.display="none"
hidden
is used for visibility
Yes, it is security issue. Check folder permissions and service account under which SQL server 2008 starts.
Assuming they always exist and are not part of your data, this will work:
declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)
I defined a median function for a list of numbers as
def median(numbers):
return (sorted(numbers)[int(round((len(numbers) - 1) / 2.0))] + sorted(numbers)[int(round((len(numbers) - 1) // 2.0))]) / 2.0
function ordsfx(a){return["th","st","nd","rd"][(a=~~(a<0?-a:a)%100)>10&&a<14||(a%=10)>3?0:a]}
See annotated version at https://gist.github.com/furf/986113#file-annotated-js
Short, sweet, and efficient, just like utility functions should be. Works with any signed/unsigned integer/float. (Even though I can't imagine a need to ordinalize floats)
A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.
You can modify cookies using document.cookie
.
You can easily find many examples how to modify cookies.
If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .
It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.
In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?
Also as it creates an Object and its always good to assign value in object rather than manipulating string.
Here is the code sample:
var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);
sscsb.ConnectTimeout = 30;
var conn = new SqlConnection(sscsb.ConnectionString);
Sometimes I need to extract several command line parameters, but not all of them and not from the first one. Let's assume the following call:
Test.bat uno dos tres cuatro cinco seis siete
Of course, the extension ".bat" is not needed at least you have test.exe in same folder. What we want is to get the output "tres cuatro cinco" (no matter if one line or three). The goal is that only I need three parameters and starting in the third one. In order to have a simple example the action for each one is just "echo", but you can think in some other more complex action over the selected parameters.
I've produced some examples, (options) in order you can see which one you consider better for you. Unfortunately, there is not a nice (or I don't know about) way based on a for loop over the range like "for %%i in (%3, 1, %5)".
@echo off
setlocal EnableDelayedExpansion
echo Option 1: one by one (same line)
echo %3, %4, %5
echo.
echo Option 2: Loop For one by one
for %%a in (%3, %4, %5) do echo %%a
echo.
echo Option 3: Loop For with check of limits
set i=0
for %%a in (%*) do (
set /A i=i+1
If !i! GTR 2 if !i! LSS 6 echo %%a
)
echo.
echo Option 4: Loop For with auxiliary list
for /l %%i in (3,1,5) do (
set a=%%i
set b=echo %%
set b=!b!!a!
call !b!
)
echo.
echo Option 5: Assigning to an array of elements previously
set e[0]=%0
set i=0
for %%a in (%*) do (
set /A i=i+1
set e[!i!]=%%a
)
for /l %%i in (3,1,5) do (
echo !e[%%i]!
)
echo.
echo Option 6: using shift and goto loop. It doesn't work with for loop
set i=2
:loop6
set /A i=i+1
echo %3
shift
If %i% LSS 5 goto :loop6
Probably you can find more options or combine several ones. Enjoy them.
This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....
application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.
Solution
Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.
Paolo Bergantino's answer has the great advantage of only using the stdlib, and works for this simple example where there are no decorator arguments nor decorated function arguments.
However it has 3 major limitations if you want to tackle more general cases:
makestyle(style='bold')
decorator is non-trivial.@functools.wraps
do not preserve the signature, so if bad arguments are provided they will start executing, and might raise a different kind of error than the usual TypeError
.@functools.wraps
to access an argument based on its name. Indeed the argument can appear in *args
, in **kwargs
, or may not appear at all (if it is optional).I wrote decopatch
to solve the first issue, and wrote makefun.wraps
to solve the other two. Note that makefun
leverages the same trick than the famous decorator
lib.
This is how you would create a decorator with arguments, returning truly signature-preserving wrappers:
from decopatch import function_decorator, DECORATED
from makefun import wraps
@function_decorator
def makestyle(st='b', fn=DECORATED):
open_tag = "<%s>" % st
close_tag = "</%s>" % st
@wraps(fn)
def wrapped(*args, **kwargs):
return open_tag + fn(*args, **kwargs) + close_tag
return wrapped
decopatch
provides you with two other development styles that hide or show the various python concepts, depending on your preferences. The most compact style is the following:
from decopatch import function_decorator, WRAPPED, F_ARGS, F_KWARGS
@function_decorator
def makestyle(st='b', fn=WRAPPED, f_args=F_ARGS, f_kwargs=F_KWARGS):
open_tag = "<%s>" % st
close_tag = "</%s>" % st
return open_tag + fn(*f_args, **f_kwargs) + close_tag
In both cases you can check that the decorator works as expected:
@makestyle
@makestyle('i')
def hello(who):
return "hello %s" % who
assert hello('world') == '<b><i>hello world</i></b>'
Please refer to the documentation for details.
On Android 7 works it:
ip route get 8.8.8.8
output will be: 8.8.8.8 via gateway...
You can create space between table rows by adding an empty row of cells like this...
<tr><td></td><td></td></tr>
CSS can then be used to target the empty cells like this…
table :empty{border:none; height:10px;}
NB: This technique is only good if none of your normal cells will be empty/vacant.
Even a non-breaking space will do to avoid a cell from being targetted by the CSS rule above.
Needless to mention that you can adjust the space's height to whatever you like with the height property included.
You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.
import io
print (io.DEFAULT_BUFFER_SIZE)
It's an old question, however might be useful for someone like me.
lodash
has _.inRange()
function https://lodash.com/docs/4.17.4#inRange
Example:
_.inRange(3, 2, 4);
// => true
Please note that this method utilizes the Lodash
utility library, and requires access to an installed version of Lodash.
app.get
is called when the HTTP method is set to GET
, whereas app.use
is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.
Here I found another good option to migrate your MongoDB data to Elasticsearch. A go daemon that syncs mongodb to elasticsearch in realtime. Its the Monstache. Its available at : Monstache
Below the initial setp to configure and use it.
Step 1:
C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test
Step 2 :
C:\Program Files\MongoDB\Server\4.0\bin>mongo
C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
MongoDB Enterprise test:PRIMARY>
Step 3 : Verify the replication.
MongoDB Enterprise test:PRIMARY> rs.status();
{
"set" : "test",
"date" : ISODate("2019-01-18T11:39:00.380Z"),
"myState" : 1,
"term" : NumberLong(2),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
}
},
"lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
"members" : [
{
"_id" : 0,
"name" : "localhost:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 736,
"optime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2019-01-18T11:38:57Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1547810805, 1),
"electionDate" : ISODate("2019-01-18T11:26:45Z"),
"configVersion" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
}
],
"ok" : 1,
"operationTime" : Timestamp(1547811537, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1547811537, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
MongoDB Enterprise test:PRIMARY>
Step 4.
Download the "https://github.com/rwynn/monstache/releases".
Unzip the download and adjust your PATH variable to include the path to the folder for your platform.
GO to cmd and type "monstache -v"
# 4.13.1
Monstache uses the TOML format for its configuration. Configure the file for migration named config.toml
Step 5.
My config.toml -->
mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
elasticsearch-urls = ["http://localhost:9200"]
direct-read-namespaces = [ "admin.users" ]
gzip = true
stats = true
index-stats = true
elasticsearch-max-conns = 4
elasticsearch-max-seconds = 5
elasticsearch-max-bytes = 8000000
dropped-collections = false
dropped-databases = false
resume = true
resume-write-unsafe = true
resume-name = "default"
index-files = false
file-highlighting = false
verbose = true
exit-after-direct-reads = false
index-as-update=true
index-oplog-time=true
Step 6.
D:\15-1-19>monstache -f config.toml
An old post, but I love to share as I have the same case but I finally knew the problem :
Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.
Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.
But please inspect this sample that did not heed the above case :
<div class="btn-list" id="selected-country"></div>
Dynamically appended :
<button class="btn-map" data-country="'+country+'">'+ country+' </button>
This function is working good by clicking the button :
$(document).ready(function() {
$('#selected-country').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
})
or you can use body like :
$('body').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
compare to this that not working :
$(document).ready(function() {
$('.btn-map').on("click", function() {
var datacountry = $(this).data('country'); alert(datacountry);
});
});
hope it will help
<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>
You have few problems with your code like using .
for concatenation
Try this -
$(function () {
$('input').on('click', function () {
var Status = $(this).val();
$.ajax({
url: 'Ajax/StatusUpdate.php',
data: {
text: $("textarea[name=Status]").val(),
Status: Status
},
dataType : 'json'
});
});
});
This can be done by iterating myString
and shifting fromIndex
parameter in indexOf()
:
int currentIndex = 0;
while (
myString.indexOf(
mySubstring,
currentIndex) >= 0) {
System.out.println(currentIndex);
currentIndex++;
}
3 years later and not a single person has answered this question completely.
The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.
Assuming the form has a submit button, whether a <button id="save-form">
or an <input id="save-form" type="submit">
, do:
$("#save-form").on("click", function () {
$.ajax({
...
});
return false;
});
date("Y-m-d",strtotime("last day of +1 month",strtotime($anydate)))
Since the string resources will have already been loaded for the existing locale, the activities already opened will not automatically display using strings from the new locale. The only way to solve this is to reload all of the strings and set them again on the views. Typically, a call to setContentView(...)
will be able to cover this (depending on your Activity structure), but of course it has the side-effect of losing any view state you had.
public void onResume() {
super.onResume();
...
if (localeHasChanged) {
setContentView(R.layout.xxx);
}
...
}
You will probably not want to reload the views every single time in onResume()
, but only when the locale has changed. Checking when to update the views (i.e. localeHasChanged
) is a matter of propagating the locale change event to the previous activities. This could be done in many ways, such as using static singleton-esque state or persisting this event to storage.
You could also try to minimise the number of Activities that can be opened when you can change the locale, e.g. by having the selection be at one of the initial screens.
Try this code.
startPoint.distanceTo(endPoint) function returns the distance between those places in meters.
Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);
Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);
double distance=startPoint.distanceTo(endPoint);
here "distance" is our required result in Meters. I hope it will work for android.
Here is a way to calculate memory usage of currently running application:
public static long getUsedMemorySize() {
long freeSize = 0L;
long totalSize = 0L;
long usedSize = -1L;
try {
Runtime info = Runtime.getRuntime();
freeSize = info.freeMemory();
totalSize = info.totalMemory();
usedSize = totalSize - freeSize;
} catch (Exception e) {
e.printStackTrace();
}
return usedSize;
}
Use %p
, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u
expects an unsigned int
, but what if void*
has a different size or alignment requirement than unsigned int
?)
*) [See Jonathan's fine answer!] Alternatively to %p
, you can use pointer-specific macros from <inttypes.h>
, added in C99.
All object pointers are implicitly convertible to void*
in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):
printf("x lives at %p.\n", (void*)&x);
you can wrap the content of the <tbody>
in a scrollable <div>
:
html
....
<tbody>
<tr>
<td colspan="2">
<div class="scrollit">
<table>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
...
css
.scrollit {
overflow:scroll;
height:100px;
}
see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/
Different tools may interpret the meaning of @Nullable
differently. For example, the Checker Framework and FindBugs handle @Nullable
differently.
Try this
/.*[^a]$/
The []
denotes a character class, and the ^
inverts the character class to match everything but an a
.
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
Update
Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.
He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.
He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.
The demos can be found on his GitHub Account.
The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.
Original Answer
Well go ahead and built it yourself then.
Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.
One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.
Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.
What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.
I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.
Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).
Rome (or RoR) wasn't built over night, and neither will Node.js be.
Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)
As far as I remember, in the current JDBC, Resultsets and statements implement the AutoCloseable interface. That means they are closed automatically upon being destroyed or going out of scope.
Have you tried rake reklamer:iqmedier
?
My custom rake tasks are in the lib directory, not in lib/tasks. Not sure if that matters.
Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:
Public Module Module1
Public Foo As Integer
End Module
I tried many solutions. I found mine in the drop down menu of the Entreprise Explorer: - Deleting org.eclipse.core.resources has no effect. - "Top Level Elements -> Projects" was already checked for me; swtiching with Documents has no effect. - Selecting all extensions in the filter option of the drop down menu has no effect at first sight, maybe it solve part of the problem.
The solution come from "Unselecting documents" (third choice in the Entreprise Explorer drop down menu). I think that choice reset the filtering of documents displayed in the Explorer.
Hope it'll helps JN Gerbaux
Without a class or an id, and with your specific html:
table tr td label {display:none}
Otherwise if you have jQuery
$('label[for="foo"]').css('display', 'none');
For transitions you can use the following to detect the end of a transition via jQuery:
$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
Mozilla has an excellent reference:
For animations it's very similar:
$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Note that you can pass all of the browser prefixed event strings into the bind() method simultaneously to support the event firing on all browsers that support it.
Update:
Per the comment left by Duck: you use jQuery's .one()
method to ensure the handler only fires once. For example:
$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
$("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Update 2:
jQuery bind()
method has been deprecated, and on()
method is preferred as of jQuery 1.7
. bind()
You can also use off()
method on the callback function to ensure it will be fired only once. Here is an example which is equivalent to using one()
method:
$("#someSelector")
.on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
function(e){
// do something here
$(this).off(e);
});
References:
A simple way to see the Git commit short version and the Git commit message is:
git log --oneline
Note that this is shorthand for
git log --pretty=oneline --abbrev-commit
Lodash has got _.mapValues()
which is identical to Underscore.js's _.mapObject()
.
Create a directory named like Images
and put all the images that will be rendered by the Markdown.
For example, put example.png
into Images
.
To load example.png
that was located under the Images
directory before.
![title](Images/example.png)
Note : Images
directory must be located under the same directory of your markdown text file which has .md
extension.
Definition in http.js from the @angular/http:
delete(url, options)
The request doesn't accept a body so it seem your only option is to but your data in the URI.
I found another topic with references to correspond RFC, among other things: How to pass data in the ajax DELETE request other than headers
Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.
If you follow the stackoverflow podcasts you can hear Jeff (and Geoff?) discuss its greatness. https://blog.stackoverflow.com/2008/08/podcast-17/. But remember that using these separate layers means things are easier in the future--and harder now. And layers can make things slower. And you may not need them. But don't let that stop you from learning what it is--when building big, robust, long-lived systems, it's invaluable.
You can use this two attributes together with TextFormField
TextFormField(
keyboardType: TextInputType.number
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
It's allow to put only numbers, no thing else ..
https://api.flutter.dev/flutter/services/TextInputFormatter-class.html
This worked for me:
$("#element1").droppable(
{
drop: function(event, ui)
{
var currentPos = ui.helper.position();
alert("left="+parseInt(currentPos.left)+" top="+parseInt(currentPos.top));
}
});
var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);
Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/
If you don't want line numbers shown all the time another way to find the line number of a piece of code is to just click in the left-most margin and create a breakpoint (a small blue arrow appears) then go to the breakpoint navigator (?7) where it will list the breakpoint with its line number. You can delete the breakpoint by right clicking on it.
To add to CrazyGeek's answer, get
or get_or_create
queries work only when there's one instance of the object in the database, filter
is for two or more.
If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.
def updateUserCollection(request):
data = json.loads(request.body)
card_id = data['card_id']
action = data['action']
user = request.user
card = Cards.objects.get(card_id=card_id)
if data-action == 'add':
collection = Collection.objects.get_or_create(user=user, card=card)
collection.quantity + 1
collection.save()
elif data-action == 'remove':
collection = Cards.objects.filter(user=user, card=card)
collection.quantity = 0
collection.update()
Note: .save()
becomes .update()
for updating multiple objects. Hope this helps someone, gave me a long day's headache.
set this jquery min js
script src="http://code.jquery.com/jquery-1.10.1.min.js"
in wp-admin/admin-header.php
If you are trying to bind is a Model class, you can add a new readonly property to it like:
public string FormattedPercentage
{
get
{
If(this.Percentage < 50)
return "0 %";
else
return string.Format("{0} %", this.Percentage)
}
}
Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself
Joins are more easily explained with an example:
To simulate persons and emails stored in separate tables,
Table A and Table B are joined by Table_A.id = Table_B.name_id
Inner Join
Only matched ids' rows are shown.
Outer Joins
Matched ids and not matched rows for Table A are shown.
Matched ids and not matched rows for Table B are shown.
Matched ids and not matched rows from both Tables are shown.
Note: Full outer join is not available on MySQL
Your code assumes the existence of something:
$user = $_POST["username"];
PHP is letting you know that there is no "username" in the $_POST
array. In this instance, you would be safer checking to see if the value isset()
before attempting to access it:
if ( isset( $_POST["username"] ) ) {
/* ... proceed ... */
}
Alternatively, you could hi-jack the ||
operator to assign a default:
$user = $_POST["username"] || "visitor" ;
As long as the user's name isn't a falsy value, you can consider this method pretty reliable. A much safer route to default-assignment would be to use the ternary operator:
$user = isset( $_POST["username"] ) ? $_POST["username"] : "visitor" ;
My EAR project had 2 modules *.ear and *.war and I got this dependency error on *.war
project when trying mvn eclipse:eclipse
. Resolved it by fixing utf-8 encoding issue in the *.war
project. mvn
-X
or -e
options weren't of help here.
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
I had the same error in VS2013 and Resharper9. The problem was because i forgot to annotate test method with [Test] :) Hope this helps anyone
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
// UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
Hopefully, this reply will save beginners a lot of aggravation.
This will Read Specified file extension files in given path(looks sub folders also)
public static Map<String,List<File>> getFileNames(String
dirName,Map<String,List<File>> filesContainer,final String fileExt){
String dirPath = dirName;
List<File>files = new ArrayList<>();
Map<String,List<File>> completeFiles = filesContainer;
if(completeFiles == null) {
completeFiles = new HashMap<>();
}
File file = new File(dirName);
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
boolean acceptFile = false;
if(file.isDirectory()) {
acceptFile = true;
}else if (file.getName().toLowerCase().endsWith(fileExt))
{
acceptFile = true;
}
return acceptFile;
}
};
for(File dirfile : file.listFiles(fileFilter)) {
if(dirfile.isFile() &&
dirfile.getName().toLowerCase().endsWith(fileExt)) {
files.add(dirfile);
}else if(dirfile.isDirectory()) {
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
getFileNames(dirfile.getAbsolutePath(),completeFiles,fileExt);
}
}
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
return completeFiles;
}
Thanks Antonio,
I've just added the lists
command at the end so it will only return one array with key and count:
Laravel 4
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->lists('total','browser');
Laravel 5.1
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->lists('total','browser')->all();
Laravel 5.2+
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->pluck('total','browser')->all();
update on someone else his answer transparant sides instead of white so it works on other color backgrounds too.
body {_x000D_
background: url(http://s1.picswalls.com/wallpapers/2016/03/29/beautiful-nature-backgrounds_042320876_304.jpg)_x000D_
}_x000D_
_x000D_
div {_x000D_
background: url(https://www.w3schools.com/w3css/img_avatar3.png) center center;_x000D_
background-size: contain;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
margin: 50px;_x000D_
border: 5px solid white;_x000D_
box-shadow: 0px 0 rgba(0, 0, 0, 0), 0px 0 rgba(0, 0, 0, 0), 0 7px 7px -5px black;_x000D_
}
_x000D_
<div>_x000D_
</div>
_x000D_
You could only write one where clause.
SELECT table1.f_id FROM table1
INNER JOIN table2
ON table2.f_id = table1.f_id
where table1.f_com_id = '430' AND
table1.f_status = 'Submitted' AND table2.f_type = 'InProcess'
YurkamTim is right. It needs only a modification:
After function($) you need a pointer to the external variable by "use(&$searchedValue)" and then you can access the external variable. Also you can modify it.
$neededObject = array_filter(
$arrayOfObjects,
function ($e) use (&$searchedValue) {
return $e->id == $searchedValue;
}
);
It looks like details
is an array of hashes. So item
inside of your block will be the whole hash. Therefore, to check the :qty
key, you'd do something like the following:
details.select{ |item| item[:qty] != "" }
That will give you all items where the :qty
key isn't an empty string.
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
interesting, datepicker default date is current date as I found,
but you can set date by
$("#yourinput").datepicker( "setDate" , "7/11/2011" );
don't forget to check you system date :)
First get the item you want, change what you want on that object and set it back on the state.
The way you're using state by only passing an object in getInitialState
would be way easier if you'd use a keyed object.
handleChange: function (e) {
item = this.state.items[1];
item.name = 'newName';
items[1] = item;
this.setState({items: items});
}
(left, upper, right, lower) means two points,
with an 800x600 pixel image, the image's left upper point is (0, 0), the right lower point is (800, 600).
So, for cutting the image half:
from PIL import Image
img = Image.open("ImageName.jpg")
img_left_area = (0, 0, 400, 600)
img_right_area = (400, 0, 800, 600)
img_left = img.crop(img_left_area)
img_right = img.crop(img_right_area)
img_left.show()
img_right.show()
The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).
Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).
I have used jQuery AJAX to make AJAX requests.
Check the following code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "testme", //this is my servlet
data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
success: function(msg){
$('#output').append(msg);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
input:<input id="ip" type="text" name="" value="" /><br></br>
output:<input id="op" type="text" name="" value="" /><br></br>
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
<div id="output"></div>
</body>
Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH
I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:
StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = @PatientId and IdDrugService = 226)> 0)
THEN cast((S.UnitsOrdered) as varchar(50))
ELSE 'No Labs Available'
END
window bottom scroll to top scroll using jquery.
<script>
var lastScroll = 0;
$(document).ready(function($) {
$(window).scroll(function(){
setTimeout(function() {
var scroll = $(window).scrollTop();
if (scroll > lastScroll) {
$("header").removeClass("menu-sticky");
}
if (scroll == 0) {
$("header").removeClass("menu-sticky");
}
else if (scroll < lastScroll - 5) {
$("header").addClass("menu-sticky");
}
lastScroll = scroll;
},0);
});
});
</script>
Here is one more alternative that uses XSL transformations for more complex email templates: Sending HTML-based email from .NET applications.
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
foreach ($arr as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
true array:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
$array = array(); // inisiasi variable array in format array
foreach ($arr as $line) { // loop line by line and convert into array
$array[] = $line;
};
print_r($array); // display all value
echo $array[1]; // diplay index 1
Embed Online:
body, html, iframe { _x000D_
width: 100% ;_x000D_
height: 100% ;_x000D_
overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/vE1gst" ></iframe>
_x000D_
You should check the EOF after reading from file.
fscanf_s // read from file
while(condition) // check EOF
{
fscanf_s // read from file
}
Now that more time has passed, here's a way to do it in Java 8:
URLConnection conn = url.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
pageText = reader.lines().collect(Collectors.joining("\n"));
}
I think you want to say "Are the last four characters of $file equal to .txt
?" If so, you can use the following:
if [ ${file: -4} == ".txt" ]
Note that the space between file:
and -4
is required, as the ':-' modifier means something different.
Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>>
or List<KeyValuePair<string, string>>
if you're not using .NET 4.
When we download the binary of apache-jmeter-x.x.tgz, where x could be any version of apache Jmeter. ApacheJMeter.jar must present inside apache-jmeter-x/bin folder , if it is not present somewhere your package not downloaded properly. Cause could be slow internet, or improper shutdown
Download package again and make sure ApacheJMeter.jar present in apache-jmeter-x/bin folder. Once it is present hit sh jemeter.sh
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
You need a new version of notepad++. Looks like old versions don't support |
.
Note: egrep "CAT|TOWN"
will search for lines containing CATOWN. (CAT)|(TOWN)
is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)
You could also do
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id
is unique among all rows. Otherwise there could be multiple rows with the maximum value for id
and you'll only get one.
You need to follow the installation instructions and not just download the files into your Python27
directory. It has to be installed in the site-packages
directory properly, which the directions tell you how to do.
UsernamePasswordAuthenticationFilter
is only used for/login
, and latter filters are not?
No, UsernamePasswordAuthenticationFilter
extends AbstractAuthenticationProcessingFilter
, and this contains a RequestMatcher
, that means you can define your own processing url, this filter only handle the RequestMatcher
matches the request url, the default processing url is /login
.
Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter
executes chain.doFilter(request, response);
.
More details about core fitlers
Does the form-login namespace element auto-configure these filters?
UsernamePasswordAuthenticationFilter
is created by <form-login>
, these are Standard Filter Aliases and Ordering
Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?
It depends on whether the before fitlers are successful, but FilterSecurityInterceptor
is the last fitler normally.
Does configuring two http elements create two springSecurityFitlerChains?
Yes, every fitlerChain has a RequestMatcher
, if the RequestMatcher
matches the request, the request will be handled by the fitlers in the fitler chain.
The default RequestMatcher
matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**"
).
If you want to konw more about the fitlers, I think you can check source code in spring security.
doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
If you are already extending from ActionBarActivity and you are trying to get the action bar from a fragment:
ActionBar mActionBar = (ActionBarActivity)getActivity()).getSupportActionBar();
Tossing my hat in the ring for fun, added advantage of memoizing
const callOnce = (fn, i=0, memo) => () => i++ ? memo : (memo = fn());
// usage
const myExpensiveFunction = () => { return console.log('joe'),5; }
const memoed = callOnce(myExpensiveFunction);
memoed(); //logs "joe", returns 5
memoed(); // returns 5
memoed(); // returns 5
...
When you use Object.defineProperties
, by default writable
is set to false
, so _year
and edition
are actually read only properties.
Explicitly set them to writable: true
:
_year: {
value: 2004,
writable: true
},
edition: {
value: 1,
writable: true
},
Check out MDN for this method.
writable
true
if and only if the value associated with the property may be changed with an assignment operator.
Defaults tofalse
.
The following may work as well.
function isNumeric(v) {
return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
};
Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.
mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep '^INSERT' > 5406.sql
You're probably trying to run Python 3 file with Python 2 interpreter. Currently (as of 2019), python
command defaults to Python 2 when both versions are installed, on Windows and most Linux distributions.
But in case you're indeed working on a Python 2 script, a not yet mentioned on this page solution is to resave the file in UTF-8+BOM encoding, that will add three special bytes to the start of the file, they will explicitly inform the Python interpreter (and your text editor) about the file encoding.
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
Try this::
sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
m => string.Format(
"{0},{1},{2}",
m.Groups[1].Value,
m.Groups[2].Value.Replace(",", string.Empty),
m.Groups[3].Value));
This is about as clean an answer as you'll get, at least with regexes.
(\D+)
: First capture group. One or more non-digit characters.\s+\$
: One or more spacing characters, then a literal dollar sign ($).([\d,]+)
: Second capture group. One or more digits and/or commas.\.\d+
: Decimal point, then at least one digit.\s+
: One or more spacing characters.(.)
: Third capture group. Any non-line-breaking character.The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:
"$1,$2,$3"
using Linq would be:
listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";
UPDATE
This can be simplified to be...
listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";
For multiple items (condition is met by multiple items):
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
Enter this url in your browser with the users name you want to find and your access token
https://api.instagram.com/v1/users/search?q=[USERNAME]&access_token=[ACCESS TOKEN]
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
You can do it directly with the HTTPS URL like this:
pip install git+https://github.com/username/repo.git
This also works just appending that line in the requirements.txt in a Django project, for instance.
if you handel this from dataBase try :
<img :src="baseUrl + 'path/path' + obj.key +'.png'">
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
Late to the party, but the top voted answers all seemed like hacks to me.
All I did was remove the following from my app.config in the test project. Worked.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
using (FileStream fs = File.Create(path))
{
}
Will create or overwrite a file.
SHOW FULL PROCESSLIST
If you don't use FULL
, "only the first 100 characters of each statement are shown in the Info
field".
When using phpMyAdmin, you should also click on the "Full texts" option ("? T ?" on top left corner of a results table) to see untruncated results.
For bootstrap 4.3.1, I was using nav-pills and nothing worked for me except this:
<ul class="nav nav-pills justify-content-end ml-auto">
<li ....</li>
</ul>
You'll need to either insert BR
tag appropriately in the resulting string, or use for example a PRE
tag so that the formatting of the stringify
is retained:
var data = { a: 1, b: 2 };
var Hello = React.createClass({
render: function() {
return <div><pre>{JSON.stringify(data, null, 2) }</pre></div>;
}
});
React.render(<Hello />, document.getElementById('container'));
class PrettyPrintJson extends React.Component {
render() {
// data could be a prop for example
// const { data } = this.props;
return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
}
}
ReactDOM.render(<PrettyPrintJson/>, document.getElementById('container'));
const PrettyPrintJson = ({data}) => {
// (destructured) data could be a prop for example
return (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);
}
Or, ...
const PrettyPrintJson = ({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>);
(You might even want to use a memo, 16.6+)
const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>));
[>=1000]#,##0,"K";[<=-1000]-#,##0,"K";0
teylyn's answer is great. This just adds negatives beyond -1000 following the same format.
First I would suggest putting a Log in each case of your switch to be sure that your code is being called.
Then I would check that the layouts are actually different.
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.
This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.
The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>
, but an expression Expression<Func<P,T>>
. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.
The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x)
translates to return x == null || x == string.empty
. That has to be done explicitly for the translation to SQL to take place.
There might be a more elegant way to do this but here is my solution. With Jquery
fileEle.value = "";
var parEle = $(fileEle).parent();
var newEle = $(fileEle).clone()
$(fileEle).remove();
parEle.append(newEle);
Basically you cleat the value of the input. Clone it and put the clone in place of the old one.
Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.
Different number of bins on the same dataset can reveal different features of the data.
Unfortunately, there is no universal best method that can determine the number of bins.
One of the powerful methods is the Freedman–Diaconis rule, which automatically determines the number of bins based on statistics of a given dataset, among many other alternatives.
Accordingly, the following can be used to utilise the Freedman–Diaconis rule in a gnuplot
script:
Say you have a file containing a single column of samples, samplesFile
:
# samples
0.12345
1.23232
...
The following (which is based on ChrisW's answer) may be embed into an existing gnuplot
script:
...
## preceeding gnuplot commands
...
#
samples="$samplesFile"
stats samples nooutput
N = floor(STATS_records)
samplesMin = STATS_min
samplesMax = STATS_max
# Freedman–Diaconis formula for bin-width size estimation
lowQuartile = STATS_lo_quartile
upQuartile = STATS_up_quartile
IQR = upQuartile - lowQuartile
width = 2*IQR/(N**(1.0/3.0))
bin(x) = width*(floor((x-samplesMin)/width)+0.5) + samplesMin
plot \
samples u (bin(\$1)):(1.0/(N*width)) t "Output" w l lw 1 smooth freq
One of the biggest problems I found was to convert from weeks to dates, and then from dates to weeks.
The main problem is when trying to get the correct week year from a date that belongs to a week of the previous year. Luckily System.Globalization.ISOWeek.GetYear
handles this.
Here is my solution:
public class WeekOfYear
{
public static (int Year, int Week) DateToWeekOfYear(DateTime date) =>
(ISOWeek.GetYear(date), ISOWeek.GetWeekOfYear(date));
public static bool ValidYearAndWeek(int year, int week) =>
year >= 1 && year <= 9999 && week >= 1 && week <= 53 // bounds of year/week
&& !(year <= 1 && week <= 1) && !(year >= 9999 && week >= 53); // bounds of DateTime
public int Year { get; }
public int Week { get; }
public virtual DateTime StartOfWeek { get; protected set; }
public virtual DateTime EndOfWeek { get; protected set; }
public virtual IEnumerable<DateTime> DaysInWeek =>
Enumerable.Range(1, 10).Select(i => StartOfWeek.AddDays(i));
public WeekOfYear(int year, int week)
{
if (!ValidYearAndWeek(year, week))
throw new ArgumentException($"DateTime can't represent {week} of year {year}.");
Year = year;
Week = week;
StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday);
EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddDays(1).AddTicks(-1);
}
public WeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
public WeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}
The second biggest problem was the preference for weeks starting on Sundays in the US.
The solution I cam up with subclasses WeekOfYear
from above, and manages the offset of the in the constructor (which converts week to dates) and DateToWeekOfYear
(which converts from date to week).
public class UsWeekOfYear : WeekOfYear
{
public static new (int Year, int Week) DateToWeekOfYear(DateTime date)
{
// if date is a sunday, return the next week
if (date.DayOfWeek == DayOfWeek.Sunday) date = date.AddDays(1);
return WeekOfYear.DateToWeekOfYear(date);
}
public UsWeekOfYear(int year, int week) : base(year, week)
{
StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday).AddDays(-1);
EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddTicks(-1);
}
public UsWeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
public UsWeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}
Here is some test code:
public static void Main(string[] args)
{
Console.WriteLine("== Last Week / First Week");
Log(new WeekOfYear(2020, 53));
Log(new UsWeekOfYear(2020, 53));
Log(new WeekOfYear(2021, 1));
Log(new UsWeekOfYear(2021, 1));
Console.WriteLine("\n== Year Crossover (iso)");
var start = new DateTime(2020, 12, 26);
var i = 0;
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed
Console.WriteLine("\n== Year Crossover (us)");
i = 0;
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed
var x = new UsWeekOfYear(2020, 53) as WeekOfYear;
}
public static void Log(WeekOfYear week)
{
Console.WriteLine($"{week} - {week.StartOfWeek:yyyy-MM-dd} ({week.StartOfWeek:ddd}) - {week.EndOfWeek:yyyy-MM-dd} ({week.EndOfWeek:ddd})");
}
public static void Log(DateTime date, WeekOfYear week)
{
Console.WriteLine($"{date:yyyy-MM-dd (ddd)} - {week} - {week.StartOfWeek:yyyy-MM-dd (ddd)} - {week.EndOfWeek:yyyy-MM-dd (ddd)}");
}
<%: Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @autocomplete = "off", @readonly=true})%>
This is how you set multiple properties
You just need to wrap it around a String object like this:
String numberString = String(n);
You can also do:
String stringOne = "Hello String"; // using a constant String
String stringOne = String('a'); // converting a constant char into a String
String stringTwo = String("This is a string"); // converting a constant string into a String object
String stringOne = String(stringTwo + " with more"); // concatenating two strings
String stringOne = String(13); // using a constant integer
String stringOne = String(analogRead(0), DEC); // using an int and a base
String stringOne = String(45, HEX); // using an int and a base (hexadecimal)
String stringOne = String(255, BIN); // using an int and a base (binary)
String stringOne = String(millis(), DEC); // using a long and a base
best way is to use Java7: Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
public void saveDataInFile(String data) throws IOException {
Path path = Paths.get(fileName);
byte[] strToBytes = data.getBytes();
Files.write(path, strToBytes);
}
Write with FileChannel If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
public void saveDataInFile(String data)
throws IOException {
RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
FileChannel channel = stream.getChannel();
byte[] strBytes = data.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
Write with DataOutputStream
public void saveDataInFile(String data) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(data);
outStream.close();
}
Write with FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a FileOutputStream:
public void saveDataInFile(String data) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = data.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Write with PrintWriter we can use a PrintWriter to write formatted text to a file:
public void saveDataInFile() throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Write with BufferedWriter: use BufferedWriter to write a String to a new file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
append a String to the existing file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
Here's a good way using :after on the image div, instead of the extra overlay div: http://jsfiddle.net/Zf5am/576/
<div class="image">
<img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>
.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}
I was in such situation .. and found This:
int ColumnIndex = DataGrid.CurrentColumn.DisplayIndex;
TextBlock CellContent = DataGrid.SelectedCells[ColumnIndex].Column.GetCellContent(DataGrid.SelectedItem);
And make sure to treat custom columns' templates
Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.
i also had this problem and didnt wanted to use deprecated solution so i ended up with:
in parrent
<dynamic-table
ContainerCustomStyle='width: 400px;'
>
</dynamic-Table>
child component
@Input() ContainerCustomStyle: string;
in child in html div
<div class="container mat-elevation-z8"
[style]='GetStyle(ContainerCustomStyle)' >
and in code
constructor(private sanitizer: DomSanitizer) { }
GetStyle(c) {
if (isNullOrUndefined(c)) { return null; }
return this.sanitizer.bypassSecurityTrustStyle(c);
}
works like expected and should not be deprecated ;)
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
They need to be percent-encoded:
> encodeURIComponent('&')
"%26"
So in your case, the URL would look like:
http://www.mysite.com?candy_name=M%26M
Check some typo ','
<?php
//file_get_content(url);
$jsonD = '{
"bpath":"http://www.sampledomain.com/",
"clist":[{
"cid":"11",
"display_type":"grid",
"ctitle":"abc",
"acount":"71",
"alist":[{
"aid":"6865",
"adate":"2 Hours ago",
"atitle":"test",
"adesc":"test desc",
"aimg":"",
"aurl":"?nid=6865",
"weburl":"news.php?nid=6865",
"cmtcount":"0"
},
{
"aid":"6857",
"adate":"20 Hours ago",
"atitle":"test1",
"adesc":"test desc1",
"aimg":"",
"aurl":"?nid=6857",
"weburl":"news.php?nid=6857",
"cmtcount":"0"
}
]
},
{
"cid":"1",
"display_type":"grid",
"ctitle":"test1",
"acount":"2354",
"alist":[{
"aid":"6851",
"adate":"1 Days ago",
"atitle":"test123",
"adesc":"test123 desc",
"aimg":"",
"aurl":"?nid=6851",
"weburl":"news.php?nid=6851",
"cmtcount":"7"
},
{
"aid":"6847",
"adate":"2 Days ago",
"atitle":"test12345",
"adesc":"test12345 desc",
"aimg":"",
"aurl":"?nid=6847",
"weburl":"news.php?nid=6847",
"cmtcount":"7"
}
]
}
]
}
';
$parseJ = json_decode($jsonD,true);
print_r($parseJ);
?>
The user's IP address can be retrieved using the following snippet:
from flask import request
print(request.remote_addr)
That feature is called a common table expression http://msdn.microsoft.com/en-us/library/ms190766.aspx
You won't be able to do the exact thing in mySQL, the easiest thing would to probably make a view that mirrors that CTE and just select from the view. You can do it with subqueries, but that will perform really poorly. If you run into any CTEs that do recursion, I don't know how you'd be able to recreate that without using stored procedures.
EDIT: As I said in my comment, that example you posted has no need for a CTE, so you must have simplified it for the question since it can be just written as
SELECT article.*, userinfo.*, category.* FROM question
INNER JOIN userinfo ON userinfo.user_userid=article.article_ownerid
INNER JOIN category ON article.article_categoryid=category.catid
WHERE article.article_isdeleted = 0
ORDER BY article_date DESC Limit 1, 3
Each control deriving from Panel
implements distinct layout logic performed in Measure()
and Arrange()
:
Measure()
determines the size of the panel and each of its childrenArrange()
determines the rectangle where each control rendersThe last child of the DockPanel
fills the remaining space. You can disable this behavior by setting the LastChild
property to false
.
The StackPanel
asks each child for its desired size and then stacks them. The stack panel calls Measure()
on each child, with an available size of Infinity
and then uses the child's desired size.
A Grid
occupies all available space, however, it will set each child to their desired size and then center them in the cell.
You can implement your own layout logic by deriving from Panel
and then overriding MeasureOverride()
and ArrangeOverride()
.
See this article for a simple example.
Or, if spacing is not the problem, it might want the parent directory name rather than the file name.
Not $ dev_appserver helloapp.py
But $ dev_appserver hello/
For example:
Johns-Mac:hello john$ dev_appserver.py helloworld.py
Traceback (most recent call last):
File "/usr/local/bin/dev_appserver.py", line 82, in <module>
_run_file(__file__, globals())
...
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/yaml_listener.py", line 212, in _GenerateEventParameters
raise yaml_errors.EventListenerYAMLError(e)
google.appengine.api.yaml_errors.EventListenerYAMLError: mapping values are not allowed here
in "helloworld.py", line 3, column 39
Versus
Johns-Mac:hello john$ cd ..
Johns-Mac:fbm john$ dev_appserver.py hello/
INFO 2014-09-15 11:44:27,828 api_server.py:171] Starting API server at: http://localhost:61049
INFO 2014-09-15 11:44:27,831 dispatcher.py:183] Starting module "default" running at: http://localhost:8080
//here is how to do it in Windows App.Config
public static bool ChangeConnectionString(string Name, string value, string providerName, string AppName)
{
bool retVal = false;
try
{
string FILE_NAME = string.Concat(Application.StartupPath, "\\", AppName.Trim(), ".exe.Config"); //the application configuration file name
XmlTextReader reader = new XmlTextReader(FILE_NAME);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
string nodeRoute = string.Concat("connectionStrings/add");
XmlNode cnnStr = null;
XmlElement root = doc.DocumentElement;
XmlNodeList Settings = root.SelectNodes(nodeRoute);
for (int i = 0; i < Settings.Count; i++)
{
cnnStr = Settings[i];
if (cnnStr.Attributes["name"].Value.Equals(Name))
break;
cnnStr = null;
}
cnnStr.Attributes["connectionString"].Value = value;
cnnStr.Attributes["providerName"].Value = providerName;
doc.Save(FILE_NAME);
retVal = true;
}
catch (Exception ex)
{
retVal = false;
//Handle the Exception as you like
}
return retVal;
}
from traceback import format_exc
try:
fault = 10/0
except ZeroDivision:
print(format_exc())
Another possibility is to use the format_exc() method from the traceback module.
An alterntive is to use an enum and a component class that extends the standard RadioButton.
public enum Genders
{
Male,
Female
}
[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
public GenderRadioButton()
{
InitializeComponent();
}
public GenderRadioButton (IContainer container)
{
container.Add(this);
InitializeComponent();
}
public Genders gender{ get; set; }
}
Use a common event handler for the GenderRadioButtons
private void Gender_CheckedChanged(Object sender, EventArgs e)
{
if (((RadioButton)sender).Checked)
{
//get selected value
Genders myGender = ((GenderRadioButton)sender).Gender;
//get the name of the enum value
string GenderName = Enum.GetName(typeof(Genders ), myGender);
//do any work required when you change gender
switch (myGender)
{
case Genders.Male:
break;
case Genders.Female:
break;
default:
break;
}
}
}
I've discovered that if the filename has 300
in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT
error.
If you don't want to use custom views or special layouts, you can use 9-patch to make the (X) button .
Example: http://postimg.org/image/tssjmt97p/ (I don't have enough points to post images on StackOverflow)
The intersection of the right and bottom black pixels represent the content area. Anything outside of that area is padding. So to detect that the user clicked on the x you can set a OnTouchListener like so:
editText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP){
if (motionEvent.getX()>(view.getWidth()-view.getPaddingRight())){
((EditText)view).setText("");
}
}
return false;
}
});
According to your needs this solution can work better in some cases. I prefer to keep my xml less complicated. This also helps if you want to have an icon on the left, as you can simply include it in the 9 patch.
Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.
This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.
So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.
Select T.Tamil, T.English, T.Maths, T.Total, Dense_Rank()Over(Order by T.Total Desc) as Std_Rank From (select Tamil,English,Maths,(Tamil+English+Maths) as Total From Student) as T
As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.
The Problem is with your code formatting,
inorder to use strtotime()
You should replace '06/Oct/2011:19:00:02'
with 06/10/2011 19:00:02
and date('d/M/Y:H:i:s', $date);
with date('d/M/Y H:i:s', $date);
. Note the spaces in between.
So the final code looks like this
$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);
If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).
An example of a FIRST/FIRST conflict:
S -> Xb | Yc
X -> a
Y -> a
By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.
An example of a FIRST/FOLLOW conflict:
S -> AB
A -> fe | epsilon
B -> fg
By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).
Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.
Using this in combination with Laravel solved my problem. Just add this header to your jquery request Access-Control-Request-Headers: x-requested-with
and make sure that your server side response has this header set Access-Control-Allow-Headers: *
.
You can use the BytesIO
class to get a wrapper around strings that behaves like a file. The BytesIO
object provides the same interface as a file, but saves the contents just in memory:
import io
with io.BytesIO() as output:
image.save(output, format="GIF")
contents = output.getvalue()
You have to explicitly specify the output format with the format
parameter, otherwise PIL will raise an error when trying to automatically detect it.
If you loaded the image from a file it has a format
parameter that contains the original file format, so in this case you can use format=image.format
.
In old Python 2 versions before introduction of the io
module you would have used the StringIO
module instead.
java android
in my case
I want to change from
~/propic/........png
anything after /propic/ doesn't matter what before it
........png
finally, I found the code in Class StringUtils
this is the code
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return "";
}
final int pos = str.indexOf(separator);
if (pos == 0) {
return str;
}
return str.substring(pos + separator.length());
}
try this selector -
$("tr").find("td:first")
Demo -->
http://jsfiddle.net/66HbV/
Or
$("tr td:first-child")
Demo -->
http://jsfiddle.net/66HbV/1/
</td>foobar</td>
should be <td>foobar</td>
I don't think your going to get valueOf("Start Here") to work. But as far as spaces...try the following...
static private enum RandomEnum {
R("Start There"),
G("Start Here");
String value;
RandomEnum(String s) {
value = s;
}
}
System.out.println(RandomEnum.G.value);
System.out.println(RandomEnum.valueOf("G").value);
Start Here
Start Here