I searched long on this issue. There are several reasons causes this issue.
If you are facing when you and Swift code/library in an Objectice C project you should try Solution 1-2-3
If you are facing this issue with a new a Swift project Solution 4 will fit you best.
Solution 1:
Restart Xcode, then computer and iPhone
Solution 2:
Go to project build settings and set Embedded Content Contains Swift
Code flag to YES
Solution 3:
Go to project build settings and add @executable_path/Frameworks
to Runpath Search Paths option
Solution 4:
If none of above works, this should. Apple seems to be ninja patched certificates as mentioned in AirSign's post
At InHouse certificates
Subject: UID=269J2W3P2L, CN=iPhone Distribution: Company Name, O=Company Name, C=FR
they added a new field named OU
Subject: UID=269J2W3P2L, CN=iPhone Distribution: Company Name, OU=269J2W3P2L, O=Company Name, C=FR
so you should just recreate certificate and provision
I already found the answer
Swift 4
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "nextView") as! NextViewController
self.present(nextViewController, animated:true, completion:nil)
Swift 3
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)
Make sure you are not dynamically applying relative constraints to a view which is not yet there in view hierarchy.
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectZero];
[self.view addSubview:bottomView];
bottomConstraint = [NSLayoutConstraint constraintWithItem:bottomView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0];
bottomConstraint.active = YES;
In above example, bottomView has been made part of view hierarchy before applying relative constraints on it.
I spend a hour finding out what was wrong.. But Clean Project did the trick.
Build -> Clean All
The accepted solution is probably also working.. but this was enough for me.
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
If you need to change only size (Swift 4.0):
button.titleLabel?.font = button.titleLabel?.font.withSize(12)
If you want to run your command in parallel for each line you can use GNU Parallel
parallel -a <your file> <program>
Each line of your file will be passed to program as an argument. By default parallel
runs as many threads as your CPUs count. But you can specify it with -j
The window
is the actual global object.
The screen
is the screen, it contains properties about the user's display.
The document
is where the DOM is.
To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:
if ($query->num_rows() > 0) {
return $query->first_row();
}
To retrieve the first row.
You can use the following shortcut for code formatting: Ctrl+Alt+L
You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
sessionStorage.setItem("username", "John");
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
To change the encoding of your database:
Make sure the client encoding is set correctly during all this.
Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php
Please be aware that the accepted answer is a bit incomplete. Yes, at the most basic level Collation handles sorting. BUT, the comparison rules defined by the chosen Collation are used in many places outside of user queries against user data.
COLLATE SQL_Latin1_General_CP1_CI_AS
do?" means "What does the COLLATE
clause of CREATE DATABASE
do?", then:The COLLATE {collation_name}
clause of the CREATE DATABASE
statement specifies the default Collation of the Database, and not the Server; Database-level and Server-level default Collations control different things.
Server (i.e. Instance)-level controls:
master
, model
, msdb
, and tempdb
.tempdb
, it is then the default Collation for string columns in temporary tables (global and local), but not table variables.master
, it is then the Collation used for Server-level data, such as Database names (i.e. name
column in sys.databases
), Login names, etc.GOTO
labelsCOLLATE
clause is missingDatabase-level controls:
CHAR
, VARCHAR
, NCHAR
, NVARCHAR
, TEXT
, and NTEXT
-- but don't use TEXT
or NTEXT
) when the COLLATE
clause is missing from the column definition. This goes for both CREATE TABLE
and ALTER TABLE ... ADD
statements.'some text'
) and string variables (i.e. @StringVariable
). This Collation is only ever used when comparing strings and variables to other strings and variables. When comparing strings / variables to columns, then the Collation of the column will be used.sys.objects
), column names (i.e. sys.columns
), index names (i.e. sys.indexes
), etc.Also:
Latin1
does not mean "ASCII" since standard ASCII only covers values 0 - 127, and all code pages (that can be represented in SQL Server, and even NVARCHAR
) map those same 128 values to the same characters.COLLATE SQL_Latin1_General_CP1_CI_AS
do?" means "What does this particular collation do?", then:Because the name start with SQL_
, this is a SQL Server collation, not a Windows collation. These are definitely obsolete, even if not officially deprecated, and are mainly for pre-SQL Server 2000 compatibility. Although, quite unfortunately SQL_Latin1_General_CP1_CI_AS
is very common due to it being the default when installing on an OS using US English as its language. These collations should be avoided if at all possible.
Windows collations (those with names not starting with SQL_
) are newer, more functional, have consistent sorting between VARCHAR
and NVARCHAR
for the same values, and are being updated with additional / corrected sort weights and uppercase/lowercase mappings. These collations also don't have the potential performance problem that the SQL Server collations have: Impact on Indexes When Mixing VARCHAR and NVARCHAR Types.
Latin1_General
is the culture / locale.
NCHAR
, NVARCHAR
, and NTEXT
data this determines the linguistic rules used for sorting and comparison.CHAR
, VARCHAR
, and TEXT
data (columns, literals, and variables) this determines the:
Latin1_General
collations use code page 1252, Hebrew
collations use code page 1255, and so on.CP{code_page}
or {version}
CP{code_page}
, is the 8-bit code page that determines what characters map to values 128 - 255. While there are four code pages for Double-Byte Character Sets (DBCS) that can use 2-byte combinations to create more than 256 characters, these are not available for the SQL Server collations.For Windows collations: {version}
, while not present in all collation names, refers to the SQL Server version in which the collation was introduced (for the most part). Windows collations with no version number in the name are version 80
(meaning SQL Server 2000 as that is version 8.0). Not all versions of SQL Server come with new collations, so there are gaps in the version numbers. There are some that are 90
(for SQL Server 2005, which is version 9.0), most are 100
(for SQL Server 2008, version 10.0), and a small set has 140
(for SQL Server 2017, version 14.0).
I said "for the most part" because the collations ending in _SC
were introduced in SQL Server 2012 (version 11.0), but the underlying data wasn't new, they merely added support for supplementary characters for the built-in functions. So, those endings exist for version 90
and 100
collations, but only starting in SQL Server 2012.
CS
= case-sensitive or CI
= case-insensitiveAS
= accent-sensitive or AI
= accent-insensitiveKS
= Kana type-sensitive or missing = Kana type-insensitiveWS
= width-sensitive or missing = width insensitiveVSS
= variation selector sensitive (only available in the version 140 collations) or missing = variation selector insensitiveOptional last piece:
_SC
at the end means "Supplementary Character support". The "support" only affects how the built-in functions interpret surrogate pairs (which are how supplementary characters are encoded in UTF-16). Without _SC
at the end (or _140_
in the middle), built-in functions don't see a single supplementary character, but instead see two meaningless code points that make up the surrogate pair. This ending can be added to any non-binary, version 90 or 100 collation._BIN
or _BIN2
at the end means "binary" sorting and comparison. Data is still stored the same, but there are no linguistic rules. This ending is never combined with any of the 5 sensitivities or _SC
. _BIN
is the older style, and _BIN2
is the newer, more accurate style. If using SQL Server 2005 or newer, use _BIN2
. For details on the differences between _BIN
and _BIN2
, please see: Differences Between the Various Binary Collations (Cultures, Versions, and BIN vs BIN2)._UTF8
is a new option as of SQL Server 2019. It's an 8-bit encoding that allows for Unicode data to be stored in VARCHAR
and CHAR
datatypes (but not the deprecated TEXT
datatype). This option can only be used on collations that support supplementary characters (i.e. version 90 or 100 collations with _SC
in their name, and version 140 collations). There is also a single binary _UTF8
collation (_BIN2
, not _BIN
).
PLEASE NOTE: UTF-8 was designed / created for compatibility with environments / code that are set up for 8-bit encodings yet want to support Unicode. Even though there are a few scenarios where UTF-8 can provide up to 50% space savings as compared to NVARCHAR
, that is a side-effect and has a cost of a slight hit to performance in many / most operations. If you need this for compatibility, then the cost is acceptable. If you want this for space-savings, you had better test, and TEST AGAIN. Testing includes all functionality, and more than just a few rows of data. Be warned that UTF-8 collations work best when ALL columns, and the database itself, are using VARCHAR
data (columns, variables, string literals) with a _UTF8
collation. This is the natural state for anyone using this for compatibility, but not for those hoping to use it for space-savings. Be careful when mixing VARCHAR data using a _UTF8
collation with either VARCHAR
data using non-_UTF8
collations or NVARCHAR
data, as you might experience odd behavior / data loss. For more details on the new UTF-8 collations, please see: Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?
as in this post, using .is
and the attribute selector []
, you can easily add a function (or prototype):
function hasAttr($sel,attr) {
return $sel.is('['+attr+']');
}
This is very good discussion. I had one of those moments when I wished or lets say hoped (successfully that I might add) to reinvent the wheel be it a square one. Any ways above is good discussion, so any one coming here looking for what is the difference between Element property and attribute. here is my penny worth and I did have to find it out hard way. I would keep it simple so no extraordinary tech jargon.
suppose we have a variable calls 'A'. what we are used to is as following.
Below will throw an error because simply it put its is kind of object that can only have one property and that is singular left hand side = singular right hand side object. Every thing else is ignored and tossed out in bin.
let A = 'f';
A.b =2;
console.log(A.b);
_x000D_
who has decided that it has to be singular = singular. People who make JavaScript and html standards and thats how engines work.
Lets change the example.
let A = {};
A.b =2;
console.log(A.b);
_x000D_
This time it works ..... because we have explicitly told it so and who decided we can tell it in this case but not in previous case. Again people who make JavaScript and html standards.
I hope we are on this lets complicate it further
let A = {};
A.attribute ={};
A.attribute.b=5;
console.log(A.attribute.b); // will work
console.log(A.b); // will not work
_x000D_
What we have done is tree of sorts level 1 then sub levels of non-singular object. Unless you know what is where and and call it so it will work else no.
This is what goes on with HTMLDOM when its parsed and painted a DOm tree is created for each and every HTML ELEMENT. Each has level of properties per say. Some are predefined and some are not. This is where ID and VALUE bits come on. Behind the scene they are mapped on 1:1 between level 1 property and sun level property aka attributes. Thus changing one changes the other. This is were object getter ans setter scheme of things plays role.
let A = {
attribute :{
id:'',
value:''
},
getAttributes: function (n) {
return this.attribute[n];
},
setAttributes: function (n,nn){
this.attribute[n] = nn;
if(this[n]) this[n] = nn;
},
id:'',
value:''
};
A.id = 5;
console.log(A.id);
console.log(A.getAttributes('id'));
A.setAttributes('id',7)
console.log(A.id);
console.log(A.getAttributes('id'));
A.setAttributes('ids',7)
console.log(A.ids);
console.log(A.getAttributes('ids'));
A.idsss=7;
console.log(A.idsss);
console.log(A.getAttributes('idsss'));
_x000D_
This is the point as shown above ELEMENTS has another set of so called property list attributes and it has its own main properties. there some predefined properties between the two and are mapped as 1:1 e.g. ID is common to every one but value is not nor is src. when the parser reaches that point it simply pulls up dictionary as to what to when such and such are present.
All elements have properties and attributes and some of the items between them are common. What is common in one is not common in another.
In old days of HTML3 and what not we worked with html first then on to JS. Now days its other way around and so has using inline onlclick become such an abomination. Things have moved forward in HTML5 where there are many property lists accessible as collection e.g. class, style. In old days color was a property now that is moved to css for handling is no longer valid attribute.
Element.attributes is sub property list with in Element property.
Unless you could change the getter and setter of Element property which is almost high unlikely as it would break hell on all functionality is usually not writable off the bat just because we defined something as A.item does not necessarily mean Js engine will also run another line of function to add it into Element.attributes.item.
I hope this gives some headway clarification as to what is what. Just for the sake of this I tried Element.prototype.setAttribute with custom function it just broke loose whole thing all together, as it overrode native bunch of functions that set attribute function was playing behind the scene.
Try this:
<select>
<option value="">
<option>Option 1
<option>Option 2
<option>Option 3
</select>
Validates in HTML5. Works with required
attribute in select element. Can be re-selected. Works in Google Chrome 45, Internet Explorer 11, Edge, Firefox 41.
You don't need two JScrollPanes
.
Example:
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
// Add the scroll pane into the content pane
JFrame f = new JFrame();
f.getContentPane().add(sp);
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
If you want to use the catch()
of the Observable
you need to use Observable.throw()
method before delegating the error response to a method
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
constructor(private http: AuthHttp) {}_x000D_
_x000D_
envirArquivos(order): Observable < any > {_x000D_
const headers = new Headers();_x000D_
return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
new ResponseOptions({_x000D_
headers: headers_x000D_
}))_x000D_
.map(response => response.json())_x000D_
.catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
}_x000D_
_x000D_
errorHandler(error: any): void {_x000D_
console.log(error)_x000D_
}_x000D_
}
_x000D_
Using Observable.throw()
worked for me
Woo-hoo! It works with some hack!
According to this comment you need to:
Manually edit Microsoft.CSharp.DesignTime.targets
located in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed
(for VS Community edition, modify path for other editions), append ClassDesigner
value to ProjectCapability
(right pane):
Restart VS.
MyClasses.cd
with following content:
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>
Bingo. Now you may open this file in VS. You will see error message "Object reference not set to an instance of object" once after VS starts, but diagram works.
Checked on VS 2017 Community Edition, v15.3.0 with .NETCore 2.0 app/project:
GitHub issue expected to fix in v15.5
2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip
rel=0&autoplay
Example Below: .
<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.
This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;
public class Encrypt {
static byte [] arr = {1,2,3,4,5,6,7,8,9};
// static byte [] arr = new byte[16];
public static void main(String...args) {
try {
// System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
Base64.Decoder decoder = Base64.getDecoder();
// static byte [] arr = new byte[16];
Security.setProperty("crypto.policy", "unlimited");
String key = "Your key";
// System.out.println("-------" + key);
String value = "Hey, i am adnan";
String IV = "0123456789abcdef";
// System.out.println(value);
// log.info(value);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
// IvParameterSpec iv = new IvParameterSpec(arr);
// System.out.println(key);
SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
// System.out.println(skeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// System.out.println("ddddddddd"+IV);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// System.out.println(cipher.getIV());
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
// vars.put("input-1",encryptedString);
// log.info("beanshell");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.
tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000
This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.
I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:
#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000
Well, since nobody else has stepped up, I'll write the easy code to do this:
x = ms / 1000
seconds = x % 60
x /= 60
minutes = x % 60
x /= 60
hours = x % 24
x /= 24
days = x
I'm just glad you stopped at days and didn't ask for months. :)
Note that in the above, it is assumed that /
represents truncating integer division. If you use this code in a language where /
represents floating point division, you will need to manually truncate the results of the division as needed.
Have you start by reading the information on this on Wikipedia - Block cipher modes of operation? Then follow the reference link on Wikipedia to NIST: Recommendation for Block Cipher Modes of Operation.
JavaScript runs synchronously, so whatever you place after each()
will not run until each()
is complete.
Consider the following test:
var count = 0;
var array = [];
// populate an array with 1,000,000 entries
for(var i = 0; i < 1000000; i++) {
array.push(i);
}
// use each to iterate over the array, incrementing count each time
$.each(array, function() {
count++
});
// the alert won't get called until the 'each' is done
// as evidenced by the value of count
alert(count);
When the alert is called, count will equal 1000000 because the alert won't run until each()
is done.
It's in the standard library.
>>> from fractions import gcd
>>> gcd(20,8)
4
Source code from the inspect
module in Python 2.7:
>>> print inspect.getsource(gcd)
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
As of Python 3.5, gcd
is in the math
module; the one in fractions
is deprecated. Moreover, inspect.getsource
no longer returns explanatory source code for either method.
I don't have code to hand, but I always liked the approach of building a 2D lookup table of size 256 * 256 chars (RFC 1978, PPP Predictor Compression Protocol). To compress a string you loop over each char and use the lookup table to get the 'predicted' next char using the current and previous char as indexes into the table. If there is a match you write a single 1 bit, otherwise write a 0, the char and update the lookup table with the current char. This approach basically maintains a dynamic (and crude) lookup table of the most probable next character in the data stream.
You can start with a zeroed lookup table, but obviosuly it works best on very short strings if it is initialised with the most likely character for each character pair, for example, for the English language. So long as the initial lookup table is the same for compression and decompression you don't need to emit it into the compressed data.
This algorithm doesn't give a brilliant compression ratio, but it is incredibly frugal with memory and CPU resources and can also work on a continuous stream of data - the decompressor maintains its own copy of the lookup table as it decompresses, thus the lookup table adjusts to the type of data being compressed.
Back in 2010 we had the same problem and i successfully employed GoogleDocs with our small Agile Development team (8 Devs in 3 Countries).
GoogleDrawing will serve in the exact same way as a physical Scrum board would, with all the upsides of full flexibilty and also the downsides of zero automation but with the big additional upside of being virtual and accessible from anywhere with an internet connection.
It also was used for the retrospective at the end of each Sprint
GoogleSpreadsheet was used for a concise list of all the tickets from our bug tracking system (Redmine, manually transfered) and also for the (manually updated, albeit with formulas to calculate the progress) burndown chart.
The combination of these different elements is actually quite powerful, as you have the full flexibility over the content and its representation and can have your team communicate via VoIP while all are looking at the same documents and can modify them in real-time.
Here an example of the docs used in a sprint (all sensitive data removed):
As mentioned before, the only downside is the fact that you have to invest some time to maintain and prepare the data for each sprint, but for us that was hugely outweighed by the flexibility and accessibility that the Team of GoogleDocs + VoIP gave us.
There is an much easier way to do this.
Just open the file inspector and select a "global tint".
You can also set an app’s tint color in Interface Builder. The Global Tint menu in the Interface Builder Document section of the File inspector lets you open the Colors window or choose a specific color.
Also see:
Try with cURL request for cross-domain.
If you are working through third party APIs or getting data through CROSS-DOMAIN, it is always recommended to use cURL script (server side) which is more secure.
I always prefer cURL script.
Using CliWrap:
var result = await Cli.Wrap("foobar.bat").ExecuteBufferedAsync();
var exitCode = result.ExitCode;
var stdOut = result.StandardOutput;
Late to the party, but might be of interest...
I find a combination of labs
and guides
specification useful in many cases:
You want nothing but a grid and a background:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
labs(x = NULL, y = NULL) +
guides(x = "none", y = "none")
You want to only suppress the tick-mark label of one or both axes:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
guides(x = "none", y = "none")
I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:
So in your example above I would simply write:
if User.objects.filter(email = cleaned_info['username']).exists():
# at least one object satisfying query exists
else:
# no object satisfying query exists
The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:
git update-index --skip-worktree .classpath .gitignore
It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.
Running git rm --cached
doesn't work for the scenario mentioned in the question. If I simplify the question, it says:
How to have
.classpath
and.project
on the repo while each one can change it locally and git ignores this change?
As I commented under the accepted answer, the drawback of git rm --cached
is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath
and .project
won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.
Based on git documentaion:
Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.
More details is available here.
From the documentation,
Positioning your Toast
A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the
setGravity(int, int, int)
method. This accepts three parameters: aGravity
constant, anx-position
offset, and ay-position
offset.For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.
In PowerShell, I like to use:
robocopy src dest | Out-Null
It avoids having to remember all the command line switches.
If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors
) in a .htaccess file in any directory by adding the following line:
php_flag display_errors off
additionally, you can add error logging to a file:
php_flag log_errors on
Use Access's VBA function Replace(text, find, replacement)
:
Dim result As String
result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")
You can add other repo first as a remote to your current repo:
git remote add other_name PATH_TO_OTHER_REPO
then fetch brach from that remote:
git fetch other_name branch_name:branch_name
this creates that branch as a new branch in your current repo, then you can diff that branch with any of your branches, for example, to compare current branch against new branch(branch_name):
git diff branch_name
This worked for me, curly braces are not required.
ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"
notification.icon here is scope variable.
UPDATE: TensorFlow supports Python 3.6 on Windows since version 1.2.0 (see the release notes)
TensorFlow only supports Python 3.5 64-bit as of now. Support for Python 3.6 is a work in progress and you can track it here as well as chime in the discussion.
The only alternative to use Python 3.6 with TensorFlow on Windows currently is building TF from source.
If you don't want to uninstall your Anaconda distribution for Python 3.6 and install a previous release you can create a conda environment for Python=3.5 as in:
conda create --name tensorflow python=3.5
activate tensorflow
pip install tensorflow-gpu
public static Set<Double> getMode(double[] data) {
if (data.length == 0) {
return new TreeSet<>();
}
TreeMap<Double, Integer> map = new TreeMap<>(); //Map Keys are array values and Map Values are how many times each key appears in the array
for (int index = 0; index != data.length; ++index) {
double value = data[index];
if (!map.containsKey(value)) {
map.put(value, 1); //first time, put one
}
else {
map.put(value, map.get(value) + 1); //seen it again increment count
}
}
Set<Double> modes = new TreeSet<>(); //result set of modes, min to max sorted
int maxCount = 1;
Iterator<Integer> modeApperance = map.values().iterator();
while (modeApperance.hasNext()) {
maxCount = Math.max(maxCount, modeApperance.next()); //go through all the value counts
}
for (double key : map.keySet()) {
if (map.get(key) == maxCount) { //if this key's value is max
modes.add(key); //get it
}
}
return modes;
}
//std dev function for good measure
public static double getStandardDeviation(double[] data) {
final double mean = getMean(data);
double sum = 0;
for (int index = 0; index != data.length; ++index) {
sum += Math.pow(Math.abs(mean - data[index]), 2);
}
return Math.sqrt(sum / data.length);
}
public static double getMean(double[] data) {
if (data.length == 0) {
return 0;
}
double sum = 0.0;
for (int index = 0; index != data.length; ++index) {
sum += data[index];
}
return sum / data.length;
}
//by creating a copy array and sorting it, this function can take any data.
public static double getMedian(double[] data) {
double[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return (copy.length % 2 != 0) ? copy[copy.length / 2] : (copy[copy.length / 2] + copy[(copy.length / 2) - 1]) / 2;
}
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
If you want to import a specific function or class from a module, you can do this:
import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
My simple, simple, simple approach! =D
Code
string_to_test = "The criminals stole $1,000,000 in jewels."
chars_to_check = ["$", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in chars_to_check:
if char in string_to_test:
print("Char \"" + char + "\" detected!")
Output
Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!
Thanks!
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
If you are lazy, and have a lot of RAM, create a sieve of Eratosthenes which is practically a giant array from which you kicked all numbers that are not prime. From then on every prime "probability" test will be super quick. The upper limit for this solution for fast results is the amount of you RAM. The upper limit for this solution for superslow results is your hard disk's capacity.
exec has memory limitation of buffer size of 512k. In this case it is better to use spawn. With spawn one has access to stdout of executed command at run time
var spawn = require('child_process').spawn;
var prc = spawn('java', ['-jar', '-Xmx512M', '-Dfile.encoding=utf8', 'script/importlistings.jar']);
//noinspection JSUnresolvedFunction
prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
var str = data.toString()
var lines = str.split(/(\r?\n)/g);
console.log(lines.join(""));
});
prc.on('close', function (code) {
console.log('process exit code ' + code);
});
If available you can probe the current user account with posix_geteuid
and then get the user name with posix_getpwuid
.
$username = posix_getpwuid(posix_geteuid())['name'];
If you are running in safe mode however (which is often the case when exec is disabled), then it's unlikely that your PHP process is running under anything but the default www-data
or apache
account.
even cleaner:
public static bool TryCast<T>(ref T t, object o)
{
if (!(o is T))
{
return false;
}
t = (T)o;
return true;
}
Use the context-parameter
$("#testdiv",parent.document)
But if you really use a popup, you need to access opener instead of parent
$("#testdiv",opener.document)
If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:
echo '<p style="color: red; text-align: center">
Request has been sent. Please wait for my reply!
</p>';
Variables can point to anywhere they want.. An error will be thrown if you do the following:
a = "dog"
print a #dog
a[1] = "g" #ERROR!!!!!! STRINGS ARE IMMUTABLE
I think this will probably answer your question. Here's what I wrote there:
Here's a very general answer. Say the camera's at (Xc, Yc, Zc) and the point you want to project is P = (X, Y, Z). The distance from the camera to the 2D plane onto which you are projecting is F (so the equation of the plane is Z-Zc=F). The 2D coordinates of P projected onto the plane are (X', Y').
Then, very simply:
X' = ((X - Xc) * (F/Z)) + Xc
Y' = ((Y - Yc) * (F/Z)) + Yc
If your camera is the origin, then this simplifies to:
X' = X * (F/Z)
Y' = Y * (F/Z)
Thanks! to all above answers. I hope you have a .p12 file. Now, open terminal write following command. Set terminal to the path where you have put .12 file.
$ openssl pkcs12 -in yourCertifcate.p12 -out pemAPNSCert.pem -nodes
Enter Import Password: <Just enter your certificate password>
MAC verified OK
Now your .pem file is generated.
Verify .pem file First, open the .pem in a text editor to view its content. The certificate content should be in format as shown below. Make sure the pem file contains both Certificate content(from BEGIN CERTIFICATE to END CERTIFICATE) as well as Certificate Private Key (from BEGIN PRIVATE KEY to END PRIVATE KEY) :
> Bag Attributes
> friendlyName: Apple Push Services:<Bundle ID>
> localKeyID: <> subject=<>
> -----BEGIN CERTIFICATE-----
>
> <Certificate Content>
>
> -----END CERTIFICATE----- Bag Attributes
> friendlyName: <>
> localKeyID: <> Key Attributes: <No Attributes>
> -----BEGIN PRIVATE KEY-----
>
> <Certificate Private Key>
>
> -----END PRIVATE KEY-----
Also, you check the validity of the certificate by going to SSLShopper Certificate Decoder and paste the Certificate Content (from BEGIN CERTIFICATE to END CERTIFICATE) to get all the info about the certificate as shown below:
You can also sometimes get this error if you try to decrypt a secret while su
-ed to a different user on a system with GPG 2.x installed. This bug has been reported against RHEL 6 but there is no fix available; apparently this is due to some design decisions in GPG 2.x. One workaround suggested in the bug report is to run the decryption inside of a tmux or screen session. More reading here.
After updating the manifest file, instead of building your project, go to command line and reach the path ...bld\Debug\platforms\android. Run the command "ant release". Your new release.apk file will have a new version code.
use .empty()
$('select').empty().append('whatever');
you can also use .html()
but note
When
.html()
is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:
alternative: --- If you want only option elements to-be-remove, use .remove()
$('select option').remove();
This is an iterable function without yield
. It make use of the iter
function and a closure which keeps it's state in a mutable (list
) in the enclosing scope for python 2.
def count(low, high):
counter = [0]
def tmp():
val = low + counter[0]
if val < high:
counter[0] += 1
return val
return None
return iter(tmp, None)
For Python 3, closure state is kept in an immutable in the enclosing scope and nonlocal
is used in local scope to update the state variable.
def count(low, high):
counter = 0
def tmp():
nonlocal counter
val = low + counter
if val < high:
counter += 1
return val
return None
return iter(tmp, None)
Test;
for i in count(1,10):
print(i)
1
2
3
4
5
6
7
8
9
Try to create remote origin first, maybe is missing because you change name of the remote repo
git remote add origin URL_TO_YOUR_REPO
Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):
obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);
Or as an extension method:
public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
{
var type = typeof(T);
var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
return method.Invoke(obj, args);
}
Note:
If the desired method is in a superclass of obj
the T
generic must be explicitly set to the type of the superclass.
If the method is asynchronous you can use await (Task) obj.InvokeMethod(…)
.
Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).
function empty(mixed_var) {
if (!mixed_var || mixed_var == '0') {
return true;
}
if (typeof mixed_var == 'object') {
for (var k in mixed_var) {
return false;
}
return true;
}
return false;
}
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty(0);
// returns 5: true
// example 6: empty('0');
// returns 6: true
// example 7: empty(function(){});
// returns 7: false
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}
in MYSQL 5.7, max_allowed_packet
is at most 1G. if you want to set it to 4G, it would failed without error and warning.
If you're using Bootstrap 4:
<form class="d-flex">
<label for="myInput" class="align-items-center">Sample label</label>
<input type="text" id="myInput" placeholder="Sample Input" class="flex-grow-1"/>
</form>
Better yet, use what's built into Bootstrap:
<form>
<div class="input-group">
<div class="input-group-prepend">
<label for="myInput" class="input-group-text">Default</label>
</div>
<input type="text" class="form-control" id="myInput">
</div>
</form>
Code for adding fragment
public Fragment getItem(int position) {
switch (position){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
default:
break;
}
return null;
}
Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
Later you can make necessary corrections.. It worked for me.
Try adding the below code to the class that you want to use
[Serializable()]
public partial class Class
{
Then, in your javascript:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
Now you can look at the console, click on the statement and see what is inside blah
The answer provided by Joe Stefanelli is already correct.
SELECT name FROM (SELECT name FROM agentinformation) as a
We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.
Statements that include a subquery usually take one of these forms:
Check for more subquery rules and subquery types.
More examples of Nested Subqueries.
IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.
ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The
e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.
e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.
If you don't want to register a listener on every component,
you could add your own KeyEventDispatcher
to the KeyboardFocusManager
:
public class MyFrame extends JFrame {
private class MyDispatcher implements KeyEventDispatcher {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println("tester");
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
System.out.println("2test2");
} else if (e.getID() == KeyEvent.KEY_TYPED) {
System.out.println("3test3");
}
return false;
}
}
public MyFrame() {
add(new JTextField());
System.out.println("test");
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new MyDispatcher());
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.
I use a batch script to compile and run C#:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2
@echo off
if errorlevel 1 (
pause
exit
)
start %1 %1
I call it like this:
C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"
I also have a shortcut in Notepad++, which you can define by going to Run > Run...:
C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"
I assigned this shortcut to my F5 key for maximum laziness.
Swift 4
textField.addTarget(self, action: #selector(textIsChanging), for: UIControlEvents.editingChanged)
@objc func textIsChanging(_ textField:UITextField) {
print ("TextField is changing")
}
If you want to make a change once the user has typed in completely (It will be called once user dismiss keyboard or press enter).
textField.addTarget(self, action: #selector(textDidChange), for: UIControlEvents.editingDidEnd)
@objc func textDidChange(_ textField:UITextField) {
print ("TextField did changed")
}
You can change the height of a form by doing the following where you want to change the size (substitute '10' for your size):
this.Height = 10;
This can be done with the width as well:
this.Width = 10;
This can all be done easily with linq. This will find any types that are a subclass of generic base class GenericBaseType.
IEnumerable<Type> allTypes = Assembly.GetExecutingAssembly().GetTypes();
IEnumerable<Type> mySubclasses = allTypes.Where(t => t.BaseType != null
&& t.BaseType.IsGenericType
&& t.BaseType.GetGenericTypeDefinition() == typeof(GenericBaseType<,>));
This is for Color
to Brush
....
you can't convert it, you have to make a new brush....
SolidColorBrush brush = new SolidColorBrush( myColor );
now, if you need it in XAML, you COULD make a custom value converter and use that in a binding
The simplest approach would be to create a method that returns a DateInterval from the DateTime::diff of the relative time in $seconds from the current time $now which you can then chain and format. For example:-
public function toDateInterval($seconds) {
return date_create('@' . (($now = time()) + $seconds))->diff(date_create('@' . $now));
}
Now chain your method call to DateInterval::format
echo $this->toDateInterval(1640467)->format('%a days %h hours %i minutes'));
Result:
18 days 23 hours 41 minutes
Just complementing Hovercraft Full Of Eels's solution:
I reworked his code, tweaked it a bit, adding a grid, axis labels and now the Y-axis goes from the minimum value present up to the maximum value. I planned on adding a couple of getters/setters but I didn't need them, you can add them if you want.
Here is the Gist link, I'll also paste the code below: GraphPanel on Gist
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GraphPanel extends JPanel {
private int width = 800;
private int heigth = 400;
private int padding = 25;
private int labelPadding = 25;
private Color lineColor = new Color(44, 102, 230, 180);
private Color pointColor = new Color(100, 100, 100, 180);
private Color gridColor = new Color(200, 200, 200, 200);
private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
private int pointWidth = 4;
private int numberYDivisions = 10;
private List<Double> scores;
public GraphPanel(List<Double> scores) {
this.scores = scores;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1);
double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());
List<Point> graphPoints = new ArrayList<>();
for (int i = 0; i < scores.size(); i++) {
int x1 = (int) (i * xScale + padding + labelPadding);
int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
graphPoints.add(new Point(x1, y1));
}
// draw white background
g2.setColor(Color.WHITE);
g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
g2.setColor(Color.BLACK);
// create hatch marks and grid lines for y axis.
for (int i = 0; i < numberYDivisions + 1; i++) {
int x0 = padding + labelPadding;
int x1 = pointWidth + padding + labelPadding;
int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
int y1 = y0;
if (scores.size() > 0) {
g2.setColor(gridColor);
g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
g2.setColor(Color.BLACK);
String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(yLabel);
g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
}
g2.drawLine(x0, y0, x1, y1);
}
// and for x axis
for (int i = 0; i < scores.size(); i++) {
if (scores.size() > 1) {
int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding;
int x1 = x0;
int y0 = getHeight() - padding - labelPadding;
int y1 = y0 - pointWidth;
if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
g2.setColor(gridColor);
g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
g2.setColor(Color.BLACK);
String xLabel = i + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(xLabel);
g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
}
g2.drawLine(x0, y0, x1, y1);
}
}
// create x and y axes
g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);
Stroke oldStroke = g2.getStroke();
g2.setColor(lineColor);
g2.setStroke(GRAPH_STROKE);
for (int i = 0; i < graphPoints.size() - 1; i++) {
int x1 = graphPoints.get(i).x;
int y1 = graphPoints.get(i).y;
int x2 = graphPoints.get(i + 1).x;
int y2 = graphPoints.get(i + 1).y;
g2.drawLine(x1, y1, x2, y2);
}
g2.setStroke(oldStroke);
g2.setColor(pointColor);
for (int i = 0; i < graphPoints.size(); i++) {
int x = graphPoints.get(i).x - pointWidth / 2;
int y = graphPoints.get(i).y - pointWidth / 2;
int ovalW = pointWidth;
int ovalH = pointWidth;
g2.fillOval(x, y, ovalW, ovalH);
}
}
// @Override
// public Dimension getPreferredSize() {
// return new Dimension(width, heigth);
// }
private double getMinScore() {
double minScore = Double.MAX_VALUE;
for (Double score : scores) {
minScore = Math.min(minScore, score);
}
return minScore;
}
private double getMaxScore() {
double maxScore = Double.MIN_VALUE;
for (Double score : scores) {
maxScore = Math.max(maxScore, score);
}
return maxScore;
}
public void setScores(List<Double> scores) {
this.scores = scores;
invalidate();
this.repaint();
}
public List<Double> getScores() {
return scores;
}
private static void createAndShowGui() {
List<Double> scores = new ArrayList<>();
Random random = new Random();
int maxDataPoints = 40;
int maxScore = 10;
for (int i = 0; i < maxDataPoints; i++) {
scores.add((double) random.nextDouble() * maxScore);
// scores.add((double) i);
}
GraphPanel mainPanel = new GraphPanel(scores);
mainPanel.setPreferredSize(new Dimension(800, 600));
JFrame frame = new JFrame("DrawGraph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
It looks like this:
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
Intel HD Graphics is usually the on-CPU graphics chip in newer Core i3/i5/i7 processors.
As far as I know it doesn't support CUDA (which is a proprietary NVidia technology), but OpenCL is supported by NVidia, ATi and Intel.
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
I depends on what is the regexp language you use, but informally, it would be:
[:alpha:][:alpha:][:digit:][:digit:][:digit:][:digit:][:digit:][:digit:]
where [:alpha:] = [a-zA-Z]
and [:digit:] = [0-9]
If you use a regexp language that allows finite repetitions, that would look like:
[:alpha:]{2}[:digit:]{6}
The correct syntax depends on the particular language you're using, but that is the idea.
You can get around that limit by using subst if you need to.
As of SQL Server 2012 you no longer have to go through the hassle of deleting the bin file (which causes other side effects). You should be able to press the delete key within the MRU list of the Server Name dropdown in the Connect to Server dialog. This is documented in this Connect item and this blog post.
Note that if you have multiple entries for a single server name (e.g. one with Windows and one with SQL Auth), you won't be able to tell which one you're deleting.
That task should be done by the next layer up in your software stack. SQL is a data repository, not a presentation system
You can do it with
CONVERT(VARCHAR(10), fmdate(), 101)
But you shouldn't
Based on Xavier's answer, I wrote a Google chrome extension NuTake to add links to the Nuget.org package pages.
For static files like pdfs, Word docs, etc. just use Express's static function in your config:
// Express config
var app = express().configure(function () {
this.use('/public', express.static('public')); // <-- This right here
});
And then just put all your files inside that 'public' folder, for example:
/public/docs/my_word_doc.docx
And then a regular old link will allow the user to download it:
<a href="public/docs/my_word_doc.docx">My Word Doc</a>
For the controls embedded in WPF Extended WPF Toolkit Release 1.4.0, please refer http://elegantcode.com/2011/04/08/extended-wpf-toolkit-release-1-4-0/
For Calendar & DatePicker Walkthrough please refer, http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx
And you can cutomize the look and feel by Microsoft Expression Studio [Use Edit Template option]
Sample shows here:
Add following namespaces to xaml page
xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended"
xmlns:Microsoft_Windows_Controls_Core_Converters="clr-namespace:Microsoft.Windows.Controls.Core.Converters;assembly=WPFToolkit.Extended"
xmlns:Microsoft_Windows_Controls_Chromes="clr-namespace:Microsoft.Windows.Controls.Chromes;assembly=WPFToolkit.Extended"
Add followings to Page/Window resources
<!--DateTimePicker Customized Style-->
<Style x:Key="DateTimePickerStyle1" TargetType="{x:Type toolkit:DateTimePicker}">
<Setter Property="TimeWatermarkTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="WatermarkTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type toolkit:DateTimePicker}">
<Border>
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<toolkit:DateTimeUpDown AllowSpin="{TemplateBinding AllowSpin}"
BorderThickness="1,1,0,1"
FormatString="{TemplateBinding FormatString}"
Format="{TemplateBinding Format}"
ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}"
Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"
WatermarkTemplate="{TemplateBinding WatermarkTemplate}"
Watermark="{TemplateBinding Watermark}"
Foreground="#FFEFE3E3"
BorderBrush="#FFEBB31A">
<toolkit:DateTimeUpDown.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF2F2828" Offset="1"/>
</LinearGradientBrush>
</toolkit:DateTimeUpDown.Background>
</toolkit:DateTimeUpDown>
<ToggleButton x:Name="_calendarToggleButton"
Background="{x:Null}" Grid.Column="1" IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.IsHitTestVisible>
<Binding Path="IsOpen" RelativeSource="{RelativeSource TemplatedParent}">
<Binding.Converter>
<Microsoft_Windows_Controls_Core_Converters:InverseBoolConverter/>
</Binding.Converter>
</Binding>
</ToggleButton.IsHitTestVisible>
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid SnapsToDevicePixels="True">
<Microsoft_Windows_Controls_Chromes:ButtonChrome x:Name="ToggleButtonChrome" CornerRadius="0,2.75,2.75,0" InnerCornerRadius="0,1.75,1.75,0" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" BorderBrush="{x:Null}">
<Microsoft_Windows_Controls_Chromes:ButtonChrome.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FFF3F3F3" Offset="1"/>
<GradientStop Color="#7FC0A112"/>
</LinearGradientBrush>
</Microsoft_Windows_Controls_Chromes:ButtonChrome.Background>
</Microsoft_Windows_Controls_Chromes:ButtonChrome>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Stretch"/>
<Grid x:Name="arrowGlyph" Grid.Column="1" IsHitTestVisible="False" Margin="5">
<Path Data="M0,1C0,1 0,0 0,0 0,0 3,0 3,0 3,0 3,1 3,1 3,1 4,1 4,1 4,1 4,0 4,0 4,0 7,0 7,0 7,0 7,1 7,1 7,1 6,1 6,1 6,1 6,2 6,2 6,2 5,2 5,2 5,2 5,3 5,3 5,3 4,3 4,3 4,3 4,4 4,4 4,4 3,4 3,4 3,4 3,3 3,3 3,3 2,3 2,3 2,3 2,2 2,2 2,2 1,2 1,2 1,2 1,1 1,1 1,1 0,1 0,1z" Fill="#FF82E511" Height="4" Width="7"/>
</Grid>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
</ToggleButton>
</Grid>
<Popup IsOpen="{Binding IsChecked, ElementName=_calendarToggleButton}" StaysOpen="False">
<Border BorderThickness="1" Padding="3">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0"/>
<GradientStop Color="#FF8399A9" Offset="0.375"/>
<GradientStop Color="#FF718597" Offset="0.375"/>
<GradientStop Color="#FFD2C217" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Border.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#FFE9B116" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<StackPanel Background="{x:Null}">
<Calendar x:Name="Part_Calendar" BorderThickness="0" DisplayDate="2011-06-28" Background="#7FE0B41A"/>
<toolkit:TimePicker x:Name="Part_TimeUpDown" Format="ShortTime" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" WatermarkTemplate="{TemplateBinding TimeWatermarkTemplate}" Watermark="{TemplateBinding TimeWatermark}" Background="{x:Null}" Style="{DynamicResource TimePickerStyle1}"/>
</StackPanel>
</Border>
</Popup>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="TimePickerStyle1"
TargetType="{x:Type toolkit:TimePicker}">
<Setter Property="WatermarkTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type toolkit:TimePicker}">
<Border>
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid>
<toolkit:DateTimeUpDown x:Name="PART_TimeUpDown" AllowSpin="{TemplateBinding AllowSpin}" BorderThickness="1,1,0,1" FormatString="{TemplateBinding FormatString}" ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" WatermarkTemplate="{TemplateBinding WatermarkTemplate}" Watermark="{TemplateBinding Watermark}" Background="#7FE0B41A" BorderBrush="#FFF9F2F2">
<toolkit:DateTimeUpDown.Format>
<TemplateBinding Property="Format">
<TemplateBinding.Converter>
<Microsoft_Windows_Controls_Core_Converters:TimeFormatToDateTimeFormatConverter/>
</TemplateBinding.Converter>
</TemplateBinding>
</toolkit:DateTimeUpDown.Format>
</toolkit:DateTimeUpDown>
</Grid>
<ToggleButton x:Name="_timePickerToggleButton" Grid.Column="1" IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}" >
<ToggleButton.IsHitTestVisible>
<Binding Path="IsOpen" RelativeSource="{RelativeSource TemplatedParent}">
<Binding.Converter>
<Microsoft_Windows_Controls_Core_Converters:InverseBoolConverter/>
</Binding.Converter>
</Binding>
</ToggleButton.IsHitTestVisible>
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid SnapsToDevicePixels="True">
<Microsoft_Windows_Controls_Chromes:ButtonChrome x:Name="ToggleButtonChrome" CornerRadius="0,2.75,2.75,0" InnerCornerRadius="0,1.75,1.75,0" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Stretch"/>
<Grid x:Name="arrowGlyph" Grid.Column="1" IsHitTestVisible="False" Margin="5">
<Path Data="M0,1C0,1 0,0 0,0 0,0 3,0 3,0 3,0 3,1 3,1 3,1 4,1 4,1 4,1 4,0 4,0 4,0 7,0 7,0 7,0 7,1 7,1 7,1 6,1 6,1 6,1 6,2 6,2 6,2 5,2 5,2 5,2 5,3 5,3 5,3 4,3 4,3 4,3 4,4 4,4 4,4 3,4 3,4 3,4 3,3 3,3 3,3 2,3 2,3 2,3 2,2 2,2 2,2 1,2 1,2 1,2 1,1 1,1 1,1 0,1 0,1z" Fill="Black" Height="4" Width="7"/>
</Grid>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
</ToggleButton>
</Grid>
<Popup IsOpen="{Binding IsChecked, ElementName=_timePickerToggleButton}" StaysOpen="False">
<Border BorderThickness="1">
<Border.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#FFE7C857" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0"/>
<GradientStop Color="#FF8399A9" Offset="0.375"/>
<GradientStop Color="#FF718597" Offset="0.375"/>
<GradientStop Color="#FF617584" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Grid>
<ListBox x:Name="PART_TimeListItems" BorderThickness="0" DisplayMemberPath="Display" Height="130" Width="150" Background="#7FE0B41A">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Border" SnapsToDevicePixels="True">
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Margin="4"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="Border" Value="#FFE7F5FD"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" TargetName="Border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
</Border>
</Popup>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And in Window you can use the style as
Thanks,
ON DELETE CASCADE
It specifies that the child data is deleted when the parent data is deleted.
CREATE TABLE products
( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);
CREATE TABLE inventory
( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
ON DELETE CASCADE
);
For this foreign key, we have specified the ON DELETE CASCADE
clause which tells SQL Server to delete the corresponding records in the child table when the data in the parent table is deleted. So in this example, if a product_id value is deleted from the products table, the corresponding records in the inventory table that use this product_id will also be deleted.
Clean solution while staying with the nio API:
Files.isDirectory(path)
Files.isRegularFile(path)
Note that :
typeof $(this)
is JQuery object.
and
typeof $(this)[0]
is HTMLElement object
then :
if you want to apply .val()
on HTMLElement , you can add this extension .
HTMLElement.prototype.val=function(v){
if(typeof v!=='undefined'){this.value=v;return this;}
else{return this.value}
}
Then :
document.getElementById('myDiv').val() ==== $('#myDiv').val()
And
document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')
?????
INVERSE :Conversely? if you want to add value property to jQuery object , follow those steps :
Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .
Insert Line after L96 , add this code value:""
to init this new prop
Search on jQuery.fn.init
, it will be almost Line 2747
value
prop : (Before return statment add this.value=jQuery(selector).val()
)
In Visual Studio 2015 this shortcut opens a preview of the definition which even works through typedefs and #defines.
Ctrl + , (comma)
The link you gave seems to be attempting something different to the test you are trying to avoid repeating.
if (a == null || a=='')
tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).
The test you described can be replaced by:
if (!a)
Because in javascript, an empty string, and null, both evaluate to false in a boolean context.
Remove the function and check the output of:
var_dump(function_exists('parseDate'));
In which case, change the name of the function.
If you get false, you're including the file with that function twice, replace :
include
by
include_once
And replace :
require
by
require_once
EDIT : I'm just a little too late, post before beat me to it !
Simply add a -h
after adding your credentials using a -u -p
, and it will run with elevated privileges.
It is possible. Here is some step by step:
In $PROJECT_DIR/jni/Application.mk:
APP_STL := stlport_static
I tried using stlport_shared, but no luck. Same with libstdc++.
In $PROJECT_DIR/jni/Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
Nothing special here, but make sure your files are .cpp.
In $PROJECT_DIR/jni/hello-jni.cpp:
#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <iostream>
#include <vector>
#define LOG_TAG "hellojni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
// Comments omitted.
void
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
std::vector<std::string> vec;
// Go ahead and do some stuff with this vector of strings now.
}
#ifdef __cplusplus
}
#endif
The only thing that bite me here was #ifdef __cplusplus.
Watch the directories.
To compile, use ndk-build clean && ndk-build
.
I created a method fixUntrustCertificate(), so when I am dealing with a domain that is not in trusted CAs you can invoke the method before the request. This code will gonna work after java1.4. This method applies for all hosts:
public void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// set the allTrusting verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
Try
return value.replaceAll("[^A-Za-z0-9]", "");
or
return value.replaceAll("[\\W]|_", "");
I just used getLocaleString() function for my application. It should adapt the timeformat common to the locale, so no +0200 etc. Ofcourse, there will be less possibility for controlling the width of your string then.
var str = (new Date(1400167800)).toLocaleString();
another scheme showing __proto__, prototype and constructor relations:
I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;
.
$(window).on("load",function() {
function fade() {
var animation_height = $(window).innerHeight() * 0.25;
var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;
$('.fade').each(function() {
var objectTop = $(this).offset().top;
var windowBottom = $(window).scrollTop() + $(window).innerHeight();
if ( objectTop < windowBottom ) {
if ( objectTop < windowBottom - animation_height ) {
$(this).html( 'fully visible' );
$(this).css( {
transition: 'opacity 0.1s linear',
opacity: 1
} );
} else {
$(this).html( 'fading in/out' );
$(this).css( {
transition: 'opacity 0.25s linear',
opacity: (windowBottom - objectTop) * ratio
} );
}
} else {
$(this).html( 'not visible' );
$(this).css( 'opacity', 0 );
}
});
}
$('.fade').css( 'opacity', 0 );
fade();
$(window).scroll(function() {fade();});
});
See it here: http://jsfiddle.net/78xjLnu1/16/
Cheers, Martin
While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan
is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt"
.
CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:
form div
{
font-size: 12px;
font-weight: bold;
}
div.content
{
// any rule you want here, followed by !important
}
Use JavaScript setInterval()
method to redirect page after some specified time. The following script will redirect page after 5 seconds.
var count = 5;
setInterval(function(){
count--;
document.getElementById('countDown').innerHTML = count;
if (count == 0) {
window.location = 'https://www.google.com';
}
},1000);
Example script and live demo can be found from here - Redirect page after delay using JavaScript
From a background script you can listen to the chrome.tabs.onUpdated
event and check the property changeInfo.status
on the callback. It can be loading or complete. If it is complete, do the action.
Example:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// do your things
}
})
Because this will probably trigger on every tab completion, you can also check if the tab is active
on its homonymous attribute, like this:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
// do your things
}
})
If you use Windows, there some shortcuts, while devtools are opened:
Pressing Ctrl+Shift+D will dock all devtools to left, right, bottom in turn.
Press Ctrl+Shift+F if your JS console disappeared, and you want it docked back to bottom within dev tools.
I just ran into this.
If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.
TCP :
Transmission Control Protocol is a connection-oriented protocol, which means that it requires handshaking to set up end-to-end communications. Once a connection is set up, user data may be sent bi-directionally over the connection.
Reliable – Strictly only at transport layer, TCP manages message acknowledgment, retransmission and timeout. Multiple attempts to deliver the message are made. If it gets lost along the way, the server will re-request the lost part. In TCP, there's either no missing data, or, in case of multiple timeouts, the connection is dropped. (This reliability however does not cover application layer, at which a separate acknowledgement flow control is still necessary)
Ordered – If two messages are sent over a connection in sequence, the first message will reach the receiving application first. When data segments arrive in the wrong order, TCP buffers delay the out-of-order data until all data can be properly re-ordered and delivered to the application.
Heavyweight – TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control. Streaming – Data is read as a byte stream, no distinguishing indications are transmitted to signal message (segment) boundaries.
Applications of TCP
World Wide Web, email, remote administration, and file transfer rely on TCP.
UDP :
User Datagram Protocol is a simpler message-based connectionless protocol. Connectionless protocols do not set up a dedicated end-to-end connection. Communication is achieved by transmitting information in one direction from source to destination without verifying the readiness or state of the receiver.
Unreliable – When a UDP message is sent, it cannot be known if it will reach its destination; it could get lost along the way. There is no concept of acknowledgment, retransmission, or timeout.
Not ordered – If two messages are sent to the same recipient, the order in which they arrive cannot be predicted.
Lightweight – There is no ordering of messages, no tracking connections, etc. It is a small transport layer designed on top of IP.
Datagrams – Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent. No congestion control – UDP itself does not avoid congestion. Congestion control measures must be implemented at the application level.
Broadcasts – being connectionless, UDP can broadcast - sent packets can be addressed to be receivable by all devices on the subnet.
Multicast – a multicast mode of operation is supported whereby a single datagram packet can be automatically routed without duplication to very large numbers of subscribers.
Applications of UDP
Numerous key Internet applications use UDP, including: the Domain Name System (DNS), where queries must be fast and only consist of a single request followed by a single reply packet, the Simple Network Management Protocol (SNMP), the Routing Information Protocol (RIP) and the Dynamic Host Configuration Protocol (DHCP).
Voice and video traffic is generally transmitted using UDP. Real-time video and audio streaming protocols are designed to handle occasional lost packets, so only slight degradation in quality occurs, rather than large delays if lost packets were retransmitted. Because both TCP and UDP run over the same network, many businesses are finding that a recent increase in UDP traffic from these real-time applications is hindering the performance of applications using TCP, such as point of sale, accounting, and database systems. When TCP detects packet loss, it will throttle back its data rate usage. Since both real-time and business applications are important to businesses, developing quality of service solutions is seen as crucial by some.
Some VPN systems such as OpenVPN may use UDP while implementing reliable connections and error checking at the application level.
If all you need to do is count how many values fall in each category, then this is a classic statistics question and can be very elegantly solved with a "histogram."
In Excel, you use the Data Analysis Add-In (if you don't have it already, refer to the link below). Once you understand histograms, you can segregate your data into buckets - called "bins" - very quickly, easily adjust your bins, and automatically chart the data.
It's three simple steps: 1) Put your data in one column 2) Create a column for your bins (10, 20, 30, etc.) 3) Select Data --> Data Analysis --> Histogram and follow the instructions for selecting the data range and bins (you can put the results into a new worksheet and Chart the results from this same menu)
http://office.microsoft.com/en-us/excel-help/create-a-histogram-HP001098364.aspx
In case you want to get the row count in the middle of a chained operation, you can use:
df.pipe(len)
Example:
row_count = (
pd.DataFrame(np.random.rand(3,4))
.reset_index()
.pipe(len)
)
This can be useful if you don't want to put a long statement inside a len()
function.
You could use __len__()
instead but __len__()
looks a bit weird.
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
Install autoenv either by
$ pip install autoenv
(or)
$ brew install autoenv
And then create .env
file in your virtualenv project folder
$ echo "source bin/activate" > .env
Now everything works fine.
Strong typing probably means that variables have a well-defined type and that there are strict rules about combining variables of different types in expressions. For example, if A is an integer and B is a float, then the strict rule about A+B might be that A is cast to a float and the result returned as a float. If A is an integer and B is a string, then the strict rule might be that A+B is not valid.
Static typing probably means that types are assigned at compile time (or its equivalent for non-compiled languages) and cannot change during program execution.
Note that these classifications are not mutually exclusive, indeed I would expect them to occur together frequently. Many strongly-typed languages are also statically-typed.
And note that when I use the word 'probably' it is because there are no universally accepted definitions of these terms. As you will already have seen from the answers so far.
Many excellent answers so far, and they do answer the question...But, if you don't want to have to deal with disabling graphics driver's settings, or creating new keyboard mappings, or are developing through a remote session (RDP) or within a VM that intercepts your keystrokes, good-old keyboard navigation still works. Just do Alt-N to bring up the Navigate
menu and then hit the B key.
Please note that you don't hit all keys at the same time. So:
Alt-N wait B
This is what I use all the time, for exactly the case that the OP asked about. Also, this will probably hold through any IntelliJ updates.
A complete unfailing solution to thread scheduling, which should yield exactly the same times per each test, is to compile your program to be OS independent and boot up your computer so as to run the program in an OS-free environment. Yet, this is largely impractical and would be difficult at best.
A good substitute to going OS-free is just to set the affinity of the current thread to 1 core and the priority to the highest. This alternative should provide consistent-enough results.
Also you should turn off optimizations which would interfere with debugging, which for g++ or gcc means adding -Og
to the command line, to prevent the code being tested from being optimized out. The -O0
flag should not be used because it introduces extra unneeded overhead which would be included in the timing results, thus skewing the timed speed of the code.
On the contrary, both assuming that you use -Ofast
(or, at the very least, -O3
) on the final production build and ignoring the issue of "dead" code elimination, -Og
performs very few optimizations compared to -Ofast
; thus -Og
can misrepresent the real speed of the code in the final product.
Further, all speed tests (to some extent) perjure: in the final production product compiled with -Ofast
, each snippet/section/function of code is not isolated; rather, each snippet of code continuously flows into the next, thus allowing the compiler to potential join, merge, and optimize together pieces of code from all over the place.
At the same time, if you are benchmarking a snippet of code which makes heavy use of realloc()
, then the snippet of code might run slower in a production product with high enough memory fragmentation. Hence, the expression "the whole is more than the sum of its parts" applies to this situation because code in the final production build might run noticeably faster or slower than the individual snippet which you are speed testing.
A partial solution that may lessen the incongruity is using -Ofast
for speed testing WITH the addition of asm volatile("" :: "r"(var))
to the variables involved in the test for preventing dead code/loop elimination.
Here is an example of how to benchmark square root functions on a Windows computer.
// set USE_ASM_TO_PREVENT_ELIMINATION to 0 to prevent `asm volatile("" :: "r"(var))`
// set USE_ASM_TO_PREVENT_ELIMINATION to 1 to enforce `asm volatile("" :: "r"(var))`
#define USE_ASM_TO_PREVENT_ELIMINATION 1
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <chrono>
#include <cmath>
#include <windows.h>
#include <intrin.h>
#pragma intrinsic(__rdtsc)
#include <cstdint>
class Timer {
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_>
(clock_::now() - beg_).count(); }
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
unsigned int guess_sqrt32(register unsigned int n) {
register unsigned int g = 0x8000;
if(g*g > n) {
g ^= 0x8000;
}
g |= 0x4000;
if(g*g > n) {
g ^= 0x4000;
}
g |= 0x2000;
if(g*g > n) {
g ^= 0x2000;
}
g |= 0x1000;
if(g*g > n) {
g ^= 0x1000;
}
g |= 0x0800;
if(g*g > n) {
g ^= 0x0800;
}
g |= 0x0400;
if(g*g > n) {
g ^= 0x0400;
}
g |= 0x0200;
if(g*g > n) {
g ^= 0x0200;
}
g |= 0x0100;
if(g*g > n) {
g ^= 0x0100;
}
g |= 0x0080;
if(g*g > n) {
g ^= 0x0080;
}
g |= 0x0040;
if(g*g > n) {
g ^= 0x0040;
}
g |= 0x0020;
if(g*g > n) {
g ^= 0x0020;
}
g |= 0x0010;
if(g*g > n) {
g ^= 0x0010;
}
g |= 0x0008;
if(g*g > n) {
g ^= 0x0008;
}
g |= 0x0004;
if(g*g > n) {
g ^= 0x0004;
}
g |= 0x0002;
if(g*g > n) {
g ^= 0x0002;
}
g |= 0x0001;
if(g*g > n) {
g ^= 0x0001;
}
return g;
}
unsigned int empty_function( unsigned int _input ) {
return _input;
}
unsigned long long empty_ticks=0;
double empty_seconds=0;
Timer my_time;
template<unsigned int benchmark_repetitions>
void benchmark( char* function_name, auto (*function_to_do)( auto ) ) {
register unsigned int i=benchmark_repetitions;
register unsigned long long start=0;
my_time.reset();
start=__rdtsc();
while ( i-- ) {
auto result = (*function_to_do)( i << 7 );
#if USE_ASM_TO_PREVENT_ELIMINATION == 1
asm volatile("" :: "r"(
// There is no data type in C++ that is smaller than a char, so it will
// not throw a segmentation fault error to reinterpret any arbitrary
// data type as a char. Although, the compiler might not like it.
result
));
#endif
}
if ( function_name == nullptr ) {
empty_ticks = (__rdtsc()-start);
empty_seconds = my_time.elapsed();
std::cout<< "Empty:\n" << empty_ticks
<< " ticks\n" << benchmark_repetitions << " repetitions\n"
<< std::setprecision(15) << empty_seconds
<< " seconds\n\n";
} else {
std::cout<< function_name<<":\n" << (__rdtsc()-start-empty_ticks)
<< " ticks\n" << benchmark_repetitions << " repetitions\n"
<< std::setprecision(15) << (my_time.elapsed()-empty_seconds)
<< " seconds\n\n";
}
}
int main( void ) {
void* Cur_Thread= GetCurrentThread();
void* Cur_Process= GetCurrentProcess();
unsigned long long Current_Affinity;
unsigned long long System_Affinity;
unsigned long long furthest_affinity;
unsigned long long nearest_affinity;
if( ! SetThreadPriority(Cur_Thread,THREAD_PRIORITY_TIME_CRITICAL) ) {
SetThreadPriority( Cur_Thread, THREAD_PRIORITY_HIGHEST );
}
if( ! SetPriorityClass(Cur_Process,REALTIME_PRIORITY_CLASS) ) {
SetPriorityClass( Cur_Process, HIGH_PRIORITY_CLASS );
}
GetProcessAffinityMask( Cur_Process, &Current_Affinity, &System_Affinity );
furthest_affinity = 0x8000000000000000ULL>>__builtin_clzll(Current_Affinity);
nearest_affinity = 0x0000000000000001ULL<<__builtin_ctzll(Current_Affinity);
SetProcessAffinityMask( Cur_Process, furthest_affinity );
SetThreadAffinityMask( Cur_Thread, furthest_affinity );
const int repetitions=524288;
benchmark<repetitions>( nullptr, empty_function );
benchmark<repetitions>( "Standard Square Root", standard_sqrt );
benchmark<repetitions>( "Original Guess Square Root", original_guess_sqrt32 );
benchmark<repetitions>( "New Guess Square Root", new_guess_sqrt32 );
SetThreadPriority( Cur_Thread, THREAD_PRIORITY_IDLE );
SetPriorityClass( Cur_Process, IDLE_PRIORITY_CLASS );
SetProcessAffinityMask( Cur_Process, nearest_affinity );
SetThreadAffinityMask( Cur_Thread, nearest_affinity );
for (;;) { getchar(); }
return 0;
}
Also, credit to Mike Jarvis for his Timer.
Please note (this is very important) that if you are going to be running bigger code snippets, then you really must turn down the number of iterations to prevent your computer from freezing up.
%d
is for integers use %f
instead, it works for both float
and double
types:
double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
This may be achieved by using AppCompatCheckBox
. You can use app:buttonCompat="@drawable/selector_drawable"
to change the selector.
It's working with PNGs, but I didn't find a way for it to work with Vector Drawables.
On a SLES12 machine you can use Ctrl+PageUp and Ctrl+PageDown to navigate between tabs by default. You can always change these keys from Preferences window by browsing through "keys" section under "General" category. This process is well explained by Victor and VonC above.
You can also use chr(176)
to print the degree sign.
Here is an example using python 3.6.5 interactive shell:
Please read the example in rfc6749 sec 7.1 first.
The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.
PoP means kind of multi-factor authentication to make access token more secure. ref
Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).
Maybe it's not the case, but I would say,
BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.
NOTE: The make tool reads the makefile and checks the modification time-stamps of the files at both the side of ':' symbol in a rule.
In a directory 'test' following files are present:
prerit@vvdn105:~/test$ ls
hello hello.c makefile
In makefile a rule is defined as follows:
hello:hello.c
cc hello.c -o hello
Now assume that file 'hello' is a text file containing some data, which was created after 'hello.c' file. So the modification (or creation) time-stamp of 'hello' will be newer than that of the 'hello.c'. So when we will invoke 'make hello' from command line, it will print as:
make: `hello' is up to date.
Now access the 'hello.c' file and put some white spaces in it, which doesn't affect the code syntax or logic then save and quit. Now the modification time-stamp of hello.c is newer than that of the 'hello'. Now if you invoke 'make hello', it will execute the commands as:
cc hello.c -o hello
And the file 'hello' (text file) will be overwritten with a new binary file 'hello' (result of above compilation command).
If we use .PHONY in makefile as follow:
.PHONY:hello
hello:hello.c
cc hello.c -o hello
and then invoke 'make hello', it will ignore any file present in the pwd 'test' and execute the command every time.
Now suppose, that 'hello' target has no dependencies declared:
hello:
cc hello.c -o hello
and 'hello' file is already present in the pwd 'test', then 'make hello' will always show as:
make: `hello' is up to date.
The problem is GROUP BY
- if you group results by Locus, you only get one result per locus.
Try:
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10';
If you prefer using HAVING
syntax, then GROUP BY id
or something that is not repeating in the result set.
I had the same problem and solved it by going to File -> Project Structure... -> Suggestions and then Apply all. Like suggested by @JeffinJ I think the problem was because of the Gradle plugin update.
Yes, there is std::byte
(defined in <cstddef>
).
C++ 17 introduced it.
Another alternative that uses an external library is _.has() from Lodash.
E.g.
_.has(a, 'b.c')
is equal to
(a && a.b && a.b.c)
EDIT: As noted in the comments, you lose out on Typescript's type inference when using this method. E.g. Assuming that one's objects are properly typed, one would get a compilation error with (a && a.b && a.b.z) if z is not defined as a field of object b. But using _.has(a, 'b.z'), one would not get that error.
You can use for it the is
operator. You can then check if object is specific type by writing:
if (myObject is string)
{
DoSomething()
}
I might be too late to join the game but what the heck huh? :)
Do you think this is a threading issue? How are you using the output of this method for example? OR
Can we change your code to do something as simple as:
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(<your earlier date>);
calendar2.set(<your current date>);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff
+ " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds
+ " seconds.");
System.out.println("Time in minutes: " + diffMinutes
+ " minutes.");
System.out.println("Time in hours: " + diffHours
+ " hours.");
System.out.println("Time in days: " + diffDays
+ " days.");
}
It is evident to me that GitLens is the most popular extension for Git history.
What I like the most it can provide you side annotations when some line has been changed the last time and by whom.
Because you need parentheses around the value your looking for.
So here : document.querySelector('a[data-a="1"]')
If you don't know in advance the value but is looking for it via variable you can use template literals :
Say we have divs with data-price
<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>
We want to find an element but with the number that someone chose (so we don't know it):
// User chose 99
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"`]
I've chmoded my keypair to 600 in order to get into my personal instance last night,
And this is the way it is supposed to be.
From the EC2 documentation we have "If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you." The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.
The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.
Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.
Any problems you are having are client side, so be sure to include local OS information with any follow up questions!
Sessions would be good choice for you. Take a look at these two examples from PHP Manual:
Code of page1.php
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';
// Or pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>
Code of page2.php
<?php
// page2.php
session_start();
echo 'Welcome to page #2<br />';
echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);
// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>
To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:
PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1
Steven is right, in theory:
the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:
table
{
margin-left: auto;
margin-right: auto;
}
But the article mentioned in the beginning of this answer gives you all the other way to center a table.
An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:
div.centered
{
text-align: center;
}
div.centered table
{
margin: 0 auto;
text-align: left;
}
<div class="centered">
<table>
…
</table>
</div>
Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.
Once I had this "simple" task and I used (new Date()).getTimezoneOffset()
- the approach that is widely suggested here. But it turned out that the solution wasn't quite right.
For some undocumented reasons in my case new Date()
was returning GMT+0200 when new Date(0)
was returning GMT+0300 which was right. Since then I always use
(new Date(0)).getTimezoneOffset()
to get a correct timeshift.
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.
string = [ char for char in reversed(string)]
to send over gmail, you need to use an encrypted connection. this is not possible with telnet alone, but you can use tools like openssl
either connect using the starttls option in openssl to convert the plain connection to encrypted...
openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf -ign_eof
or connect to a ssl sockect directly...
openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
EHLO localhost
after that, authenticate to the server using the base64 encoded username/password
AUTH PLAIN AG15ZW1haWxAZ21haWwuY29tAG15cGFzc3dvcmQ=
to get this from the commandline:
echo -ne '\[email protected]\00password' | base64
AHVzZXJAZ21haWwuY29tAHBhc3N3b3Jk
then continue with "mail from:" like in your example
example session:
openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
[... lots of openssl output ...]
220 mx.google.com ESMTP m46sm11546481eeh.9
EHLO localhost
250-mx.google.com at your service, [1.2.3.4]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
AUTH PLAIN AG5pY2UudHJ5QGdtYWlsLmNvbQBub2l0c25vdG15cGFzc3dvcmQ=
235 2.7.0 Accepted
MAIL FROM: <[email protected]>
250 2.1.0 OK m46sm11546481eeh.9
rcpt to: <[email protected]>
250 2.1.5 OK m46sm11546481eeh.9
DATA
354 Go ahead m46sm11546481eeh.9
Subject: it works
yay!
.
250 2.0.0 OK 1339757532 m46sm11546481eeh.9
quit
221 2.0.0 closing connection m46sm11546481eeh.9
read:errno=0
The visible width of an element is width + padding + border + outline
, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width
on the input, or making your div wider.
Boolean primitive type is atomic for write and read operations, volatile guarantees the happens-before principle. So if you need a simple get() and set() then you don't need the AtomicBoolean.
On the other hand if you need to implement some check before setting the value of a variable, e.g. "if true then set to false", then you need to do this operation atomically as well, in this case use compareAndSet and other methods provided by AtomicBoolean, since if you try to implement this logic with volatile boolean you'll need some synchronization to be sure that the value has not changed between get and set.
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
Your file should directly be under the project folder, and not inside any other sub-folder.
If the folder of your project is named for e.g. AProject
, it should be in the same place as your src
folder.
Aproject
src
word.txt
I use this website and this pattern do leap year validation as well.
<input type="text" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" required />
markers
is not a JSON object. It is a normal JavaScript object.data:
option:
Data to be sent to the server. It is converted to a query string, if not already a string.
If you want to send the data as JSON, you have to encode it first:
data: {markers: JSON.stringify(markers)}
jQuery does not convert objects or arrays to JSON automatically.
But I assume the error message comes from interpreting the response of the service. The text you send back is not JSON. JSON strings have to be enclosed in double quotes. So you'd have to do:
return "\"received markers\"";
I'm not sure if your actual problem is sending or receiving the data.
While it does look simple enough to implement on your own with a timeout and a couple of mouse event handlers, it gets a bit more complicated when you consider cases like click-drag-release, supporting both press and long-press on the same element, and working with touch devices like the iPad. I ended up using the longclick jQuery plugin (Github), which takes care of that stuff for me. If you only need to support touchscreen devices like mobile phones, you might also try the jQuery Mobile taphold event.
Got here through google because i was looking for a good way to do things on the ui thread after being inside a Task.Run call - Using the following code you can use await
to get back to the UI Thread again.
I hope this helps someone.
public static class UI
{
public static DispatcherAwaiter Thread => new DispatcherAwaiter();
}
public struct DispatcherAwaiter : INotifyCompletion
{
public bool IsCompleted => Application.Current.Dispatcher.CheckAccess();
public void OnCompleted(Action continuation) => Application.Current.Dispatcher.Invoke(continuation);
public void GetResult() { }
public DispatcherAwaiter GetAwaiter()
{
return this;
}
}
Usage:
... code which is executed on the background thread...
await UI.Thread;
... code which will be run in the application dispatcher (ui thread) ...
If the directory doesn't exist you need to create it. Java won't create it by itself since the File
class is just a link to an entity that can also not exist at all.
As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see
FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
You should try creating a path for the folder it contains before:
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
i it integer, int to Integer
Integer intObj = new Integer(i);
add to collection
list.add(String.valueOf(intObj));
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
/dt is the commad which lists you all the tables present in a database. using
/d command and /d+ we can get the details of a table. The sysntax will be like
* /d table_name (or) \d+ table_name
Simply casting to List<TestB>
almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning):
List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
You can do it like
<button v-on:click="Function1(); Function2();"></button>
OR
<button @click="Function1(); Function2();"></button>
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
mmap
has the advantage when you have random access on big files. Another advantage is that you access it with memory operations (memcpy, pointer arithmetic), without bothering with the buffering. Normal I/O can sometimes be quite difficult when using buffers when you have structures bigger than your buffer. The code to handle that is often difficult to get right, mmap is generally easier. This said, there are certain traps when working with mmap
.
As people have already mentioned, mmap
is quite costly to set up, so it is worth using only for a given size (varying from machine to machine).
For pure sequential accesses to the file, it is also not always the better solution, though an appropriate call to madvise
can mitigate the problem.
You have to be careful with alignment restrictions of your architecture(SPARC, itanium), with read/write IO the buffers are often properly aligned and do not trap when dereferencing a casted pointer.
You also have to be careful that you do not access outside of the map. It can easily happen if you use string functions on your map, and your file does not contain a \0 at the end. It will work most of the time when your file size is not a multiple of the page size as the last page is filled with 0 (the mapped area is always in the size of a multiple of your page size).
Had same issue this end of week, only Firefox will not accept certificate... The solution for me has been to add, in the apache configuration of the website, the intermediate certificate with the following line :
SSLCACertificateFile /your/path/to/ssl_ca_certs.pem
Find more infomration on https://httpd.apache.org/docs/2.4/fr/mod/mod_ssl.html
Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.
I very often use count(/html/body) = 0
, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.
<xsl:choose>
<xsl:when test="/html/body">
<!-- Found the node(s) -->
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
<!-- No node exists -->
</xsl:otherwise>
</xsl:choose>
I have a simpler idea. Use LINQ with a new selection.
public class Fruit
{
public string Name {get; set;}
public int SeedCount {get; set;}
}
void SomeMethod()
{
List<Fruit> originalFruits = new List<Fruit>();
originalFruits.Add(new Fruit {Name="Apple", SeedCount=10});
originalFruits.Add(new Fruit {Name="Banana", SeedCount=0});
//Deep Copy
List<Fruit> deepCopiedFruits = from f in originalFruits
select new Fruit {Name=f.Name, SeedCount=f.SeedCount};
}
SELECT ROUND((6 - 3 * RAND()), 0)
git show somebranch:path/to/your/file
you can also do multiple files and have them concatenated:
git show branchA~10:fileA branchB^^:fileB
You do not have to provide the full path to the file, relative paths are acceptable e.g.:
git show branchA~10:../src/hello.c
If you want to get the file in the local directory (revert just one file) you can checkout:
git checkout somebranch^^^ -- path/to/file
This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.
input_string = eval('b"' + sys.argv[1] + '"')
It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:
See it in action with jsfiddle here (except the php processor)
### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.type = 'text';
nextEmail.name = 'emails[]';
nextEmail.className = 'class_for_styling';
nextEmail.style.display = 'block';
nextEmail.placeholder = 'Enter E-mail Here';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
foreach ($_POST[emails] AS $postEmail){
if ($postEmail){$mailer->AddAddress($postEmail);}
}
}
?>
So what it does basically is to generate a new input text box on every click with the name "emails[]".
The [] added at the end makes it an array when posted.
Then we go through each element of the array with "foreach" on PHP side adding the:
$mailer->AddAddress($postEmail);
You could download it from a Android 4.0 phone and then mount the system image rw
and copy it over.
Didnt tried it before but it should work.
You can try this simple android dialog popup library. It is very simple to use on your activity.
When submit button is clicked try following code after including above lib in your code
Pop.on(this)
.with()
.title(R.string.title) //ignore if not needed
.icon(R.drawable.icon) //ignore if not needed
.cancelable(false) //ignore if not needed
.layout(R.layout.custom_pop)
.when(new Pop.Yah() {
@Override
public void clicked(DialogInterface dialog, View view) {
Toast.makeText(getBaseContext(), "Yah button clicked", Toast.LENGTH_LONG).show();
}
}).show();
Add one line in your gradle and you good to go
dependencies {
compile 'com.vistrav:pop:2.0'
}
Simply, @Id: This annotation specifies the primary key of the entity.
@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.
GenerationType enum defines four strategies:
1. Generation Type . TABLE,
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY
4. Generation Type. AUTO
GenerationType.SEQUENCE
With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.
GenerationType.TABLE
With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html
The Allow-Control-Allow-Origin plugin for Chrome does not work. This is for MacOS
I added alias chrome='open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir --disable-web-security'
to my .profile as an alias.
The other commands will disable my other extensions and this will boot your normal chrome with cors disabled
"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.
You can check that with:
$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )
"#if one" means that if "#define one" has been written "#if one" is executed otherwise "#ifndef one" is executed.
This is just the C Pre-Processor (CPP) Directive equivalent of the if, then, else branch statements in the C language.
i.e. if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); so if there was no #define one statement then the else branch of the statement would be executed.
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
Use
var isEmpty: Bool { get }
Example
let lang = "Swift 5"
if lang.isEmpty {
print("Empty string")
}
If you want to ignore white spaces
if lang.trimmingCharacters(in: .whitespaces).isEmpty {
print("Empty string")
}
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
Select your results by clicking in the top left corner, right click and select "Copy with Headers". Paste in excel. Done!
Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability
Your query execution will return list of Object[]
.
List result_source = LoadSource.list();
for(Object[] objA : result_source) {
// read it all
}
Use ls -s
to list file size, or if you prefer ls -sh
for human readable sizes.
For directories use du
, and again, du -h
for human readable sizes.
Step 1 : Check the proxy configured in eclipse is correct or not ? (Window->Preferences->General->Network Connections).
Step 2 : Right Click on Project-> Go to Maven -> Update the project
Step 3: Run as Maven Install.
==== By Following these steps, i am able to solve this error.
A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.
using System;
using System.Management;
namespace Utils
{
class NetworkManagement
{
/// <summary>
/// Returns a list of all the network interface class names that are currently enabled in the system
/// </summary>
/// <returns>list of nic names</returns>
public static string[] GetAllNicDescriptions()
{
List<string> nics = new List<string>();
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"])
.Select(x=> new NetworkAdapterConfiguration(x)))
{
nics.Add(config.Description);
}
}
}
return nics.ToArray();
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
{
using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
{
foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
// NAC class was generated by opening a developer console and entering:
// mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
// See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/
using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
{
if (config.SetDNSServerSearchOrder(dnsServers) == 0)
{
RestartNetworkAdapter(nicDescription);
}
}
}
}
}
return false;
}
/// <summary>
/// Restarts a given Network adapter
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
public static void RestartNetworkAdapter(string nicDescription)
{
using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
{
using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
{
foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
{
// NA class was generated by opening dev console and entering
// mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
{
adapter.Disable();
adapter.Enable();
Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
return;
}
}
}
}
}
/// <summary>
/// Get's the DNS Server of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
public static string[] GetNameservers(string nicDescription)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
.Select( x => new NetworkAdapterConfiguration(x)))
{
return config.DNSServerSearchOrder;
}
}
}
return null;
}
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
/// <param name="ipAddresses">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
.Select( x=> new NetworkAdapterConfiguration(x)))
{
// Set the new IP and subnet masks if needed
config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
config.SetGateways(new[] {gateway}, new ushort[] {1});
}
}
}
}
}
}
}
Full source: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs
def allTheSame(i):
j = itertools.groupby(i)
for k in j: break
for k in j: return False
return True
Works in Python 2.4, which doesn't have "all".
Sometimes you want to have your GridView as simple as:
<asp:GridView ID="grid" runat="server" />
You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.
protected void Page_Load(object sender, EventArgs e)
{
grid.RowDataBound += grid_RowDataBound;
// Your DB access code here...
// grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// grid.DataBind();
}
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}
The results shown here.
svn revert filename
this should revert a single file.
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.
Input
xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???") # Read Note about Python 2
NOTE: In Python 2, when calling the
toString(...)
code, assigningxml
withElementTree.Element("Person", Name="???")
will raise an error...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)
Output
ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="크리스" />'
# Python 3 (John): b'<Person Name="John" />'
# Python 2 (???): <Person Name="크리스" />
# Python 2 (John): <Person Name="John" />
ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" /> <-------- Python 3
# Python 3 (John): <Person Name="John" />
# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode
ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'
# Python 2 (???): <Person Name="???" /> <-------- Python 2
# Python 2 (John): <Person Name="John" />
ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="크리스" />
# Python 3 (John): <Person Name="John" />
# Python 2 (???): <Person Name="크리스" />
# Python 2 (John): <Person Name="John" />
Alright so for me, the error being fixed is when there are different versions of python installed and yum can't find a certain .so file and throws an exception.
yum wants 2.7.5 according to the error.
which python gives me /usr/bin/python
python --version gives me 2.7.5
The fix for me was append /lib64 to the LD_LIBRARY_PATH environment variable. The relevant content is /lib64/python2.7 and /lib64/python3.6.
export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH
Fixed the yum error for me with multiple python versions installed.
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] = []
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks: Same markup rules for 3 and N dimensional arrays.
The accepted answer:
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}
unfortunately is not correct.
initialState
is passed as a reference to this.state
, so whenever you change state
you also change initialState
(const doesn't really matter here). The result is that you can never go back to initialState
.
You have to deep copy initialState
to state
, then it will work. Either write a deep copy function yourself or use some existing module like this.
Option 1- From Studio
In Android Studio, go to File > Project Structure. Then select the "project" tab on the left.
Your Gradle version will be displayed here.
Option 2- gradle-wrapper.properties
If you are using the Gradle wrapper, then your project will have a gradle/wrapper/gradle-wrapper.properties
folder.
This file should contain a line like this:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
This determines which version of Gradle you are using. In this case, gradle-2.2.1-all.zip
means I am using Gradle 2.2.1.
Option 3- Local Gradle distribution
If you are using a version of Gradle installed on your system instead of the wrapper, you can run gradle --version
to check.
I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.
Continuing with what Dave Ward said:
Page/Control design
<asp:Label runat="server" ID="Label1" Style="display: none;" />
<asp:Button runat="server" ID="Button1" />
Code behind
Somewhere in the load section:
Label label1 = (Label)FindControl("Label1");
((Label)FindControl("Button1")).OnClientClick = "ToggleVisibility('" + label1.ClientID + "')";
Javascript file
function ToggleVisibility(elementID)
{
var element = document.getElementByID(elementID);
if (element.style.display = 'none')
{
element.style.display = 'inherit';
}
else
{
element.style.display = 'none';
}
}
Of course, if you don't want to toggle but just to show the button/label then adjust the javascript method accordingly.
The important point here is that you need to send the information about the ClientID
of the control that you want to manipulate on the client side to the javascript file either setting global variables or through a function parameter as in my example.
It will convert Enum Constant
into Camel Case. It would be helpful for anyone who is looking for such funtionality.
public enum TRANSLATE_LANGUAGES {
ARABIC("ar"), BULGARIAN("bg"), CATALAN("ca"), CHINESE_SIMPLIFIED("zh-CN"), CHINESE_TRADITIONAL("zh-TW"), CZECH("cs"), DANISH("da"), DUTCH("nl"), ENGLISH("en"), ESTONIAN("et"), FINNISH("fi"), FRENCH(
"fr"), GERMAN("de"), GREEK("el"), HAITIAN_CREOLE("ht"), HEBREW("he"), HINDI("hi"), HMONG_DAW("mww"), HUNGARIAN("hu"), INDONESIAN("id"), ITALIAN("it"), JAPANESE("ja"), KOREAN("ko"), LATVIAN(
"lv"), LITHUANIAN("lt"), MALAY("ms"), NORWEGIAN("no"), PERSIAN("fa"), POLISH("pl"), PORTUGUESE("pt"), ROMANIAN("ro"), RUSSIAN("ru"), SLOVAK("sk"), SLOVENIAN("sl"), SPANISH("es"), SWEDISH(
"sv"), THAI("th"), TURKISH("tr"), UKRAINIAN("uk"), URDU("ur"), VIETNAMESE("vi");
private String code;
TRANSLATE_LANGUAGES(String language) {
this.code = language;
}
public String langCode() {
return this.code;
}
public String toCamelCase(TRANSLATE_LANGUAGES lang) {
String toString = lang.toString();
if (toString.contains("_")) {
String st = toUpperLowerCase(toString.split("_"));
}
return "";
}
private String toUpperLowerCase(String[] tempString) {
StringBuilder builder = new StringBuilder();
for (String temp : tempString) {
String char1 = temp.substring(0, 1);
String restString = temp.substring(1, temp.length()).toLowerCase();
builder.append(char1).append(restString).append(" ");
}
return builder.toString();
}
}
Use this function for date conversion, its working fine when your device in 24/12 hr format
See https://developer.apple.com/library/archive/qa/qa1480/_index.html
func convertDateFormatter(fromFormat:String,toFormat:String,_ dateString: String) -> String{
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = fromFormat
let date = formatter.date(from: dateString)
formatter.dateFormat = toFormat
return date != nil ? formatter.string(from: date!) : ""
}
If you're using 64-bit but still having problem even after installing AccessDatabaseEngine, see this post, it solved the problem for me.
i.e. You need to install this AccessDatabaseEngine
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:
function showMe(e) {
// i am spammy!
alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
If you're using Ubuntu then use the following:
sudo chown -R ubuntu /var/www/html
sudo chmod -R 755 /var/www/html
While all of the other answers work, they all have one big problem: it is up to the browser to decide what to do if they encounter a Location header. Usually browser stop processing the request and redirect to the URI indicated with the Location header. But a malicious user could just ignore the Location header and continue its request. Furthermore there may be other things that cause the php interpreter to continue evaluating the script past the Location header, which is not what you intended.
Image this:
<?php
if (!logged_id()) {
header("Location:login.php");
}
delete_everything();
?>
What you want and expected is that not logged in users are redirected to the login page, so that only logged in users can delete_everything. But if the script gets executed past the Location header still everything gets deleted. Thus, it is import to ALWAYS put an exit after a Location header, like this:
<?php
if (!logged_id()) {
header("Location:login.php");
exit; // <- don't forget this!
}
delete_everything();
?>
So, to answer your question: to redirect from a php page to another page (not just php, you can redirect to any page this way), use this:
<?php
header("Location:http://www.example.com/some_page.php");
exit; // <- don't forget this!
?>
Small note: the HTTP standard says that you must provide absolute URLs in the Location header (http://... like in my example above) even if you just want to redirect to another file on the same domain. But in practice relative URLs (Location:some_page.php) work in all browsers, though not being standard compliant.
private void indBoxProject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int NewProjID = (e.AddedItems[0] as kProject).ProjectID;
this.MyProject = new kProject(NewProjID);
LoadWorkPhase();
}
The use of the e.AddedItems[0] as kProject
where kProject is a class that holds the data worked for me as it was defaulting to the RemovedItems[0] before I have made this explicit distinction. Thanks SwDevMan81 for the initial information that answered this question for me.
In some cases a one-way request without a response can be fired to a TCP server, without a SSL certificate. A TCP server, in contrast to a HTTP server, will catch you request. However there will be no access to any data sent from the browser, because the browser will not send any data without a positive certificate check. And in special cases even a bare TCP signal without any data is enough to execute some tasks. For example for an IoT device within a LAN to start a connection to an external service. Link
This is a kind of a "Wake Up" trigger, that works on a port without any security.
In case a response is needed, this can be implemented using a secured public https server, which can send the needed data back to the browser using e.g. Websockets.
With either string concatenation or string interpolation (via template literals).
Here with JavaScript template literal:
function geoPreview() {
var lat = document.getElementById("lat").value;
var long = document.getElementById("long").value;
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}
Both parameters are unused and can be removed.
Join strings with the +
operator:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";
For more concise code, use JavaScript template literals to replace expressions with their string representations.
Template literals are enclosed by ``
and placeholders surrounded with ${}
:
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;
Template literals are available since ECMAScript 2015 (ES6).
if you create a console application, console will stay opened until you close the application.
if you already creat an application and you dont know how to open a console, you can change the subsystem as Console(/Subsystem:Console) in project configurations -> linker -> system.
In my case I got this error when I had mistakenly named a class the same as the class it was inheriting from.