If the class uses as a parameterized type, it can declare an array of type T[], but it cannot directly instantiate such an array. Instead, a common approach is to instantiate an array of type Object[], and then make a narrowing cast to type T[], as shown in the following:
public class Portfolio<T> {
T[] data;
public Portfolio(int capacity) {
data = new T[capacity]; // illegal; compiler error
data = (T[]) new Object[capacity]; // legal, but compiler warning
}
public T get(int index) { return data[index]; }
public void set(int index, T element) { data[index] = element; }
}
from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
Gonna answer in opposite direction.
2) For a full explanation about \r
and \n
I have to refer to this question, which is far more complete than I will post here: Difference between \n and \r?
Long story short, Linux uses \n
for a new-line, Windows \r\n
and old Macs \r
. So there are multiple ways to write a newline. Your second tool (RegExr) does for example match on the single \r
.
1) [\r\n]+
as Ilya suggested will work, but will also match multiple consecutive new-lines. (\r\n|\r|\n)
is more correct.
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim()
then trim the inside spaces using .replace(/\s+/g, ' ')
.
Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
Are you using smart pointers such as Boost shared_ptr
? If so, check if you are directly using the raw pointer anywhere by calling get()
. I've found this to be quite a common problem.
For example, imagine a scenario where a raw pointer is passed (maybe as a callback handler, say) to your code. You might decide to assign this to a smart pointer in order to cope with reference counting etc. Big mistake: your code doesn't own this pointer unless you take a deep copy. When your code is done with the smart pointer it will destroy it and attempt to destroy the memory it points to since it thinks that no-one else needs it, but the calling code will then try to delete it and you'll get a double free problem.
Of course, that might not be your problem here. At it's simplest here's an example which shows how it can happen. The first delete is fine but the compiler senses that it's already deleted that memory and causes a problem. That's why assigning 0 to a pointer immediately after deletion is a good idea.
int main(int argc, char* argv[])
{
char* ptr = new char[20];
delete[] ptr;
ptr = 0; // Comment me out and watch me crash and burn.
delete[] ptr;
}
Edit: changed delete
to delete[]
, as ptr is an array of char.
Well I couldn't find a Django way, but I did find a python way from inside my model:
def format_price(self):
import locale
locale.setlocale(locale.LC_ALL, '')
return locale.format('%d', self.price, True)
Try using the ToDictionary
method like so:
var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );
You could ask your fiendly Confluence administrator to create a macro for you. Here is an example of a macro for Confluence 3.x
Macro Name: inlinecode
Macro Title: Markup text like stackoverflow inline code
Categories: Formatting
Macro Body Processing: Convert wiki markup to HTML
Output Format: HTML
Template:
## Macro title: Inline Code
## Macro has a body: Y
## Body processing: Convert wiki markup to HTML
## Output: HTML
##
## Developed by: My Name
## Date created: dd/mm/yyyy
## Installed by: My Name
## This makes the body text look like inline code markup from stackoverflow
## @noparams
<span style="padding: 1px 5px 1px 5px; font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif; background-color: #eeeeee;">$body</span>
Then users can use {inlinecode}like this{inlinecode}
You could also use the {html}
or {style}
macros if they are installed or add this style to the stylesheet for your space.
While you are at it ask your Confluence admin to create a kbd macro for you. Same as the above, except Macro name
is kbd and Template
is:
<span style="padding: 0.1em 0.6em;border: 1px solid #ccc; font-size: 11px; font-family: Arial,Helvetica,sans-serif; background-color: #f7f7f7; color: #333; -moz-box-shadow: 0 1px 0px rgba(0, 0, 0, 0.2),0 0 0 2px #ffffff inset; -webkit-box-shadow: 0 1px 0px rgba(0, 0, 0, 0.2),0 0 0 2px #ffffff inset; box-shadow: 0 1px 0px rgba(0, 0, 0, 0.2),0 0 0 2px #ffffff inset; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; display: inline-block; margin: 0 0.1em; text-shadow: 0 1px 0 #fff; line-height: 1.4; white-space: nowrap; ">$body</span>
Then you can write documentation to tell users to hit the F1 and Enter keys.
Point 1: Add require()
function calling line of code only in the app.js
file or main.js
file.
Point 2: Make sure the required package is installed by checking the pacakage.json
file. If not updated, run "npm i".
You would want to amend the commit and then do a force push which will update the branch with the PR.
Here's how I recommend you do this:
git reset --soft HEAD^
or if it's a different commit, you would want to replace 'HEAD^' with the commit id)git commit -a -c ORIG_HEAD
The now that your branch has been updated, the Pull Request will include your changes.
Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.
Clear improperly cached compile errors.
All Projects Locations in Eclipse
workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\
color="white"
is not a known attribute to Angular Material.
color attribute can changed to primary
, accent
, and warn
. as said in this doc
your icon inside button works because its parent class button has css class of color:white
, or may be your color="accent"
is white. check the developer tools to find it.
By default, icons will use the current font color
Still amazed that none recommended the guava library for this.
//Sample taken from a current working project of mine just to illustrate the idea
@Override
public int hashCode(){
return Objects.hashCode(this.getDate(), this.datePattern);
}
@Override
public boolean equals(Object obj){
if ( ! obj instanceof DateAndPattern ) {
return false;
}
return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())
&& Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());
}
I tried with this method and it significantly reduced my database insert execution time.
List<string> toinsert = new List<string>();
StringBuilder insertCmd = new StringBuilder("INSERT INTO tabblename (col1, col2, col3) VALUES ");
foreach (var row in rows)
{
// the point here is to keep values quoted and avoid SQL injection
var first = row.First.Replace("'", "''")
var second = row.Second.Replace("'", "''")
var third = row.Third.Replace("'", "''")
toinsert.Add(string.Format("( '{0}', '{1}', '{2}' )", first, second, third));
}
if (toinsert.Count != 0)
{
insertCmd.Append(string.Join(",", toinsert));
insertCmd.Append(";");
}
using (MySqlCommand myCmd = new MySqlCommand(insertCmd.ToString(), SQLconnectionObject))
{
myCmd.CommandType = CommandType.Text;
myCmd.ExecuteNonQuery();
}
*Create SQL connection object and replace it where I have written SQLconnectionObject.
Important Android Studio Shortcuts You Need the Most
Navigation Shortcuts
Go to class : CTRL + N
Go to file : CTRL + SHIFT + N
Navigate open tabs : ALT + Left-Arrow; ALT + Right-Arrow
Lookup recent files : CTRL + E
Go to line : CTRL + G
Navigate to last edit location : CTRL + SHIFT + BACKSPACE
Go to declaration : CTRL + B
Go to implementation : CTRL + ALT + B
Go to source : F4
Go to super Class : CTRL + U
Show Call hierarchy : CTRL + ALT + H
Search in path/project : CTRL + SHIFT + F
Programming Shortcuts
Reformat code : CTRL + ALT + L
Optimize imports : CTRL + ALT + O
Code Completion : CTRL + SPACE
Issue quick fix : ALT + ENTER
Surround code block : CTRL + ALT + T
Rename and refactor : SHIFT + F6
Line Comment or Uncomment : CTRL + /
Block Comment or Uncomment : CTRL + SHIFT + /
Go to previous/next method : ALT + UP/DOWN
Show parameters for method : CTRL + P
Quick documentation lookup : CTRL + Q
General Shortcuts
Delete line : CTRL + Y
Safe Delete : ALT + DELETE
Close Active Tab : CTRL + F4
Build and run : SHIFT + F10
Build : CTRL + F9
All purpose (Meta)Shortcut : CTRL + SHIFT + A
compare
has overloads for comparing substrings. If you're comparing whole strings you should just use ==
operator (and whether it calls compare
or not is pretty much irrelevant).
You need to do this on each word after you split
into an array
of words.
public String reverse(String word) {
char[] chs = word.toCharArray();
int i=0, j=chs.length-1;
while (i < j) {
// swap chs[i] and chs[j]
char t = chs[i];
chs[i] = chs[j];
chs[j] = t;
i++; j--;
}
return String.valueOf(chs);
}
Switch the alloc type:
GCHandle handle = GCHandle.Alloc(a, GCHandleType.Normal);
Javascript is flexible:
var arr = {
"fred": {"apple": 2, "orange": 4},
"mary": {}
//etc, etc
};
alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
alert(key + ": " + arr.fred[key]);
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
Slightly similar to one of examples here, simplified from std::map
usage perspective.
template<class KEY, class VALUE>
std::vector<KEY> getKeys(const std::map<KEY, VALUE>& map)
{
std::vector<KEY> keys(map.size());
for (const auto& it : map)
keys.push_back(it.first);
return keys;
}
Use like this:
auto keys = getKeys(yourMap);
It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
pno (*AddClient)(client_t *);
};
pno client_t_AddClient(client_t *self) { /* code */ }
int main()
{
client_t client;
client.AddClient = client_t_AddClient; // probably really done in some init fn
//code ..
client.AddClient(&client);
}
It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.
If it's about just one property - let's say you want to temporarily change some default, for instance disable CA checking: you can do it with
npm config set ca ""
To come back to the defaults for that setting, simply
npm config delete ca
To verify, use npm config get ca
.
THE C WAY
You can use gets
function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets
is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream
itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
NewScores is an alias to Scores table - it looks like you can combine the queries as follows:
SELECT
ROW_NUMBER() OVER( ORDER BY NETT) AS Rank,
Name,
FlagImg,
Nett,
Rounds
FROM (
SELECT
Members.FirstName + ' ' + Members.LastName AS Name,
CASE
WHEN MenuCountry.ImgURL IS NULL THEN
'~/images/flags/ismygolf.png'
ELSE
MenuCountry.ImgURL
END AS FlagImg,
AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett,
COUNT(Score.ScoreID) AS Rounds
FROM
Members
INNER JOIN
Score NewScores
ON Members.MemberID = NewScores.MemberID
LEFT OUTER JOIN MenuCountry
ON Members.Country = MenuCountry.ID
WHERE
Members.Status = 1
AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
GROUP BY
Members.FirstName + ' ' + Members.LastName,
MenuCountry.ImgURL
) AS Dertbl
ORDER BY;
<head>
<title>Site</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
etc...
</head>
I've used that very recently and it works fine on iPad. Haven't tested on Android or other devices (because the website will be displayed on iPad only).
We use WinSCP. Its free. Its not a lib, but has a well documented and full featured command line interface that you can use with Process.Start.
Update: with v.5.0, WinSCP has a .NET wrapper library to the scripting layer of WinSCP.
The C gets function is dangerous and has been a very costly mistake. Tony Hoare singles it out for specific mention in his talk "Null References: The Billion Dollar Mistake":
http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare
The whole hour is worth watching but for his comments view from 30 minutes on with the specific gets criticism around 39 minutes.
Hopefully this whets your appetite for the whole talk, which draws attention to how we need more formal correctness proofs in languages and how language designers should be blamed for the mistakes in their languages, not the programmer. This seems to have been the whole dubious reason for designers of bad languages to push the blame to programmers in the guise of 'programmer freedom'.
The default constructor for std::string always returns an object that is set to a null string.
I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:
I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit
or /usr/bin/time
result from each of several methods of checksumming a file of approx. 11MB:
$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f /tmp/test.data.300k
real 0m0.043s
user 0m0.032s
sys 0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400
So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum
function (md5sum_read
in the above listing) is pretty similar to Omnifarious's:
import hashlib
def md5sum(filename, blocksize=65536):
hash = hashlib.md5()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash.update(block)
return hash.hexdigest()
Granted, these are from single runs (the mmap
ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize)
after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum
on the command line is not necessarily faster than a Python implementation...
EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32()
call:
import zlib
def adler32sum(filename, blocksize=65536):
checksum = zlib.adler32("")
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
checksum = zlib.adler32(block, checksum)
return checksum & 0xffffffff
Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for ""
, which is 1
-- CRC can start with 0
instead. The AND
-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.
You have to hide the column at the grid view control rather than at the data source. Hiding it at the data source it will not render to the grid view at all, therefore you won't be able to access the value in the grid view. Doing it the way you're suggesting, you would have to access the column value through the data source as opposed to the grid view.
To hide the column on the grid view control, you can use code like this:
dataGridView1.Columns[0].Visible = false;
To access the column from the data source, you could try something like this:
object colValue = ((DataTable)dataGridView.DataSource).Rows[dataSetIndex]["ColumnName"];
You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.
(It's the same as when you say int n = 10;
: There are no dynamic resources involved that you have to manage manually.)
Interesting idea. Some searching on Google produced a few pages of interest, including:
Hope this helps.
The following is running code:
SELECT abnno, COUNT(abnno)
FROM tbl_Name
GROUP BY abnno
HAVING ( COUNT(abnno) > 1 )
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
Also relevant, but specially to excel, look at this answer and this other one that suggests, inserting a line at the beginning of the CSV with
"sep=,"
To inform excel which separator to expect
Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode
in PHP), or are you building the JSON string by hand?
The only thing that grabs my attention is the escape apostrophe (\'
). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
$.inArray
returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is
if(jQuery.inArray("test", myarray) != -1) {
console.log("is in array");
} else {
console.log("is NOT in array");
}
There are multiple ways to do so, but Oracle and IBM say that using +
, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder
or StringBuffer
is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer
.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types. The two tables was also different storage engines.
One column was a CHAR (90) and the other was a BIGINT (20).
One table was InnoDB and the other was MEMORY.
Part of query:
[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );
Changing the column type on the one column from BIGINT to CHAR solved the issue.
If your web server is running php5, I believe you must use php5_value
. This resolved the same error I received when using php_value
.
I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:
CAST(YourValueHere as smalldatetime);
For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.
below is undocumented and not recomended by oracle. and can not apply in function, show error
select wm_concat(distinct name) as names from demotable group by group_id
regards zia
Settings ->
Preference ->
Edit Components (tab) ->
Tab Setting (group) ->
Replace by space
In version 5.6.8 (and above):
Settings ->
Preferences... ->
Language Menu/Tab Settings ->
Tab Settings (group) ->
Replace by space
How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?
If you right click on your project and choose build path->configure
build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime
. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes
try
$this->load->view('home/home_view',$data);
instead of this:
$this->load->view(‘home\home_view’,$data);
Depending on what you mean by "use them as Strings", you might not want to use an enum here. In most cases, the solution proposed by The Elite Gentleman will allow you to use them through their toString-methods, e.g. in System.out.println(STRING_ONE)
or String s = "Hello "+STRING_TWO
, but when you really need Strings (e.g. STRING_ONE.toLowerCase()
), you might prefer defining them as constants:
public interface Strings{
public static final String STRING_ONE = "ONE";
public static final String STRING_TWO = "TWO";
}
You can pipe the output of type
into find
inside the in(…)
clause of a for /f
loop:
for /f %%A in ('
type "%~dpf1" ^| find /c /v ""
') do set "lineCount=%%A"
But the pipe starts a subshell, which slows things down.
Or, you could redirect input from the file into find
like so:
for /f %%A in ('
find /c /v "" ^< "%~dpf1"
') do set "lineCount=%%A"
But this approach will give you an answer 1 less than the actual number of lines if the file ends with one or more blank lines, as teased out by the late foxidrive in counting lines in a file.
And then again, you could always try:
find /c /v "" example.txt
The trouble is, the output from the above command looks like this:
---------- EXAMPLE.TXT: 511
You could split the string on the colon to get the count, but there might be more than one colon if the filename had a full path.
Here’s my take on that problem:
for /f "delims=" %%A in ('
find /c /v "" "%~1"
') do for %%B in (%%A) do set "lineCount=%%B"
This will always store the count in the variable.
Just one last little problem… find
treats null characters as newlines. So if sneaky nulls crept into your text file, or if you want to count the lines in a Unicode file, this answer isn’t for you.
IN WORDPRESS:
global $wpdb; $table_name=$wpdb->prefix.'posts';
foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
var_dump( $column_name );
}
Remove the <br>
from the .navcontainer-top li
styles.
Check if the deployment target in the General section of the project settings, is greater than that of your device's iOS version.
If yes then you need to update the version of your device to at least the deployment target version. in order for you to be able to install the application on your device.
git branch --merged master
lists branches merged into master
git branch --merged
lists branches merged into HEAD (i.e. tip of current branch)
git branch --no-merged
lists branches that have not been merged
By default this applies to only the local branches. The -a
flag will show both local and remote branches, and the -r
flag shows only the remote branches.
This question is more dificult to answer than seems at first sight. If you want to deal with emails correctly.
There were loads of people around the world looking for "the regex to rule them all" but the truth is that there are tones of email providers.
What's the problem? Well, "a_z%@gmail.com cannot exists but it may exists an address like that through another provider "[email protected].
Why? According to the RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification.
I'll take an excerpt to facilitate the lecture:
The local-part of the email address may use any of these ASCII characters:
- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but "John..Doe"@example.com is allowed);[6]
Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected].
So, i can own an email address like that:
A__z/J0hn.sm{it!}[email protected]
If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.
Imagine my frustration at not being able to register anywhere checked with those regex!!
The only one who really can validate an email address is the provider of the email address.
How to deal with, so?
It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type="email" that is running near to RFC, little chance to fail. HTML5 input type="email" info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html
For example, this is an RFC valid email:
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
But the html5 validation will tell you that the text before @ must not contain " or () chars for example, which is actually incorrect.
Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.
A good practice while doing this is the "enter your e-mail again" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title "is this your current e-mail?", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a "yes, submit" button.
This is all nicely lined up including the field label. Lining up the field label was the tricky part.
<div class="form-group">
<label class="control-label col-md-5">Create a</label>
<div class="col-md-7">
<label class="radio-inline control-label">
<input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
</label>
<label class="radio-inline control-label">
<input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
</label>
</div>
</div>
<div class="form-group">
@Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
<div class="col-md-7">
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
</label>
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
</label>
</div>
</div>
If you are able to get your hands on date-fns
library v2+, you can import the function addMonths
, and use that to get the next month
<script type="module">
import { addMonths } from 'https://cdn.jsdelivr.net/npm/date-fns/+esm';
const current = new Date();
const nextMonth = addMonths(current, 1);
console.log(`Next month is ${nextMonth}`);
</script>
_x000D_
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
From your terminal, do this:
git fetch
git tags
git tag -d {tag-name}
git push origin :refs/tags/{tag-name}
Now go to Github.com and refresh, they disappear.
Concise and memory efficient:
#!/usr/bin/env python
# file: grep.py
import re, sys
map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))
It works like egrep (without too much error handling), e.g.:
cat input-file | grep.py "RE"
And here is the one-liner:
cat input-file | python -c "import re,sys;map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))" "RE"
I've also had this problem recently.
The solution that worked for me was to uninstall vmware, restart windows, and the reinstall vmware.
Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.
Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode()
. The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv()
or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)
Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.
Either way, notify your data provider that they're sending invalid data so that they can fix it.
Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.
function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}
function utf8_encode_callback($m)
{
return utf8_encode($m[0]);
}
Yes, the sorting is different.
Items in the ORDER BY
list are applied in order.
Later items only order peers left from the preceding step.
Why don't you just try?
Have a look at Listamatic. Tabs are semantically just a list of items styled in a particular way. You don't even necessarily need javascript to make vertical tabs work as the various examples at Listamatic show.
Here is the generic solution I use. It solves the problem for importing from modules in the same folder:
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
Put this at top of the module which gives the error "No module named xxxx"
It is a hard question in the C/C++ world, with so many elements beyond the standard.
I think header file order is not a serious problem as long as it compiles, like squelart said.
My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.
The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.
For example, in stddef.h in VS2005, there is:
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof
in their system headers, I should write in my header:
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
And be sure to tell the user to #include "custom.h"
after all system headers, otherwise, the line of offsetof
in stddef.h will assert a macro redefinition error.
We pray not to meet any more of such cases in our career.
The target. dot works on objects; arrow works on pointers to objects.
std::string str("foo");
std::string * pstr = new std::string("foo");
str.size ();
pstr->size ();
According to the jQuery documentation, shorthand CSS properties are not supported.
Depending on what you mean by "total padding", you may be able to do something like this:
var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');
I'm fairly certain that the ls
command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd
, which is the command line for the Windows OS).
You should use dir
instead, which is the Windows equivalent of ls
.
Edit (since this post seems to be getting so many views :) ):
You can't use ls
on cmd
as it's not shipped with Windows
, but you can use it on other terminal programs (such as GitBash). Note, ls
might work on some FTP
servers if the servers are linux
based and the FTP
is being used from cmd
.
dir
on Windows
is similar to ls
. To find out the various options available, just do dir/?
.
If you really want to use ls
, you could install 3rd party tools to allow you to run unix
commands on Windows
. Such a program is Microsoft Windows Subsystem for Linux
(link to docs).
Simply use JS toLowerCase()
let v = "Your Name"
let u = v.toLowerCase();
or
let u = "Your Name".toLowerCase();
For OpenSuse Linux, One can simply install the java-binfmt package in the zypper repository as shown below:
sudo zypper in java-binfmt-misc
chmod 755 file.jar
./file.jar
Here's a bit of script I use for testing if a server is 2005 or later
declare @isSqlServer2005 bit
select @isSqlServer2005 = case when CONVERT(int, SUBSTRING(CONVERT(varchar(15), SERVERPROPERTY('productversion')), 0, CHARINDEX('.', CONVERT(varchar(15), SERVERPROPERTY('productversion'))))) < 9 then 0 else 1 end
select @isSqlServer2005
Note : updated from original answer (see comment)
You can use the following stored procedure to fetch , values.
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[sp_parsedata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_parsedata]
GO
create procedure sp_parsedata
(@cid integer,@st varchar(1000))
as
declare @coid integer
declare @c integer
declare @c1 integer
select @c1=len(@st) - len(replace(@st, ',', ''))
set @c=0
delete from table1 where complainid=@cid;
while (@c<=@c1)
begin
if (@c<@c1)
begin
select @coid=cast(replace(left(@st,CHARINDEX(',',@st,1)),',','') as integer)
select @st=SUBSTRING(@st,CHARINDEX(',',@st,1)+1,LEN(@st))
end
else
begin
select @coid=cast(@st as integer)
end
insert into table1(complainid,courtid) values(@cid,@coid)
set @c=@c+1
end
You can use theme_get()
to display the possible options for theme.
You can control the legend font size using:
+ theme(legend.text=element_text(size=X))
replacing X with the desired size.
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
Using Erik's answer, as a starting point. I found a simpler solution that worked for me.
In my ng-click function I have:
var the_string = 'lifeMeaning';
if ($scope[the_string] === undefined) {
//Valid in my application for first usage
$scope[the_string] = true;
} else {
$scope[the_string] = !$scope[the_string];
}
//$scope.$apply
I've tested it with and without $scope.$apply. Works correctly without it!
Check your buffer id using :buffers
you will see list of buffers there like
1 a.php
2 b.php
3 c.php
if you want to remove b.php from buffer
:2bw
if you want to remove/close all from buffers
:1,3bw
The reason why there is no ConcurrentList is because it fundamentally cannot be written. The reason why is that several important operations in IList rely on indices, and that just plain won't work. For example:
int catIndex = list.IndexOf("cat");
list.Insert(catIndex, "dog");
The effect that the author is going after is to insert "dog" before "cat", but in a multithreaded environment, anything can happen to the list between those two lines of code. For example, another thread might do list.RemoveAt(0)
, shifting the entire list to the left, but crucially, catIndex will not change. The impact here is that the Insert
operation will actually put the "dog" after the cat, not before it.
The several implementations that you see offered as "answers" to this question are well-meaning, but as the above shows, they don't offer reliable results. If you really want list-like semantics in a multithreaded environment, you can't get there by putting locks inside the list implementation methods. You have to ensure that any index you use lives entirely inside the context of the lock. The upshot is that you can use a List in a multithreaded environment with the right locking, but the list itself cannot be made to exist in that world.
If you think you need a concurrent list, there are really just two possibilities:
If you have a ConcurrentBag and are in a position where you need to pass it as an IList, then you have a problem, because the method you're calling has specified that they might try to do something like I did above with the cat & dog. In most worlds, what that means is that the method you're calling is simply not built to work in a multi-threaded environment. That means you either refactor it so that it is or, if you can't, you're going to have to handle it very carefully. You you'll almost certainly be required to create your own collection with its own locks, and call the offending method within a lock.
Try this until a non-no answer appears:
function parent() {
this.child;
interestingProperty = "5";
...
}
function child() {
this.parent;
...
}
a = new parent();
a.child = new child();
a.child.parent = a; // this gives the child a reference to its parent
alert(a.interestingProperty+" === "+a.child.parent.interestingProperty);
Sticky session means to route the requests of particular session to the same physical machine who served the first request for that session.
A php/ajax progress bar can be done. (Checkout the Html_Ajax library in pear). However this requires installing a custom module into php.
Other methods require using an iframe, through which php looks to see how much of the file has been uploaded. However this hidden iframe, may be blocked by some browsers addons because hidden iframes are often used to send malicious data to a users computer.
Your best bet is to use some form of flash progress bar if you do not have control over your server.
using angularjs:
$timeout(function(){
if(yourvariable===-1){
doSomeThingAfter5Seconds();
}
},5000)
In general one could,
merge_list <- function(...) by(v<-unlist(c(...)),names(v),base::c)
Note that the by()
solution returns an attribute
d list, so it will print differently, but will still be a list. But you can get rid of the attributes with attr(x,"_attribute.name_")<-NULL
. You can probably also use aggregate()
.
Happy coding!
If you get an error on Internet Explorer, Change the security settings to allow ActiveX
var CallBackFunction = function(content) {
alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction) {
try {
var file = FileElement.files[0];
var contents_ = "";
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function(evt) {
CallBackFunction(evt.target.result);
}
reader.onerror = function(evt) {
alert("Error reading file");
}
}
} catch (Exception) {
var fall_back = ieReadFile(FileElement.value);
if (fall_back != false) {
CallBackFunction(fall_back);
}
}
}
///Reading files with Internet Explorer
function ieReadFile(filename) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(filename, 1);
var contents = fh.ReadAll();
fh.Close();
return contents;
} catch (Exception) {
alert(Exception);
return false;
}
}
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl();
is toDataURL();
and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.
Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.
I had the same issue displaying my side navigation panel height to 100%.
My steps to fix it was to:
In the index.css file ------
.html {
height: 100%;
}
.body {
height:100%;
}
In the sidePanel.css (this was giving me issues):
.side-panel {
height: 100%;
position: fixed; <--- this is what made the difference and scaled to 100% correctly
}
Other attributes were taken out for clarity, but I think the issue lies with scaling the height to 100% in nested containers like how you are trying to scale height in your nested containers. The parent classes height will need to be applied the 100%. - What i'm curious about is why fixed: position corrects the scale and fails without it; this is something i'll learn eventually with some more practice.
I've been working with react for a week now and i'm a novice to web developing, but I wanted to share a fix that I discovered with scaling height to 100%; I hope this helps you or anyone who has a similar issue. Good luck!
BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);
20
Add a try/catch block, if the transaction succeeds it will commit the changes, if the transaction fails the transaction is rolled back:
BEGIN TRANSACTION [Tran1]
BEGIN TRY
INSERT INTO [Test].[dbo].[T1] ([Title], [AVG])
VALUES ('Tidd130', 130), ('Tidd230', 230)
UPDATE [Test].[dbo].[T1]
SET [Title] = N'az2' ,[AVG] = 1
WHERE [dbo].[T1].[Title] = N'az'
COMMIT TRANSACTION [Tran1]
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION [Tran1]
END CATCH
/bin/sh
may or may not invoke the same program as /bin/bash
.
sh
supports at least the features required by POSIX (assuming a correct implementation). It may support extensions as well.
bash
, the "Bourne Again Shell", implements the features required for sh plus bash-specific extensions. The full set of extensions is too long to describe here, and it varies with new releases. The differences are documented in the bash manual. Type info bash
and read the "Bash Features" section (section 6 in the current version), or read the current documentation online.
In my case (Hibernate 3.5.2, Postgresql, Ubuntu), setting hibernate.hbm2ddl.auto=update
only created new tables and created new columns in already existing tables.
It did neither drop tables, nor drop columns, nor alter columns. It can be called a safe option, but something like hibernate.hbm2ddl.auto=create_tables add_columns
would be more clear.
Convert int[] to Integer[]:
int[] primitiveArray = {1, 2, 3, 4, 5};
Integer[] objectArray = new Integer[primitiveArray.length];
for(int ctr = 0; ctr < primitiveArray.length; ctr++) {
objectArray[ctr] = Integer.valueOf(primitiveArray[ctr]); // returns Integer value
}
Convert Integer[] to int[]:
Integer[] objectArray = {1, 2, 3, 4, 5};
int[] primitiveArray = new int[objectArray.length];
for(int ctr = 0; ctr < objectArray.length; ctr++) {
primitiveArray[ctr] = objectArray[ctr].intValue(); // returns int value
}
Zimi's answer describes this process generally. Here are the specifics:
Create and switch to a new branch. Make sure the new branch is based on master
so it will include the recent hotfixes.
git checkout master
git branch feature1_new
git checkout feature1_new
# Or, combined into one command:
git checkout -b feature1_new master
After switching to the new branch, merge the changes from your existing feature branch. This will add your commits without duplicating the hotfix commits.
git merge feature1
On the new branch, resolve any conflicts between your feature and the master branch.
Done! Now use the new branch to continue to develop your feature.
myclass.h
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
class MyClass
{
public:
MyClass();
/* use virtual otherwise linker will try to perform static linkage */
virtual void DoSomething();
private:
int x;
};
#endif
myclass.cc
#include "myclass.h"
#include <iostream>
using namespace std;
extern "C" MyClass* create_object()
{
return new MyClass;
}
extern "C" void destroy_object( MyClass* object )
{
delete object;
}
MyClass::MyClass()
{
x = 20;
}
void MyClass::DoSomething()
{
cout<<x<<endl;
}
class_user.cc
#include <dlfcn.h>
#include <iostream>
#include "myclass.h"
using namespace std;
int main(int argc, char **argv)
{
/* on Linux, use "./myclass.so" */
void* handle = dlopen("myclass.so", RTLD_LAZY);
MyClass* (*create)();
void (*destroy)(MyClass*);
create = (MyClass* (*)())dlsym(handle, "create_object");
destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");
MyClass* myClass = (MyClass*)create();
myClass->DoSomething();
destroy( myClass );
}
On Mac OS X, compile with:
g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user
On Linux, compile with:
g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user
If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object
and destroy_object
. Your main application would not need to be changed in any way.
Here is an updated version for Chart.js 2.3
Sep 23, 2016: Edited my code to work with v2.3 for both line/bar type.
Important: Even if you don't need the animation, don't change the duration option to 0, otherwise you will get chartInstance.controller is undefined error.
var chartData = {_x000D_
labels: ["January", "February", "March", "April", "May", "June"],_x000D_
datasets: [_x000D_
{_x000D_
fillColor: "#79D1CF",_x000D_
strokeColor: "#79D1CF",_x000D_
data: [60, 80, 81, 56, 55, 40]_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
var opt = {_x000D_
events: false,_x000D_
tooltips: {_x000D_
enabled: false_x000D_
},_x000D_
hover: {_x000D_
animationDuration: 0_x000D_
},_x000D_
animation: {_x000D_
duration: 1,_x000D_
onComplete: function () {_x000D_
var chartInstance = this.chart,_x000D_
ctx = chartInstance.ctx;_x000D_
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = 'bottom';_x000D_
_x000D_
this.data.datasets.forEach(function (dataset, i) {_x000D_
var meta = chartInstance.controller.getDatasetMeta(i);_x000D_
meta.data.forEach(function (bar, index) {_x000D_
var data = dataset.data[index]; _x000D_
ctx.fillText(data, bar._model.x, bar._model.y - 5);_x000D_
});_x000D_
});_x000D_
}_x000D_
}_x000D_
};_x000D_
var ctx = document.getElementById("Chart1"),_x000D_
myLineChart = new Chart(ctx, {_x000D_
type: 'bar',_x000D_
data: chartData,_x000D_
options: opt_x000D_
});
_x000D_
<canvas id="myChart1" height="300" width="500"></canvas>
_x000D_
First, go to c:\mongodb\bin>
to turn on mongoDB, if you see in console that mongo is listening in port 27017, it is OK
If not, close console and create folder c:\data\db
and start mongod again
If you're working with a multiline string, like a code file:
<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>
And want to replace all leading lines, to get this result:
<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>
You must add the multiline
flag to your regex, ^
and $
match line by line:
string.replace(/^\s+|\s+$/gm, '');
Relevant quote from docs:
The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.
All three define the meaning of zero in different context.
These three are always different when you look at the memory:
NULL - 0x00000000 or 0x00000000'00000000 (32 vs 64 bit)
NUL - 0x00 or 0x0000 (ascii vs 2byte unicode)
'0' - 0x20
I hope this clarifies it.
Actually,
var var1 = 1, var2 = 1, var3 = 1;
is not equivalent to:
var var1 = var2 = var3 = 1;
The difference is in scoping:
function good() {_x000D_
var var1 = 1, var2 = 1, var3 = 1;_x000D_
}_x000D_
_x000D_
function bad() {_x000D_
var var1 = var2 = var3 = 1;_x000D_
}_x000D_
_x000D_
good();_x000D_
console.log(window.var2); // undefined_x000D_
_x000D_
bad();_x000D_
console.log(window.var2); // 1. Aggh!
_x000D_
Actually this shows that assignment are right associative. The bad
example is equivalent to:
var var1 = (window.var2 = (window.var3 = 1));
You don't necessarily have to use the [string]:: prefix. This works in the same way:
if ($version)
{
$request += "/" + $version
}
A variable that is null or empty string evaluates to false.
In bootstrap-3.3.7.js you will see the following code.
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
So the bootstrap is going to replace the remote content into <div class="modal-content">
element. This is the default behavior by framework. So the problem is in your remote content itself, it should contain <div class="modal-header">
, <div class="modal-body">
, <div class="modal-footer">
by design.
Use Shift+Del.
More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.
You can not simply ping in Java as it relies on ICMP, which is sadly not supported in Java
http://mindprod.com/jgloss/ping.html
Use sockets instead
Hope it helps
CSS
@media print {
.pagebreak {
page-break-before: always;
}
}
HTML
<div class="pagebreak"></div>
use this xml code to add vertical line
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:background="#000000" />
use this xml code to add horizontal line
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000000" />
If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".
Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."
My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.
As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.
Iliya,
Sorry for that.
you code is work. but its had some problem with Array row and columns
here i correct your code this work correctly, you can try this ..
public static void printMatrix(int size, int row, int[][] matrix) {
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
for (int i = 1; i <= matrix[row].length; i++) {
System.out.printf("| %4d ", matrix[row][i - 1]);
}
System.out.println("|");
if (row == size - 1) {
// when we reach the last row,
// print bottom line "---------"
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
}
}
public static void length(int[][] matrix) {
int rowsLength = matrix.length;
for (int k = 0; k < rowsLength; k++) {
printMatrix(rowsLength, k, matrix);
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }
};
length(matrix);
}
and out put look like
----------------------
| 1 | 2 | 5 |
----------------------
| 3 | 4 | 6 |
----------------------
| 7 | 8 | 9 |
----------------------
Here is it with a loop for all files with some extension:
ll -ltr *.filename_extension > list.lst
for i in $(cat list.lst | awk '{ print $8 }') # validate if it is the 8 column on ls
do
echo $i
sed -i '/^#/d' $i
done
You might be loading multiselect.js file before the option list updated with AJAX call so while execution of multiselect.js file there is empty option list is there to apply multiselect functionlaity. So first update the option list by AJAX call then initiate the multiselect call you will get the dropdown list with the dynamic option list.
Hope this will help you out.
Multiselect dropdown list and related js & css files
// This function should be called while loading page_x000D_
var loadParentTaskList = function(){_x000D_
$.ajax({_x000D_
url: yoururl,_x000D_
method: 'POST',_x000D_
success: function(data){_x000D_
// To add options list coming from AJAX call multiselect_x000D_
for (var field in data) {_x000D_
$('<option value = "'+ data[field].name +'">' + data[field].name + '</option>').appendTo('#parent_task');_x000D_
}_x000D_
_x000D_
// To initiate the multiselect call _x000D_
$("#parent_task").multiselect({_x000D_
includeSelectAllOption: true_x000D_
})_x000D_
}_x000D_
});_x000D_
}
_x000D_
// Multiselect drop down list with id parent_task_x000D_
<select id="parent_task" multiple="multiple">_x000D_
</select>
_x000D_
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
That heavily depends on the structure of the search tree and the number and location of solutions (aka searched-for items).
If you know a solution is not far from the root of the tree, a breadth first search (BFS) might be better.
If the tree is very deep and solutions are rare, depth first search (DFS) might take an extremely long time, but BFS could be faster.
If the tree is very wide, a BFS might need too much memory, so it might be completely impractical.
If solutions are frequent but located deep in the tree, BFS could be impractical.
If the search tree is very deep you will need to restrict the search depth for depth first search (DFS), anyway (for example with iterative deepening).
But these are just rules of thumb; you'll probably need to experiment.
Another issue is parallelism: if you want to parallelize BFS you would need a shared datastructure between threads, which is a bad thing. DFS might be easier to distribute even between connected machines if you don't insist on the exact order of visiting the nodes.
In C, it is good style because you can change the type to something besides an enum.
typedef enum e_TokenType
{
blah1 = 0x00000000,
blah2 = 0X01000000,
blah3 = 0X02000000
} TokenType;
foo(enum e_TokenType token); /* this can only be passed as an enum */
foo(TokenType token); /* TokenType can be defined to something else later
without changing this declaration */
In C++ you can define the enum so that it will compile as C++ or C.
Sheet.getPhysicalNumberOfRows()
does not involve some empty rows.
If you want to loop for all rows, do not use this to know the loop size.
To supplement @user2744787's answer, here is a screenshot to show how to use cmd
with arguments in a Scheduled Task:
Program/script: cmd
Add arguments: /c run_with_default_port.bat > IMQuantWebServices.log
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
Since a new question has just been closed against this: you shouldn't create Thread
objects yourself. Here's another way to do it:
public void method() {
Executors.newSingleThreadExecutor().submit(() -> {
// yourCode
});
}
You should probably retain the executor service between calls though.
Building on David D's answer:
function NumberFormat(num,n) {
var num = (arguments[0] != null) ? arguments[0] : 0;
var n = (arguments[1] != null) ? arguments[1] : 2;
if(num > 0){
num = String(num);
if(num.indexOf('.') !== -1) {
var numarr = num.split(".");
if (numarr.length > 1) {
if(n > 0){
var temp = numarr[0] + ".";
for(var i = 0; i < n; i++){
if(i < numarr[1].length){
temp += numarr[1].charAt(i);
}
}
num = Number(temp);
}
}
}
}
return Number(num);
}
console.log('NumberFormat(123.85,2)',NumberFormat(123.85,2));
console.log('NumberFormat(123.851,2)',NumberFormat(123.851,2));
console.log('NumberFormat(0.85,2)',NumberFormat(0.85,2));
console.log('NumberFormat(0.851,2)',NumberFormat(0.851,2));
console.log('NumberFormat(0.85156,2)',NumberFormat(0.85156,2));
console.log('NumberFormat(0.85156,4)',NumberFormat(0.85156,4));
console.log('NumberFormat(0.85156,8)',NumberFormat(0.85156,8));
console.log('NumberFormat(".85156",2)',NumberFormat(".85156",2));
console.log('NumberFormat("0.85156",2)',NumberFormat("0.85156",2));
console.log('NumberFormat("1005.85156",2)',NumberFormat("1005.85156",2));
console.log('NumberFormat("0",2)',NumberFormat("0",2));
console.log('NumberFormat("",2)',NumberFormat("",2));
console.log('NumberFormat(85156,8)',NumberFormat(85156,8));
console.log('NumberFormat("85156",2)',NumberFormat("85156",2));
console.log('NumberFormat("85156.",2)',NumberFormat("85156.",2));
// NumberFormat(123.85,2) 123.85
// NumberFormat(123.851,2) 123.85
// NumberFormat(0.85,2) 0.85
// NumberFormat(0.851,2) 0.85
// NumberFormat(0.85156,2) 0.85
// NumberFormat(0.85156,4) 0.8515
// NumberFormat(0.85156,8) 0.85156
// NumberFormat(".85156",2) 0.85
// NumberFormat("0.85156",2) 0.85
// NumberFormat("1005.85156",2) 1005.85
// NumberFormat("0",2) 0
// NumberFormat("",2) 0
// NumberFormat(85156,8) 85156
// NumberFormat("85156",2) 85156
// NumberFormat("85156.",2) 85156
In case you're having issues with what @Karl Nosworthy and @esilver had provided above, I've updated the NSMutableAttributedString extension to its Swift 4 version.
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
_ = NSMutableAttributedString(string: textToFind)
// Set Attribuets for Color, HyperLink and Font Size
let attributes = [NSFontAttributeName: UIFont.bodyFont(.regular, shouldResize: true), NSLinkAttributeName:NSURL(string: linkURL)!, NSForegroundColorAttributeName: UIColor.blue]
self.setAttributes(attributes, range: foundRange)
return true
}
return false
}
}
'nunique' is an option for .agg() since pandas 0.20.0, so:
df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})
1.) Create a sequence of numbers 'seq' from 1 to 1000, and fix the width '-w' (width is determined by length of ending number, in this case 4 digits for 1000).
2.) Also, select which numbers you want using 'sed -n' (in this case, we select numbers 1-100).
3.) 'echo' out each number. Numbers are stored in the variable 'i', accessed using the '$'.
Pros: This code is pretty clean.
Cons: 'seq' isn't native to all Linux systems (as I understand)
for i in `seq -w 1 1000 | sed -n '1,100p'`;
do
echo $i;
done
For older versions of windows (2k, 2k3, xp)
"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions"
You can make a template of templates too, and reach private variable.
var a= {e:10, gy:'sfdsad'}; //global object
console.log(`e is ${a.e} and gy is ${a.gy}`);
//e is 10 and gy is sfdsad
var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}
console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad
backtick( b ); // use fonction's variable
//e is 20 and gy is fghj
function backtick( temp ) {
var a= {e:20, gy:'fghj'}; // local object
console.log( eval(`\`${temp}\``) );
}
You can simply use the powerful .loc
method and use one condition or several depending on your need (tested with pandas=1.0.5).
Code Summary:
df=pd.DataFrame(dict(Type='A B B C'.split(), Set='Z Z X Y'.split()))
df['Color'] = "red"
df.loc[(df['Set']=="Z"), 'Color'] = "green"
#practice!
df.loc[(df['Set']=="Z")&(df['Type']=="B")|(df['Type']=="C"), 'Color'] = "purple"
Explanation:
df=pd.DataFrame(dict(Type='A B B C'.split(), Set='Z Z X Y'.split()))
# df so far:
Type Set
0 A Z
1 B Z
2 B X
3 C Y
add a 'color' column and set all values to "red"
df['Color'] = "red"
Apply your single condition:
df.loc[(df['Set']=="Z"), 'Color'] = "green"
# df:
Type Set Color
0 A Z green
1 B Z green
2 B X red
3 C Y red
or multiple conditions if you want:
df.loc[(df['Set']=="Z")&(df['Type']=="B")|(df['Type']=="C"), 'Color'] = "purple"
You can read on Pandas logical operators and conditional selection here: Logical operators for boolean indexing in Pandas
Inside your Stack, you should wrap your background
widget in a Positioned.fill.
return new Stack(
children: <Widget>[
new Positioned.fill(
child: background,
),
foreground,
],
);
I found this method working quite well (for me) to produce a flat array of unique values:
$uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();
If you ran ->toSql()
on this query builder, you will see it generates a query like this:
select distinct `name` from `users`
The ->pluck()
is handled by illuminate\collection lib (not via sql query).
This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):
SELECT
CONCAT(table_name, '.', column_name) AS 'foreign key',
CONCAT(referenced_table_name, '.', referenced_column_name) AS 'references',
constraint_name AS 'constraint name'
FROM
information_schema.key_column_usage
WHERE
referenced_table_name IS NOT NULL;
If you want to check tables in a specific database, add the following:
AND table_schema = 'database_name';
I found this trying to store a massive number of files(350k+) in a repo. Yes, store. Laughs.
$ time git add .
git add . 333.67s user 244.26s system 14% cpu 1:06:48.63 total
The following extracts from the Bitbucket documentation are quite interesting.
When you work with a DVCS repository cloning, pushing, you are working with the entire repository and all of its history. In practice, once your repository gets larger than 500MB, you might start seeing issues.
... 94% of Bitbucket customers have repositories that are under 500MB. Both the Linux Kernel and Android are under 900MB.
The recommended solution on that page is to split your project into smaller chunks.
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
What about:
SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a
I wouldn't use:
svn checkout
just to authorizes the server authentication, I rather use:
svn list https://your.repository.url
which will ask you to do the authentication as well.
If this is needed to get authorization to a user that can't login, run:
sudo -u username svn list https://your.repository.url
There is an alternative solution to this problem which also deals with duplicate matches.
We start with 2 lists of equal length: emails
, otherarray
. The objective is to remove items from both lists for each index i
where emails[i] == '[email protected]'
.
This can be achieved using a list comprehension and then splitting via zip
:
emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']
from operator import itemgetter
res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))
print(emails) # ['[email protected]', '[email protected]']
print(otherarray) # ['some', 'details']
For most systems, the build requirements are now mentioned in python-ldap's documentation, in the "Installing" section.
If anything is missing for your system (or your system is missing entirely), please let maintainer know! (As of 2018, I am the maintainer, so a comment here should be enough. Or you can send a pull request or mail.)
This is really late to the party, but maybe it will help someone. My solution seems similar to what the OP described as problematic, but maybe it's a feature that Chrome offers now, but not then. I tried right-clicking and saving the .log file after the object was written to the console, but all that gave me was a text file with this:
console.js:230 Done: Array(50000)[0 … 9999][10000 … 19999][20000 … 29999][30000 … 39999][40000 … 49999]length: 50000__proto__: Array(0)
which was of no use to anyone.
What I ended up doing was finding the console.log(data)
in the code, dropped a breakpoint on it and then typed JSON.Stringify(data)
in the console which displayed the entire object as a JSON string and the Chrome console actually gives you a button to copy it. Then paste into a text editor and there's your JSON
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
MSDN Documentation Here
To add a bit of context to M.Ali's Answer you can convert a string to a uniqueidentifier using the following code
SELECT CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E')
If that doesn't work check to make sure you have entered a valid GUID
If you don't want to use a library, this should cover most/all of the same form element types.
function serialize(form) {
if (!form || !form.elements) return;
var serial = [], i, j, first;
var add = function (name, value) {
serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
}
var elems = form.elements;
for (i = 0; i < elems.length; i += 1, first = false) {
if (elems[i].name.length > 0) { /* don't include unnamed elements */
switch (elems[i].type) {
case 'select-one': first = true;
case 'select-multiple':
for (j = 0; j < elems[i].options.length; j += 1)
if (elems[i].options[j].selected) {
add(elems[i].name, elems[i].options[j].value);
if (first) break; /* stop searching for select-one */
}
break;
case 'checkbox':
case 'radio': if (!elems[i].checked) break; /* else continue */
default: add(elems[i].name, elems[i].value); break;
}
}
}
return serial.join('&');
}
Multiple action tags in a single intent-filter tag will also cause the same error.
Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.
For not changing the size of button on setting the background color:
button.getBackground().setColorFilter(button.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
this didn't change the size of the button and works with the old android versions too.
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
Quick answer: No, at least not with native SMS service.
Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.
If you hide the overflow and there is a long word, you risk loosing that word, so you could go one step further and use the "word-wrap" css attribute.
http://msdn.microsoft.com/en-us/library/ms531186(VS.85).aspx
Help -> About Eclipse -> Installation Details -> tab Configuration
Look for -arch
, and below it you'll see either x86_64
(meaning 64bit) or x86
(meaning 32bit).
Here's some fun I had solving something similar in node.
function formatTimeDiff(date1, date2) {
return Array(3)
.fill([3600, date1.getTime() - date2.getTime()])
.map((v, i, a) => {
a[i+1] = [a[i][0]/60, ((v[1] / (v[0] * 1000)) % 1) * (v[0] * 1000)];
return `0${Math.floor(v[1] / (v[0] * 1000))}`.slice(-2);
}).join(':');
}
const millis = 1000;
const utcEnd = new Date(1541424202 * millis);
const utcStart = new Date(1541389579 * millis);
const utcDiff = formatTimeDiff(utcEnd, utcStart);
console.log(`Dates:
Start : ${utcStart}
Stop : ${utcEnd}
Elapsed : ${utcDiff}
`);
/*
Outputs:
Dates:
Start : Mon Nov 05 2018 03:46:19 GMT+0000 (UTC)
Stop : Mon Nov 05 2018 13:23:22 GMT+0000 (UTC)
Elapsed : 09:37:02
*/
You can see it in action at https://repl.it/@GioCirque/TimeSpan-Formatting
See table's rules
attribute - https://www.w3.org/TR/html401/struct/tables.html#h-11.3.1
In my case was by uploading an APK, that although it was signed with production certificate and was a release variant, was generated by the run play button from Android studio. Problem solved after generating APK from Gradle or from Build APK menu option.
you can append the file with >> sign. It insert the contents at the last of the file which we are using.e.g if file let its name is myfile contains xyz then cat >> myfile abc ctrl d
after the above process the myfile contains xyzabc.
The answer below is related to this deprecation warning occurring in the Fragments tutorial on the Android developer website and may not be related to the posts above.
I used this code on the tutorial lesson and it did worked.
public void onAttach(Context context){
super.onAttach(context);
Activity activity = getActivity();
I was worried that activity maybe null as what the documentation states.
getActivity
FragmentActivity getActivity () Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.
But the onCreate on the main_activity clearly shows that the fragment was loaded and so after this method, calling get activity from the fragment will return the main_activity class.
getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit();
I hope I am correct with this. I am an absolute newbie.
This was driving me bonkers as the .astype()
solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there:
t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')
print pd.Timedelta(t2 - t1).seconds / 3600.0
...if you want hours. Or:
print pd.Timedelta(t2 - t1).seconds / 60.0
...if you want minutes.
file
only guesses at the file encoding and may be wrong (especially in cases where special characters only appear late in large files).hexdump
to look at bytes of non-7-bit-ASCII text and compare against code tables for common encodings (ISO 8859-*, UTF-8) to decide for yourself what the encoding is.iconv
will use whatever input/output encoding you specify regardless of what the contents of the file are. If you specify the wrong input encoding, the output will be garbled.iconv
, file
may not report any change due to the limited way in which file
attempts to guess at the encoding. For a specific example, see my long answer.I ran into this today and came across your question. Perhaps I can add a little more information to help other people who run into this issue.
First, the term ASCII is overloaded, and that leads to confusion.
7-bit ASCII only includes 128 characters (00-7F or 0-127 in decimal). 7-bit ASCII is also sometimes referred to as US-ASCII.
UTF-8 encoding uses the same encoding as 7-bit ASCII for its first 128 characters. So a text file that only contains characters from that range of the first 128 characters will be identical at a byte level whether encoded with UTF-8 or 7-bit ASCII.
The term extended ASCII (or high ASCII) refers to eight-bit or larger character encodings that include the standard seven-bit ASCII characters, plus additional characters.
ISO 8859-1 (aka "ISO Latin 1") is a specific 8-bit ASCII extension standard that covers most characters for Western Europe. There are other ISO standards for Eastern European languages and Cyrillic languages. ISO 8859-1 includes characters like Ö, é, ñ and ß for German and Spanish.
"Extension" means that ISO 8859-1 includes the 7-bit ASCII standard and adds characters to it by using the 8th bit. So for the first 128 characters, it is equivalent at a byte level to ASCII and UTF-8 encoded files. However, when you start dealing with characters beyond the first 128, your are no longer UTF-8 equivalent at the byte level, and you must do a conversion if you want your "extended ASCII" file to be UTF-8 encoded.
ISO 8859 and proprietary adaptations
file
One lesson I learned today is that we can't trust file
to always give correct interpretation of a file's character encoding.
The command tells only what the file looks like, not what it is (in the case where file looks at the content). It is easy to fool the program by putting a magic number into a file the content of which does not match it. Thus the command is not usable as a security tool other than in specific situations.
file
looks for magic numbers in the file that hint at the type, but these can be wrong, no guarantee of correctness. file
also tries to guess the character encoding by looking at the bytes in the file. Basically file
has a series of tests that helps it guess at the file type and encoding.
My file is a large CSV file. file
reports this file as US ASCII encoded, which is WRONG.
$ ls -lh
total 850832
-rw-r--r-- 1 mattp staff 415M Mar 14 16:38 source-file
$ file -b --mime-type source-file
text/plain
$ file -b --mime-encoding source-file
us-ascii
My file has umlauts in it (ie Ö). The first non-7-bit-ascii doesn't show up until over 100k lines into the file. I suspect this is why file
doesn't realize the file encoding isn't US-ASCII.
$ pcregrep -no '[^\x00-\x7F]' source-file | head -n1
102321:?
I'm on a Mac, so using PCRE's grep
. With GNU grep you could use the -P
option. Alternatively on a Mac, one could install coreutils (via Homebrew or other) in order to get GNU grep.
I haven't dug into the source-code of file
, and the man page doesn't discuss the text encoding detection in detail, but I am guessing file
doesn't look at the whole file before guessing encoding.
Whatever my file's encoding is, these non-7-bit-ASCII characters break stuff. My German CSV file is ;
-separated and extracting a single column doesn't work.
$ cut -d";" -f1 source-file > tmp
cut: stdin: Illegal byte sequence
$ wc -l *
3081673 source-file
102320 tmp
3183993 total
Note the cut
error and that my "tmp" file has only 102320 lines with the first special character on line 102321.
Let's take a look at how these non-ASCII characters are encoded. I dump the first non-7-bit-ascii into hexdump
, do a little formatting, remove the newlines (0a
) and take just the first few.
$ pcregrep -o '[^\x00-\x7F]' source-file | head -n1 | hexdump -v -e '1/1 "%02x\n"'
d6
0a
Another way. I know the first non-7-bit-ASCII char is at position 85 on line 102321. I grab that line and tell hexdump
to take the two bytes starting at position 85. You can see the special (non-7-bit-ASCII) character represented by a ".", and the next byte is "M"... so this is a single-byte character encoding.
$ tail -n +102321 source-file | head -n1 | hexdump -C -s85 -n2
00000055 d6 4d |.M|
00000057
In both cases, we see the special character is represented by d6
. Since this character is an Ö which is a German letter, I am guessing that ISO 8859-1 should include this. Sure enough, you can see "d6" is a match (ISO/IEC 8859-1).
Important question... how do I know this character is an Ö without being sure of the file encoding? The answer is context. I opened the file, read the text and then determined what character it is supposed to be. If I open it in Vim it displays as an Ö because Vim does a better job of guessing the character encoding (in this case) than file
does.
So, my file seems to be ISO 8859-1. In theory I should check the rest of the non-7-bit-ASCII characters to make sure ISO 8859-1 is a good fit... There is nothing that forces a program to only use a single encoding when writing a file to disk (other than good manners).
I'll skip the check and move on to conversion step.
$ iconv -f iso-8859-1 -t utf8 source-file > output-file
$ file -b --mime-encoding output-file
us-ascii
Hmm. file
still tells me this file is US ASCII even after conversion. Let's check with hexdump
again.
$ tail -n +102321 output-file | head -n1 | hexdump -C -s85 -n2
00000055 c3 96 |..|
00000057
Definitely a change. Note that we have two bytes of non-7-bit-ASCII (represented by the "." on the right) and the hex code for the two bytes is now c3 96
. If we take a look, seems we have UTF-8 now (c3 96
is the encoding of Ö
in UTF-8) UTF-8 encoding table and Unicode characters
But file
still reports our file as us-ascii
? Well, I think this goes back to the point about file
not looking at the whole file and the fact that the first non-7-bit-ASCII characters don't occur until late in the file.
I'll use sed
to stick a Ö at the beginning of the file and see what happens.
$ sed '1s/^/Ö\'$'\n/' source-file > test-file
$ head -n1 test-file
Ö
$ head -n1 test-file | hexdump -C
00000000 c3 96 0a |...|
00000003
Cool, we have an umlaut. Note the encoding though is c3 96
(UTF-8). Hmm.
Checking our other umlauts in the same file again:
$ tail -n +102322 test-file | head -n1 | hexdump -C -s85 -n2
00000055 d6 4d |.M|
00000057
ISO 8859-1. Oops! It just goes to show how easy it is to get the encodings screwed up. To be clear, I've managed to create a mix of UTF-8 and ISO 8859-1 encodings in the same file.
Let's try converting our new test file with the umlaut (Ö) at the front and see what happens.
$ iconv -f iso-8859-1 -t utf8 test-file > test-file-converted
$ head -n1 test-file-converted | hexdump -C
00000000 c3 83 c2 96 0a |.....|
00000005
$ tail -n +102322 test-file-converted | head -n1 | hexdump -C -s85 -n2
00000055 c3 96 |..|
00000057
Oops. The first umlaut that was UTF-8 was interpreted as ISO 8859-1 since that is what we told iconv
. The second umlaut is correctly converted from d6
(ISO 8859-1) to c3 96
(UTF-8).
I'll try again, but this time I will use Vim to do the Ö insertion instead of sed
. Vim seemed to detect the encoding better (as "latin1" aka ISO 8859-1) so perhaps it will insert the new Ö with a consistent encoding.
$ vim source-file
$ head -n1 test-file-2
?
$ head -n1 test-file-2 | hexdump -C
00000000 d6 0d 0a |...|
00000003
$ tail -n +102322 test-file-2 | head -n1 | hexdump -C -s85 -n2
00000055 d6 4d |.M|
00000057
It looks good. It looks like ISO 8859-1 for new and old umlauts.
Now the test.
$ file -b --mime-encoding test-file-2
iso-8859-1
$ iconv -f iso-8859-1 -t utf8 test-file-2 > test-file-2-converted
$ file -b --mime-encoding test-file-2-converted
utf-8
Boom! Moral of the story. Don't trust file
to always guess your encoding right. It is easy to mix encodings within the same file. When in doubt, look at the hex.
A hack (also prone to failure) that would address this specific limitation of file
when dealing with large files would be to shorten the file to make sure that special (non-ascii) characters appear early in the file so file
is more likely to find them.
$ first_special=$(pcregrep -o1 -n '()[^\x00-\x7F]' source-file | head -n1 | cut -d":" -f1)
$ tail -n +$first_special source-file > /tmp/source-file-shorter
$ file -b --mime-encoding /tmp/source-file-shorter
iso-8859-1
You could then use (presumably correct) detected encoding to feed as input to iconv
to ensure you are converting correctly.
Christos Zoulas updated file
to make the amount of bytes looked at configurable. One day turn-around on the feature request, awesome!
http://bugs.gw.com/view.php?id=533 Allow altering how many bytes to read from analyzed files from the command line
The feature was released in file
version 5.26.
Looking at more of a large file before making a guess about encoding takes time. However, it is nice to have the option for specific use-cases where a better guess may outweigh additional time and I/O.
Use the following option:
-P, --parameter name=value
Set various parameter limits.
Name Default Explanation
bytes 1048576 max number of bytes to read from file
Something like...
file_to_check="myfile"
bytes_to_scan=$(wc -c < $file_to_check)
file -b --mime-encoding -P bytes=$bytes_to_scan $file_to_check
... it should do the trick if you want to force file
to look at the whole file before making a guess. Of course, this only works if you have file
5.26 or newer.
file
to display UTF-8 instead of US-ASCIISome of the other answers seem to focus on trying to make file
display UTF-8 even if the file only contains plain 7-bit ascii. If you think this through you should probably never want to do this.
file
command is saying the file is UTF-8, that implies that the file contains some characters with UTF-8 specific encoding. If that isn't really true, it could cause confusion or problems down the line. If file
displayed UTF-8 when the file only contained 7-bit ascii characters, this would be a bug in the file
program.file
command output before accepting a file as input and it won't process the file unless it "sees" UTF-8...well that is pretty bad design. I would argue this is a bug in that program.If you absolutely must take a plain 7-bit ascii file and convert it to UTF-8, simply insert a single non-7-bit-ascii character into the file with UTF-8 encoding for that character and you are done. But I can't imagine a use-case where you would need to do this. The easiest UTF-8 character to use for this is the Byte Order Mark (BOM) which is a special non-printing character that hints that the file is non-ascii. This is probably the best choice because it should not visually impact the file contents as it will generally be ignored.
Microsoft compilers and interpreters, and many pieces of software on Microsoft Windows such as Notepad treat the BOM as a required magic number rather than use heuristics. These tools add a BOM when saving text as UTF-8, and cannot interpret UTF-8 unless the BOM is present or the file contains only ASCII.
This is key:
or the file contains only ASCII
So some tools on windows have trouble reading UTF-8 files unless the BOM character is present. However this does not affect plain 7-bit ascii only files. I.e. this is not a reason for forcing plain 7-bit ascii files to be UTF-8 by adding a BOM character.
Here is more discussion about potential pitfalls of using the BOM when not needed (it IS needed for actual UTF-8 files that are consumed by some Microsoft apps). https://stackoverflow.com/a/13398447/3616686
Nevertheless if you still want to do it, I would be interested in hearing your use case. Here is how. In UTF-8 the BOM is represented by hex sequence 0xEF,0xBB,0xBF
and so we can easily add this character to the front of our plain 7-bit ascii file. By adding a non-7-bit ascii character to the file, the file is no longer only 7-bit ascii. Note that we have not modified or converted the original 7-bit-ascii content at all. We have added a single non-7-bit-ascii character to the beginning of the file and so the file is no longer entirely composed of 7-bit-ascii characters.
$ printf '\xEF\xBB\xBF' > bom.txt # put a UTF-8 BOM char in new file
$ file bom.txt
bom.txt: UTF-8 Unicode text, with no line terminators
$ file plain-ascii.txt # our pure 7-bit ascii file
plain-ascii.txt: ASCII text
$ cat bom.txt plain-ascii.txt > plain-ascii-with-utf8-bom.txt # put them together into one new file with the BOM first
$ file plain-ascii-with-utf8-bom.txt
plain-ascii-with-utf8-bom.txt: UTF-8 Unicode (with BOM) text
This bookmarlet works in Google sites/Youtube as of Aug 2019 (tested in Chrome and Firefox):
javascript: function enableContextMenu(aggressive = false) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll("body"); removeContextMenuOnAll("img"); removeContextMenuOnAll("td"); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); el.addEventListener("dragstart", bringBackDefault, true); el.addEventListener("selectstart", bringBackDefault, true); el.addEventListener("click", bringBackDefault, true); el.addEventListener("mousedown", bringBackDefault, true); el.addEventListener("mouseup", bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener("contextmenu", bringBackDefault, true); el.removeEventListener("dragstart", bringBackDefault, true); el.removeEventListener("selectstart", bringBackDefault, true); el.removeEventListener("click", bringBackDefault, true); el.removeEventListener("mousedown", bringBackDefault, true); el.removeEventListener("mouseup", bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } enableContextMenu();
For peskier sites, set/pass aggressive to true (this will disable most event handlers and hence disable interaction with the page):
javascript: function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll("body"); removeContextMenuOnAll("img"); removeContextMenuOnAll("td"); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); el.addEventListener("dragstart", bringBackDefault, true); el.addEventListener("selectstart", bringBackDefault, true); el.addEventListener("click", bringBackDefault, true); el.addEventListener("mousedown", bringBackDefault, true); el.addEventListener("mouseup", bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener("contextmenu", bringBackDefault, true); el.removeEventListener("dragstart", bringBackDefault, true); el.removeEventListener("selectstart", bringBackDefault, true); el.removeEventListener("click", bringBackDefault, true); el.removeEventListener("mousedown", bringBackDefault, true); el.removeEventListener("mouseup", bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } enableContextMenu();
You should be able to use \n
inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n
for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
\r\n
instead, which is the Windows newline.Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
Source: official documentation.
You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:
var = 1
def global_var_change():
global var
var = "value changed"
global_var_change() #call the function for changes
print var
Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.
I fixed this (using Java / Spring backend) by adding a handler that matches everything defined in my Angular routes, that sends back index.html instead of a 404. This then effectively (re)bootstraps the application and loads the correct page. I also have a 404 handler for anything that isn't caught by this.
@Controller ////don't use RestController or it will just send back the string "index.html"
public class Redirect {
private static final Logger logger = LoggerFactory.getLogger(Redirect.class);
@RequestMapping(value = {"comma", "sep", "list", "of", "routes"})
public String redirectToIndex(HttpServletRequest request) {
logger.warn("Redirect api called for URL {}. Sending index.html back instead. This will happen on a page refresh or reload when the page is on an Angular route", request.getRequestURL());
return "/index.html";
}
}
<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>
You could also use ng-hide="somefield.length"
instead of ng-show="!somefield.length"
if that reads more naturally for you.
A better alternative might be to really take advantage of the form abilities of Angular:
<form name="myform">
<input name="myfield" ng-model="somefield" ng-minlength="5" required>
<span ng-show="myform.myfield.$error.required">Please enter something!</span>
<span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form>
I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:
JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");
If you statically import javax.swing.JOptionPane.showMessageDialog
using:
import static javax.swing.JOptionPane.showMessageDialog;
This further reduces to
showMessageDialog(null, "This is even shorter");
I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.
But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin
It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area
type normal division first and then type shift + S->d
/* EXAMPLE: /MONDAY/ SET DATEFIRST 1 SELECT dbo.FUNC_GETDATEDIFFERENCE_WO_WEEKEND('2019-02-01','2019-02-12') */ CREATE FUNCTION FUNC_GETDATEDIFFERENCE_WO_WEEKEND ( @pdtmaLastLoanPayDate DATETIME, @pdtmaDisbursedDate DATETIME ) RETURNS BIGINT BEGIN
DECLARE
@mintDaysDifference BIGINT
SET @mintDaysDifference = 0
WHILE CONVERT(NCHAR(10),@pdtmaLastLoanPayDate,121) <= CONVERT(NCHAR(10),@pdtmaDisbursedDate,121)
BEGIN
IF DATEPART(WEEKDAY,@pdtmaLastLoanPayDate) NOT IN (6,7)
BEGIN
SET @mintDaysDifference = @mintDaysDifference + 1
END
SET @pdtmaLastLoanPayDate = DATEADD(DAY,1,@pdtmaLastLoanPayDate)
END
RETURN ISNULL(@mintDaysDifference,0)
END
JEP 158 introduces a common logging system for all components of the JVM which will change (and IMO simplify) how logging works with GC. JEP 158 added a new command-line option to control logging from all components of the JVM:
-Xlog
For example, the following option:
-Xlog:gc
will log messages tagged with gc
tag using info
level to stdout
. Or this one:
-Xlog:gc=debug:file=gc.txt:none
would log messages tagged with gc
tag using debug
level to a file called gc.txt
with no decorations. For more detailed discussion, you can checkout the examples in the JEP page.
How can I switch between opened windows in Eclipse
CTRL+F7 works here - Eclipse Photon on Windows.
You can try finding all elements that have this class and setting the "zoom" property to "nothing".
If you are using jQuery javascript library, you can do it with $(".the_required_class").css("zoom","")
Edit: Removed this statement as it turned out to not be true, as pointed out in a comment and other answers it has indeed been possible since 2010.
False: there is no generally known way for modifying stylesheets from JavaScript.
If you need to get the int value, just have a getter for the value in your ENUM:
private enum DownloadType {
AUDIO(1), VIDEO(2), AUDIO_AND_VIDEO(3);
private final int value;
private DownloadType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public static void main(String[] args) {
System.out.println(DownloadType.AUDIO.getValue()); //returns 1
System.out.println(DownloadType.VIDEO.getValue()); //returns 2
System.out.println(DownloadType.AUDIO_AND_VIDEO.getValue()); //returns 3
}
Or you could simple use the ordinal()
method, which would return the position of the enum constant in the enum.
private enum DownloadType {
AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
//rest of the code
}
System.out.println(DownloadType.AUDIO.ordinal()); //returns 0
System.out.println(DownloadType.VIDEO.ordinal()); //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.ordinal()); //returns 2
function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}
Use like
ready(function(){
//some code
});
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//Some Code here
//DOM is avaliable
//var h1s = document.querySelector("h1");
});
Support: IE9+
I have this function in the document ready event so that the reCaptcha is dynamically sized. Anyone should be able to drop this in place and go.
function ScaleReCaptcha()
{
if (document.getElementsByClassName('g-recaptcha').length > 0)
{parentWidth = document.getElementsByClassName('g-recaptcha') [0].parentNode.clientWidth;
childWidth = document.getElementsByClassName('g-recaptcha')[0].firstChild.clientWidth;
scale = (parentWidth) / (childWidth);
new_width = childWidth * scale;
document.getElementsByClassName('g-recaptcha')[0].style.transform = 'scale(' + scale + ')';
document.getElementsByClassName('g-recaptcha')[0].style.transformOrigin = '0 0';
}
}
Use this
string[] str = new string[] {"Foo", "Bar"};
myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;
OR
foreach (string s in str)
myComboBox.Items.Add(s);
myComboBox.SelectedIndex = 0;
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation
dependency with NSJSONSerialization
as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
I had the same problem, and it turned out I hadn't installed the library.
this link was super usefull.
git show --stat origin/branch_name
This will give you a list of the files that have been added or modified under this branch.
This has worked for me!
$('#selected-option option:selected').val()
Hope this helps someone!
For me such issue occur when I had multiple export
statements in single .ts
file...
In WinForms, ValueMember
and DisplayMember
are used when data-binding the list. If you're not data-binding, then you can add any arbitrary object as a ListItem
.
The catch to that is that, in order to display the item, ToString()
will be called on it. Thus, it is highly recommended that you only add objects to the ListBox where calling ToString()
will result in meaningful output.
Nothing to add to the semantic aspects of "final".
But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.
One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)
In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.
This technique is known as Devirtualization. A term worth remembering. :-)
There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):
http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly
That solution will open up a new browser window without the normal features such as address bar and similar.
To implement a modal popup, I suggest you to take a look at jQuery and SimpleModal, which is really slick.
(Here are some simple demos using SimpleModal: http://www.ericmmartin.com/projects/simplemodal-demos/)
You can do:
x = re.findall('\d+', text)
result = x[0] if len(x) > 0 else ''
Note that your question isn't exactly related to regex. Rather, how do you safely find an element from an array, if it has none.
You should use .NET Core, instead of .NET Framework or Xamarin, in the following 6 typical scenarios according to the documentation here.
1. Cross-Platform needs
Clearly, if your goal is to have an application (web/service) that should be able to run across platforms (Windows, Linux and MacOS), the best choice in the .NET ecosystem is to use .NET Core as its runtime (CoreCLR) and libraries are cross-platform. The other choice is to use the Mono Project.
Both choices are open source, but .NET Core is directly and officially supported by Microsoft and will have a heavy investment moving forward.
When using .NET Core across platforms, the best development experience exists on Windows with the Visual Studio IDE which supports many productivity features including project management, debugging, source control, refactoring, rich editing including Intellisense, testing and much more. But rich development is also supported using Visual Studio Code on Mac, Linux and Windows including intellisense and debugging. Even third party editors like Sublime, Emacs, VI and more work well and can get editor intellisense using the open source Omnisharp project.
2. Microservices
When you are building a microservices oriented system composed of multiple independent, dynamically scalable, stateful or stateless microservices, the great advantage that you have here is that you can use different technologies/frameworks/languages at a microservice level. That allows you to use the best approach and technology per micro areas in your system, so if you want to build very performant and scalable microservices, you should use .NET Core. Eventually, if you need to use any .NET Framework library that is not compatible with .NET Core, there’s no issue, you can build that microservice with the .NET Framework and in the future you might be able to substitute it with the .NET Core.
The infrastructure platform you could use are many. Ideally, for large and complex microservice systems, you should use Azure Service Fabric. But for stateless microservices you can also use other products like Azure App Service or Azure Functions.
Note that as of June 2016, not every technology within Azure supports the .NET Core, but .NET Core support in Azure will be increasing dramatically now that .NET Core is RTM released.
3. Best performant and scalable systems
When your system needs the best possible performance and scalability so you get the best responsiveness no matter how many users you have, then is where .NET Core and ASP.NET Core really shine. The more you can do with the same amount of infrastructure/hardware, the richer the experience you’ll have for your end users – at a lower cost.
The days of Moore’s law performance improvements for single CPUs does not apply anymore; yet you need to do more while your system is growing and need higher scalability and performance for everyday’ s more demanding users which are growing exponentially in numbers. You need to get more efficient, optimize everywhere, and scale better across clusters of machines, VMs and CPU cores, ultimately. It is not just a matter of user’s satisfaction; it can also make a huge difference in cost/TCO. This is why it is important to strive for performance and scalability.
As mentioned, if you can isolate small pieces of your system as microservices or any other loosely-coupled approach, it’ll be better as you’ll be able to not just evolve each small piece/microservice independently and have a better long-term agility and maintenance, but also you’ll be able to use any other technology at a microservice level if what you need to do is not compatible with .NET Core. And eventually you’d be able to refactor it and bring it to .NET Core when possible.
4. Command line style development for Mac, Linux or Windows.
This approach is optional when using .NET Core. You can also use the full Visual Studio IDE, of course. But if you are a developer that wants to develop with lightweight editors and heavy use of command line, .NET Core is designed for CLI. It provides simple command line tools available on all supported platforms, enabling developers to build and test applications with a minimal installation on developer, lab or production machines. Editors like Visual Studio Code use the same command line tools for their development experiences. And IDE’s like Visual Studio use the same CLI tools but hide them behind a rich IDE experience. Developers can now choose the level they want to interact with the tool chain from CLI to editor to IDE.
5. Need side by side of .NET versions per application level.
If you want to be able to install applications with dependencies on different versions of frameworks in .NET, you need to use .NET Core which provides 100% side-by side as explained previously in this document.
6. Windows 10 UWP .NET apps.
In addition, you may also want to read:
If an item is child of an item that is hidden is(":visible") will return true, which is incorrect.
I just fixed this by added "display:inherit" to the child item. This will fixed it for me:
<div class="parent">
<div class="child">
</div>
<div>
and the CSS:
.parent{
display: hidden;
}
.child{
display: inherit;
}
Now the item can be effectively switched on and off by changing the visibility of the parent, and $(element).is(":visible") will return the visibility of the parent item
The other advantage of using curl is that you also can keep the HTTP way of sending parameters to your script if you need to, by using $_GET
, $_POST
etc like this:
*/5 * * * * curl --request GET 'http://exemple.com/path/check.php?param1=1¶m2=2'
All depends on your visualization of the array. Rows and Columns are properties of visualization (probably in your imagination) of the array, not the array itself.
It's exactly the same as asking is number "5" red or green?
I could draw it red, I could draw it greed right? Color is not an integral property of a number. In the same way representing 2D array as a grid of rows and columns is not necessary for existence of this array.
2D array has just first dimention and second dimention, everything related to visualizing those is purely your flavour.
When I have char array char[80][25]
, I may like to print it on console rotated so that I have 25 rows of 80 characters that fits the screen without scroll.
I'll try to provide viable example when representing 2D array as rows and columns doesn't make sense at all: Let's say I need an array of 1 000 000 000 integers. My machine has 8GB of RAM, so I have enough memory for this, but if you try executing var a = new int[1000000000]
, you'll most likely get OutOfMemory exception. That's because of memory fragmentation - there is no consecutive block of memory of this size. Instead you you can create 2D array 10 000 x 100 000 with your values. Logically it is 1D array, so you'd like to draw and imagine it as a single sequence of values, but due to technical implementation it is 2D.
For those of you who prefer a quick and dirty approach, just list all the columns that together define a unique record and create a unique index with those columns, like so:
ALTER IGNORE TABLE TABLE_NAME
ADD UNIQUE (column1
,column2
,column3
)
You can drop the unique index afterwords.
If the Toggle Visual Space
icon shall be added to a Visual Studio toolbar of your choice, because it shall be turned on and off via mouse click, then follow this instruction:
Customize the desired toolbar
Click on Customize...
Click on Add Command...
Go to Edit
and chose Toggle Visual Space
Click on OK
Tested with Visual Studio 2019.
It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:
<li><span class="foo">some text</span></li>
<li>some other text</li>
Then refer to it the usual way:
li > span.foo {...}
There are extensions of Word2Vec intended to solve the problem of comparing longer pieces of text like phrases or sentences. One of them is paragraph2vec or doc2vec.
"Distributed Representations of Sentences and Documents" http://cs.stanford.edu/~quocle/paragraph_vector.pdf
The reason this puts NaN
into a column is because df.index
and the Index
of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas
tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN
wherever they aren't aligned. Play around with the reindex
and align
methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align()
works with partially aligned indices:
In [7]: from pandas import DataFrame
In [8]: from numpy.random import randint
In [9]: df = DataFrame({'a': randint(3, size=10)})
In [10]:
In [10]: df
Out[10]:
a
0 0
1 2
2 0
3 1
4 0
5 0
6 0
7 0
8 0
9 0
In [11]: s = df.a[:5]
In [12]: dfa, sa = df.align(s, axis=0)
In [13]: dfa
Out[13]:
a
0 0
1 2
2 0
3 1
4 0
5 0
6 0
7 0
8 0
9 0
In [14]: sa
Out[14]:
0 0
1 2
2 0
3 1
4 0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
Name: a, dtype: float64
You can try something like this:
HSSFSheet summarySheet = wb.createSheet();
summarySheet.setColumnWidth(short column, short width);
Here params are:column number in sheet and its width But,the units of width are pretty small, you can try 4000 for example.
If you are using Pycharm then this is the virtual environment issue.
So, at the time of creating your Python project you will have to select "Existing interpreter" option -> click "system Interpreter" -> select the correct option for example "*\AppData\Local\Programs\Python\Python3.6\python.exe".
You can use 'New Virtual Env' as well, but I have just given the quick fix that should work for Pycharm users.
List performance:
>>> import timeit
>>> timeit.timeit(stmt='10**6 in a', setup='a = range(10**6)', number=100000)
0.008128150348026608
Set performance:
>>> timeit.timeit(stmt='10**6 in a', setup='a = set(range(10**6))', number=100000)
0.005674857488571661
You may want to consider Tuples as they're similar to lists but can’t be modified. They take up slightly less memory and are faster to access. They aren’t as flexible but are more efficient than lists. Their normal use is to serve as dictionary keys.
Sets are also sequence structures but with two differences from lists and tuples. Although sets do have an order, that order is arbitrary and not under the programmer’s control. The second difference is that the elements in a set must be unique.
set
by definition. [python | wiki].
>>> x = set([1, 1, 2, 2, 3, 3])
>>> x
{1, 2, 3}
Easy with kotlin
@Parcelize
class MyState(val superSavedState: Parcelable?, val loading: Boolean) : View.BaseSavedState(superSavedState), Parcelable
class MyView : View {
var loading: Boolean = false
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
return MyState(superState, loading)
}
override fun onRestoreInstanceState(state: Parcelable?) {
val myState = state as? MyState
super.onRestoreInstanceState(myState?.superSaveState ?: state)
loading = myState?.loading ?: false
//redraw
}
}
AzP already provided most of the information, but some of it is incorrect.
First of all, there is no such option inotify_interval
. The only option that exists is notify_interval
and has nothing to do with inotify
.
So to clarify, notify_interval
controls how frequently the (mini)dlna server announces itself in the network. The default value of 895 means it will announce itself about once every 15 minutes, meaning clients will need at most 15 minutes to find the server. I personally use 1-5 minutes depending on client volatility in the network.
In terms of getting minidlna to find files that have been added, there are two options:
files.db
and consists in restarting minidlna while passing the -R
argument, which forces a full rescan and builds the database from scratch. Since version 1.2.0 there's now also the -r
argument which performs a rebuild action. This preserves any existing database and drops and adds old and new records, respectively.inotify
events by setting inotify=yes
and restarting minidlna. If inotify
is set to =no
, the only option to update the file database is the forced full rescan.Additionally, in order to have inotify
working, the file-system must support inotify
events, which is not the case in most remote file-systems. If you have minidlna running over NFS it will not see any inotify events because these are generated on the server side and not on the client.
Finally, even if inotify
is working and is supported by the file-system, the user under which minidlna is running must be able to read the file, otherwise it will not be able to retrieve necessary metadata. In this case, the logfile (usually /var/log/minidlna.log
) should contain useful information.
In the PHP file first you need to register the session
<? session_start();
$_SESSION['id'] = $userData['user_id'];?>
And in each page of your php application you can retrive the session id
<? session_start()
id = $_SESSION['id'];
?>
Here is python code for computing the ROC curve (as a scatter plot):
import matplotlib.pyplot as plt
import numpy as np
score = np.array([0.9, 0.8, 0.7, 0.6, 0.55, 0.54, 0.53, 0.52, 0.51, 0.505, 0.4, 0.39, 0.38, 0.37, 0.36, 0.35, 0.34, 0.33, 0.30, 0.1])
y = np.array([1,1,0, 1, 1, 1, 0, 0, 1, 0, 1,0, 1, 0, 0, 0, 1 , 0, 1, 0])
# false positive rate
fpr = []
# true positive rate
tpr = []
# Iterate thresholds from 0.0, 0.01, ... 1.0
thresholds = np.arange(0.0, 1.01, .01)
# get number of positive and negative examples in the dataset
P = sum(y)
N = len(y) - P
# iterate through all thresholds and determine fraction of true positives
# and false positives found at this threshold
for thresh in thresholds:
FP=0
TP=0
for i in range(len(score)):
if (score[i] > thresh):
if y[i] == 1:
TP = TP + 1
if y[i] == 0:
FP = FP + 1
fpr.append(FP/float(N))
tpr.append(TP/float(P))
plt.scatter(fpr, tpr)
plt.show()
I look at this a few times at the end decided with EF implementation
A bit modified for SqlConnection
public static void ExecuteSqlScript(this SqlConnection sqlConnection, string sqlBatch)
{
// Handle backslash utility statement (see http://technet.microsoft.com/en-us/library/dd207007.aspx)
sqlBatch = Regex.Replace(sqlBatch, @"\\(\r\n|\r|\n)", string.Empty);
// Handle batch splitting utility statement (see http://technet.microsoft.com/en-us/library/ms188037.aspx)
var batches = Regex.Split(
sqlBatch,
string.Format(CultureInfo.InvariantCulture, @"^\s*({0}[ \t]+[0-9]+|{0})(?:\s+|$)", BatchTerminator),
RegexOptions.IgnoreCase | RegexOptions.Multiline);
for (int i = 0; i < batches.Length; ++i)
{
// Skip batches that merely contain the batch terminator
if (batches[i].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase) ||
(i == batches.Length - 1 && string.IsNullOrWhiteSpace(batches[i])))
{
continue;
}
// Include batch terminator if the next element is a batch terminator
if (batches.Length > i + 1 &&
batches[i + 1].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase))
{
int repeatCount = 1;
// Handle count parameter on the batch splitting utility statement
if (!string.Equals(batches[i + 1], BatchTerminator, StringComparison.OrdinalIgnoreCase))
{
repeatCount = int.Parse(Regex.Match(batches[i + 1], @"([0-9]+)").Value, CultureInfo.InvariantCulture);
}
for (int j = 0; j < repeatCount; ++j)
{
var command = sqlConnection.CreateCommand();
command.CommandText = batches[i];
command.ExecuteNonQuery();
}
}
else
{
var command = sqlConnection.CreateCommand();
command.CommandText = batches[i];
command.ExecuteNonQuery();
}
}
}
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
Simple:
text-transform: capitalize;
@Table's name attribute is the actual table name. @Entitiy's name is useful if you have two @Entity classes with the same name and you need a way to differentiate them when running queries.
Sub Results2()
Dim rCell As Range
Dim shSource As Worksheet
Dim shDest As Worksheet
Dim lCnt As Long
Set shSource = ThisWorkbook.Sheets("Sheet1")
Set shDest = ThisWorkbook.Sheets("Sheet2")
For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
lCnt = lCnt + 1
shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
Next rCell
End Sub
This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.
To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.
I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,
Sub Results3()
Dim i As Long, lCnt As Long
Dim sh As Worksheet
lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
Set sh = ThisWorkbook.Sheets("Sheet2")
Const sSOURCE As String = "Sheet1!"
For i = 1 To lCnt
sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
Next i
End Sub
I believe you are looking for the Microsoft SQL Server JDBC driver: http://msdn.microsoft.com/en-us/sqlserver/aa937724