I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.
of course this won't remove the original files. It simply removes it from the list of suggested workspaces.
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
Install the readr
package, then use library(readr)
.
From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.
To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.
In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.
Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!
So you have two solutions:
Move the folder counter_src
somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src
.
Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\
as your root directory. If Eclipse sees a project, you will be able to import it.
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
I figured it out. In order to save your Jenkins data on other drive you'll need to do the following:
Workspace Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\workspace
Build Record Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\builds
Go to TaskManager(Right Click in the Task Bar) and select Processess menu bar and select eclipse.exe and Click EndProcess
Version: Ecliplse CIndigo Service Release 2
deleting below file helped me solve my eclipse start up issue. Perforce plugin has always troubled me especially when my machine reboots, next time eclipse tries to recover workspace and craps out.
workspace/.metadata/.plugins/org.eclipse.core.resources/.snap
For your reference, Error I was getting: org.eclipse.core.runtime.CoreException: Plug-in com.perforce.team.ui was unable to load class com.perforce.team.ui.UITeamProvider.
You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.
You can then import project to your workspace, copy paste project to your new workspace folder, then
File?Import?Existing project in to workspace?select project.
If you have used custom workspace in Jenkins then deleteDir() will not delete @tmp folder.
So to delete @tmp along with workspace use following
pipeline {
agent {
node {
customWorkspace "/home/jenkins/jenkins_workspace/${JOB_NAME}_${BUILD_NUMBER}"
}
}
post {
cleanup {
/* clean up our workspace */
deleteDir()
/* clean up tmp directory */
dir("${workspace}@tmp") {
deleteDir()
}
/* clean up script directory */
dir("${workspace}@script") {
deleteDir()
}
}
}
}
This snippet will work for default workspace also.
Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.
You can also disable it through the menu "Project / Build automatically
".
But I would recommend first to check:
Preferences / Validations
, or Preferences / XML / ...
if you have WTP installed)Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:
There is an important difference between build interrupt and cancel.
When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.
There's also:
getent $HOSTNAME
or possibly:
getent `uname -n`
On Solaris 11 the ifconfig command is considered legacy and is being replaced by ipadm
ipadm show-addr
will show the IP addresses on the system for Solaris 11 and later.
I wrote this utility, it automatically generates the DSL code from a postgres database which you can then paste into dbdiagram.io/d website to get ER diagrams
For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.
# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)
# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)
# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]
# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]
# or this
v1, v2 = my_tuple_fun()
Hope this clears things up further for those that need it.
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
If you have the column it's very easy.
Using the designer, you could set the column as an identity (1,1): right click on the table ? design ? in part left (right click) ? properties ? in identity columns, select #column.
Properties:
Identity column:
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
Looking at RFC3986 - Uniform Resource Identifier (URI): Generic Syntax, your question revolves around the path component of a URI.
foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment | _____________________|__ / \ / \ urn:example:animal:ferret:nose
Citing section 3.3, valid characters for a URI segment
are of type pchar
:
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
Which breaks down to:
ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded
"!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
":" / "@"
Or in other words: You may use any (non-control-) character from the ASCII table, except /
, ?
, #
, [
and ]
.
This understanding is backed by RFC1738 - Uniform Resource Locators (URL).
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
The main reason for using em or percentages is to allow the user to change the text size without breaking the design. If you design with fonts specified in px, they do not change size (in IE 6 and others) if the user chooses text size - larger. This is very bad for users with visual handicaps.
For several examples of and articles on designs like this (there are a myriad to choose from), see the latest issue of A List Apart: Fluid Grids, the older article How to Size Text in CSS or Dan Cederholm's Bulletproof Web Design.
Your images should still be displayed with px sizes, but, in general, it is not considered good form to size your text with px.
As much as I personally despise IE6, it is currently the only browser approved for the bulk of the users in our Fortune 200 company.
\t
is a tab character. Use a raw string instead:
test_file=open(r'c:\Python27\test.txt','r')
or double the slashes:
test_file=open('c:\\Python27\\test.txt','r')
or use forward slashes instead:
test_file=open('c:/Python27/test.txt','r')
Try this method then you can do every thing you want.
It is like a stack so be careful which item comes first or last.
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="50dp" android:start="10dp" android:left="10dp">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="#012d08"/>
</shape>
</item>
<item android:top="50dp">
<shape android:shape="rectangle">
<solid android:color="#7c4b4b" />
</shape>
</item>
<item android:top="90dp" android:end="60dp">
<shape android:shape="rectangle">
<solid android:color="#e2cc2626" />
</shape>
</item>
<item android:start="50dp" android:bottom="20dp" android:top="120dp">
<shape android:shape="rectangle">
<solid android:color="#360e0e" />
</shape>
</item>
Alternatively, if your objective is to output directly to a file or stdout, you can use cat
:
cat(s1, s2, sep=", ")
If you're using the MVVM pattern then it is inconvenient (and breaks the pattern) to use the event handler. Instead, you can bind each individual TabItem's Selector.IsSelected
property to a dependency property in your viewmodel and then handle the PropertyChanged
event handler. That way you know exactly which tab was selected/deselected based on the PropertyName
and you have a special handler for each tab.
Example: MainView.xaml
<TabControl>
<TabItem Header="My tab 1" Selector.IsSelected="{Binding IsMyTab1Selected}"> ... </TabItem>
<TabItem Header="My tab 2" Selector.IsSelected="{Binding IsMyTab2Selected}"> ... </TabItem>
</TabControl>
Example: MainViewModel.cs
public bool IsMyTab1Selected {
get { return (bool)GetValue(IsMyTab1SelectedProperty); }
set { SetValue(IsMyTab1SelectedProperty, value); }
}
public static readonly DependencyProperty IsMyTab1SelectedProperty =
DependencyProperty.Register("IsMyTab1Selected", typeof(bool), typeof(MainViewModel), new PropertyMetadata(true, new PropertyChangedCallback(MyPropertyChanged)));
public bool IsMyTab2Selected {
get { return (bool)GetValue(IsMyTab2SelectedProperty); }
set { SetValue(IsMyTab2SelectedProperty, value); }
}
public static readonly DependencyProperty IsMyTab2SelectedProperty =
DependencyProperty.Register("IsMyTab2Selected", typeof(bool), typeof(MainViewModel), new PropertyMetadata(false, new PropertyChangedCallback(MyPropertyChanged)));
private void MyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.Property.Name == "IsMyTab1Selected") {
// stuff to do
} else if (e.Property.Name == "IsMyTab2Selected") {
// stuff to do
}
}
If your MainViewModel
is INotifyPropertyChanged
rather than DependencyObject
, then use this instead:
Example: MainViewModel.cs
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public MainViewModel() {
PropertyChanged += handlePropertyChanged;
}
public bool IsMyTab1Selected {
get { return _IsMyTab1Selected ; }
set {
if (value != _IsMyTab1Selected ) {
_IsMyTab1Selected = value;
OnPropertyChanged("IsMyTab1Selected ");
}
}
}
private bool _IsMyTab1Selected = false;
public bool IsMyTab2Selected {
get { return _IsMyTab2Selected ; }
set {
if (value != _IsMyTab2Selected ) {
_IsMyTab2Selected = value;
OnPropertyChanged("IsMyTab2Selected ");
}
}
}
private bool _IsMyTab2Selected = false;
private void handlePropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == "IsMyTab1Selected") {
// stuff to do
} else if (e.PropertyName == "IsMyTab2Selected") {
// stuff to do
}
}
There is nothing wrong with count() here, "trends" is the only key that is being counted in this case, you can try doing:
count($obj->trends);
Or:
count($obj->trends['2009-08-21 11:05']);
Or maybe even doing:
count($obj, COUNT_RECURSIVE);
I don't see php file, but that could be that -
replace in your php file:
$query_age = $_GET['query_age'];
with:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);
Most probably, at first time you running your script without ?query_age=[something]
and $_GET
has no key like query_age
.
Here the way the working of HTML file with Jquery.
_webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
[self.view addSubview:_webview];
NSString *filePath=[[NSBundle mainBundle]pathForResource:@"jquery" ofType:@"html" inDirectory:nil];
NSLog(@"%@",filePath);
NSString *htmlstring=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
or
[_webview loadHTMLString:htmlstring baseURL:nil];
You can use either the requests to call the HTML file in your UIWebview
I create a common init for the designated and required. For convenience inits I delegate to init(frame:)
with frame of zero.
Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews()
or updateConstraints()
. These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints()
or layoutSubviews()
. updateContstraints()
is called first, then layoutSubviews()
. In updateConstraints()
make sure to call super last. In layoutSubviews()
, call super first.
Here's what I do:
@IBDesignable
class MyView: UIView {
convenience init(args: Whatever) {
self.init(frame: CGRect.zero)
//assign custom vars
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
commonInit()
}
private func commonInit() {
//custom initialization
}
override func updateConstraints() {
//set subview constraints here
super.updateConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
//manually set subview frames here
}
}
This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (HttpContext.Current == null)
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
I was not satisfied, so I finally used this:
>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)
I don't know if it's quicker, but it looks more effective ;)
if any problem for JAVA installation version
C:\Where JAVA
will give the location of java it picking up. If you have any path other than your installation, remove those files or rename it (may be as _backup). you will get proper version of java file.
It should be simpler!
Duration.between(startLocalDateTime, endLocalDateTime).toMillis();
You can convert millis to whatever unit you like:
String.format("%d minutes %d seconds",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
I ran into this also with a file directly in the models
directory, and it turns out that I wasn't properly loading up the code on startup. I was able to fix the issue by setting config.eager_load = true
in my development.rb file. This made the class available to me in the console
Docstring conventions are in PEP-257 with much more detail than PEP-8.
However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.
I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.
I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:
def sq(n):
"""
Return the square of n.
"""
return n * n
Over:
def sq(n):
"""Returns the square of n."""
return n * n
And tend to leave off commenting on the first line in longer docstrings:
def sq(n):
"""
Return the square of n, accepting all numeric types:
>>> sq(10)
100
>>> sq(10.434)
108.86835599999999
Raises a TypeError when input is invalid:
>>> sq(4*'435')
Traceback (most recent call last):
...
TypeError: can't multiply sequence by non-int of type 'str'
"""
return n*n
Meaning I find docstrings that start like this to be messy.
def sq(n):
"""Return the squared result.
...
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
One thing that happened for me is that the version of R provided by my linux distribution (R version 3.0.2 provided by Ubuntu 14.04) was too old for the latest version of the package available on CRAN (in my case, plyr
version 1.8.3 as of today). The solution was to use the packaging system of my distribution instead of trying to install from R (apt-get install r-cran-plyr
got me version 1.8.1 of plyr
). Maybe I could have tried to update R using updateR()
, but I'm afraid that doing so would interfere with my distribution's package manager.
Edit (04/08/2020): I recently had an issue with a package (XML) reportedly not available for my R version (3.6.3, latest supported on Debian stretch), after an update of the package in CRAN. It was very unexpected because I already had installed it with success before (on the same version of R and same OS).
For some reason, the package was still there, but install.packages
was only looking at the updated (and incompatible) version. The solution was to find the URL of the compatible version and force install.packages
to use it, as follows:
install.packages("https://cran.r-project.org/src/contrib/Archive/XML/XML_3.99-0.3.tar.gz", repos=NULL, type="source", ask=FALSE)
function resize() {
var map_obj = document.getElementById("map_canvas");
/* map_obj.style.width = "500px";
map_obj.style.height = "225px";*/
if (map) {
map.checkResize();
map.panTo(new GLatLng(lat,lon));
}
}
<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse... Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor
- We can add a page break tag with style "page-break-after: always" at the point where we want to introduce the pagebreak in the html page.
- "page-break-before" also works
Example:
HTML_BLOCK_1
<p style="page-break-after: always"></p>
HTML_BLOCK_2
<p style="page-break-after: always"></p>
HTML_BLOCK_3
While printing the html file with the above code, the print preview will show three pages (one for each html block "HTML_BLOCK_n" ) where as in the browser all the three blocks appear sequentially one after the other.
You can remove the orange or blue border (outline) around text/input boxes by using: outline:none
input {
background-color: transparent;
border: 0px solid;
height: 20px;
width: 160px;
color: #CCC;
outline:none !important;
}
I use IReport to install font:
tools -> options -> fonts -> click install font
Then select the font and click
-> export as extension and type name myfont.jar
add this jar and also spring.jar* to your build path.
*copy spring.jar from Jaspersoft\iReport-3.7.0\ireport\modules\ext
Example query:
SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;
You could use
<link rel="shortcut icon" href="http://localhost/" />
That way it won't actually be requested from the server.
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
I had the same problem but I was using a reverse proxy.
So I had to set
client_max_body_size 50m;
inside both configure files :
Make sure that the value of the column is really NULL and not an empty string or 0.
Simple way is to write a custom shell command see Django Documentation and execute it using a cronjob on linux. However i would highly recommend using a message broker like RabbitMQ coupled with celery. Maybe you can have a look at this Tutorial
For the case when the process tree of interest has more than 2 levels (e.g. Chromium spawns 4-level deep process tree), pgrep
isn't of much use. As others have mentioned above, procfs files contain all the information about processes and one just needs to read them. I built a CLI tool called Procpath which does exactly this. It reads all /proc/N/stat
files, represents the contents as a JSON tree and expose it to JSONPath queries.
To get all descendant process' comma-separated PIDs of a non-root process (for the root it's ..stat.pid
) it's:
$ procpath query -d, "..children[?(@.stat.pid == 24243)]..pid"
24243,24259,24284,24289,24260,24262,24333,24337,24439,24570,24592,24606,...
Your specific error is with line 11:
awk 'BEGIN{sum+=$2}'
This is a line where awk
is invoked, and its BEGIN
block is specified - but you are already within a awk script, so you do not need to specify awk
. Also you want to run sum+=$2
on each line of input, so you do not want it within a BEGIN
block. Hence the line should simply read:
sum+=$2
You also do not need the lines:
x=sum
read name
the first just creates a synonym to sum
named x
and I'm not sure what the second does, but neither are needed.
This would make your awk script:
#!/bin/awk
### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.
# This block of code is executed for each line in the file
{
sum+=$2
# The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
# NR is a variable equal to the number of rows in the file
print "Average: " sum/ NR
# Change this to print the Average instead of just the number of rows
}
Jonathan Leffler's answer gives the awk one liner which represents the same fixed code, with the addition of checking that there are at least 1 lines of input (this stops any divide by zero error). If
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.
like this:
Intent notificationIntent = new Intent(Main.this, Main.class);
notificationIntent.putExtra("sport_id", "sport"+id);
notificationIntent.putExtra("game_url", "gameURL"+id);
notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime())));
I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...
final Class B{
static $staticVar;
static function getA(){
self::$staticVar = New A;
}
}
the stucture of b is calld a singeton handler you can also do it in a
Class a{
static $instance;
static function getA(...){
if(!isset(self::$staticVar)){
self::$staticVar = New A(...);
}
return self::$staticVar;
}
}
this is the singleton use
$a = a::getA(...);
You can create a much cleaner implementation with Moment.js Durations. No manual parsing necessary.
var time = moment.duration("00:03:15");_x000D_
var date = moment("2014-06-07 09:22:06");_x000D_
date.subtract(time);_x000D_
$('#MomentRocks').text(date.format())
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>_x000D_
<span id="MomentRocks"></span>
_x000D_
from the command line type:
mvn eclipse:eclipse
this will add all the dependencies you have in your pom.xml into eclipse...
however, if you haven't done any of this before you may need to do one other, one time only step.
Close eclipse, then run the following command from the shell:
mvn -Declipse.workspace=<eclipse workspace> eclipse:add-maven-repo
sample:
mvn -Declipse.workspace=/home/ft/workspaces/wksp1/ eclipse:add-maven-repo
Handling bytes and unsigned integers with BigInteger:
byte[] b = ... // your integer in big-endian
BigInteger ui = new BigInteger(b) // let BigInteger do the work
int i = ui.intValue() // unsigned value assigned to i
I solved in another way. You can try this.
<input id="passfld" type="text" autocomplete="off" />
<script type="text/javascript">
// Using jQuery
$(function(){
setTimeout(function(){
$("input#passfld").attr("type","password");
},10);
});
// or in pure javascript
window.onload=function(){
setTimeout(function(){
document.getElementById('passfld').type = 'password';
},10);
}
</script>
#another way
<script type="text/javascript">
function setAutoCompleteOFF(tm){
if(typeof tm =="undefined"){tm=10;}
try{
var inputs=$(".auto-complete-off,input[autocomplete=off]");
setTimeout(function(){
inputs.each(function(){
var old_value=$(this).attr("value");
var thisobj=$(this);
setTimeout(function(){
thisobj.removeClass("auto-complete-off").addClass("auto-complete-off-processed");
thisobj.val(old_value);
},tm);
});
},tm);
}catch(e){}
}
$(function(){
setAutoCompleteOFF();
});
</script>
// you need to add attribute autocomplete="off" or you can add class .auto-complete-off into the input box and enjoy
Example:
<input id="passfld" type="password" autocomplete="off" />
OR
<input id="passfld" class="auto-complete-off" type="password" />
Being late to this, but after Java 8, I personally find this following approach with the Stream
API more concise and can be an alternative to the accepted answer.
For example,
Arrays.stream(new int[size]).boxed().collect(Collectors.toList())
where size
is the desired List
size and without the disadvantage mentioned here, all elements in the List
are initialized as 0
.
(I did a quick search and did not see stream
in any answers posted - feel free to let me know if this answer is redundant and I can remove it)
For future reference,Follow these steps to avoid similar errors:
1.Download MondoDB https://www.mongodb.com/
2.Open a terminal and cd into your downloads folder or whatever folder youve saved your mondodb download(Ensure you extract your mongodb folder before you cd into it)
cd Downloads
3.Move mongodb to your usr/local path
sudo mv mongodb-osx-... /usr/local/mongodb
4.cd into your local folder
cd /usr/local/mongodb
5.make a new directory
sudo mkdir -p /data/db
6.cd into the new directory just created above
cd /data/db
7.give mongo permisions
sudo chown YourMacUserName /data/db
8.Then go/open your .bash_profile
To do so,follow these steps:
In your a new terminal
1.cd
2.pwd
3.ls -l
Check if the .bash_profile appears on your list of files on your terminal
if not create the -bash_profile
Creating .bash_profile:
In your terminal
touch .bash_profile
//skip this step if you already have a .bash_profile
Step8:
Next in your terminal:
open .bash_profile
And in your bash file that pops open add the following:
MONGO_PATH=/usr/local/mongodb
export PATH=$PATH:$MONGO_PATH/bin
And then save.(File Save or command S/CMD+S)
Step9:back in your terminal:
source .bash_profile
Now open two terminals.One will for your mondo daemon the other for your mongo.
Terminal 1: in your terminal type:mongod
mongodb
Terminal 2:
mongo
Also make sure you dont make the following typo error when starting your mongod in your terminal: This is incorrect
mongo d
gives off the following error: Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
This is Correct:
mongod
(There should be no space between the words mongo and d..mondod
Finally always keep in mind that you have to run mondod before you run mongo on your terminals.
You may have milestones set up and your job won't run until the previous job is complete.
i don't know about converting into a byte array, but it's easy to convert it into a string:
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.
This is (rather ridiculously) a private API.
The following two methods are private and sent to the UITableView's delegate:
-(NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath;
-(void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath;
They are pretty self explanatory.
Thanks to the fantastic answer from Glenn, I used ImageMagik's "mogrify *.png" functionality. However, I had images buried in sub-folders, so I used this simple Python script to apply this to all images in all sub-folders and thought it might help others:
import os
import subprocess
def system_call(args, cwd="."):
print("Running '{}' in '{}'".format(str(args), cwd))
subprocess.call(args, cwd=cwd)
pass
def fix_image_files(root=os.curdir):
for path, dirs, files in os.walk(os.path.abspath(root)):
# sys.stdout.write('.')
for dir in dirs:
system_call("mogrify *.png", "{}".format(os.path.join(path, dir)))
fix_image_files(os.curdir)
Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();
I've never used the alaistToBean, but I just read about it. You could also just loop over the results..
List<Object> rows = criteria.list();
for(Object r: rows){
Object[] row = (Object[]) r;
Type t = ((<Type>) row[0]);
}
If you have to you can manually populate User yourself that way.
Its sort of hard to look into the issue without some more information to diagnose the issue.
Swift 2
let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0
Swift 3
let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
I have written the following Java program out of curiosity, simple and self-explanatory HTH. Thanks.
/**
*
* @author sanhn
*/
public class CheckPalindrome {
private static String max_string = "";
public static void checkSubString(String s){
System.out.println("Got string is "+s);
for(int i=1;i<=s.length();i++){
StringBuilder s1 = new StringBuilder(s.substring(0,i));
StringBuilder s2 = new StringBuilder(s.substring(0,i));
s2.reverse();
if(s1.toString().equals(s2.toString())){
if(max_string.length()<=s1.length()){
max_string = s1.toString();
System.out.println("tmp max is "+max_string);
}
}
}
}
public static void main(String[] args){
String s="HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE";
for(int i=0; i<s.length(); i++)
checkSubString(s.substring(i, s.length()));
System.out.println("Max string is "+max_string);
}
}
DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
<table border="1" width="183" style='table-layout:fixed'>
<col width="67">
<col width="75">
<col width="41">
<tr>
<td>First Column</td>
<td>Second Column</td>
<td>Third Column</td>
</tr>
<tr>
<td>Row 1</td>
<td>Text</td>
<td align="right">1</td>
</tr>
<tr>
<td>Row 2</td>
<td>Abcdefg</td>
<td align="right">123</td>
</tr>
<tr>
<td>Row 3</td>
<td>Abcdefghijklmnop</td>
<td align="right">123456</td>
</tr>
</table>
I know it's old school, but give that a try, it works.
may also want to add this:
<style>
td {overflow:hidden;}
</style>
Of course, you'd put this in a separate linked stylesheet, and not inline... wouldn't you ;)
function correctedText($txt=''){
$ss = str_split($txt);
for($i=0; $i<count($ss); $i++){
$asciiNumber = ord($ss[$i]);// get the ascii dec of a single character
// asciiNumber will be from the DEC column showing at https://www.ascii-code.com
// capital letters only checked
if($asciiNumber >= 192 && $asciiNumber <= 197)$ss[$i] = 'A';
elseif($asciiNumber == 198)$ss[$i] = 'AE';
elseif($asciiNumber == 199)$ss[$i] = 'C';
elseif($asciiNumber >= 200 && $asciiNumber <= 203)$ss[$i] = 'E';
elseif($asciiNumber >= 204 && $asciiNumber <= 207)$ss[$i] = 'I';
elseif($asciiNumber == 209)$ss[$i] = 'N';
elseif($asciiNumber >= 210 && $asciiNumber <= 214)$ss[$i] = 'O';
elseif($asciiNumber == 216)$ss[$i] = 'O';
elseif($asciiNumber >= 217 && $asciiNumber <= 220)$ss[$i] = 'U';
elseif($asciiNumber == 221)$ss[$i] = 'Y';
}
$txt = implode('', $ss);
return $txt;
}
Yah I found
<base target="_parent" />
This useful for open all iframe links open in iframe.
And
$(window).load(function(){
$("a").click(function(){
top.window.location.href=$(this).attr("href");
return true;
})
})
This we can use for whole page or specific part of page.
Thanks all for your help.
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
You have at least these 3 issues:
display
yet in your javascript you attempt to get element myDiv
which is not even defined in your markup.You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.
Combining two previous answers, for Rails 4.0.4 (and up, presumably), this suffices at the end of config/boot.rb
:
require 'rails/commands/server'
module Rails
class Server
def default_options
super.merge({Port: 10524})
end
end
end
You are accesing localhost
, meaning you have a web server running on your machine. To access it from Internet, you need to assign a public IP address to your machine. Then you can access http://<public_ip>:<port>/
. Port number is normally 80.
Instant.now() // Capture the current moment in UTC.
Generate a String to represent that value:
Instant.now().toString()
2016-09-13T23:30:52.123Z
As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone†. But its toString
implementation applies the JVM’s default time zone when generating the String representation of that date-time value. Confusingly to the naïve programmer, a Date seems to have a time zone but does not.
The java.util.Date
, j.u.Calendar
, and java.text.SimpleDateFormat
classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:
Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.
Getting current time in UTC/GMT is a simple one-liner…
Instant instant = Instant.now();
That Instant
class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.
In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock
captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computer’s clock hardware.
It’s toString
method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.
If you want more flexible formatting, or other additional features, then apply an offset-from-UTC of zero, for UTC itself (ZoneOffset.UTC
constant) to get a OffsetDateTime
.
OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC );
Dump to console…
System.out.println( "now.toString(): " + now );
When run…
now.toString(): 2014-01-21T23:42:03.522Z
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.
Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.
System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );
More detailed example code (Joda-Time 2.3)…
org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );
Dump to console…
System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );
When run…
Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z
For more example code doing time zone work, see my answer to a similar question.
I recommend you always specify a time zone rather than relying implicitly on the JVM’s current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.
When calling now()
pass the desired/expected time zone to be assigned. Use the DateTimeZone
class.
DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontréal );
That class holds a constant for UTC time zone.
DateTime now = DateTime.now( DateTimeZone.UTC );
If you truly want to use the JVM’s current default time zone, make an explicit call so your code is self-documenting.
DateTimeZone zoneDefault = DateTimeZone.getDefault();
Read about ISO 8601 formats. Both java.time and Joda-Time use that standard’s sensible formats as their defaults for both parsing and generating strings.
† Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Date’s toString
method; that method uses the JVM’s current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.
Here is another simple solution using sed.
$ sed -i 's/all.*/& anotherthing/g' filename.txt
Explanation:
all.* means all lines started with 'all'.
& represent the match (ie the complete line that starts with 'all')
then sed replace the former with the later and appends the ' anotherthing' word
Answer https://stackoverflow.com/a/21369918/2526049 from dcodesmith has a side effect that turns all types of lists numeric.
<ol type="a">
will show 1. 2. 3. 4. rather than a. b. c. d.
ol {
margin: 0 0 1.5em;
padding: 0;
counter-reset: item;
}
ol > li {
margin: 0;
padding: 0 0 0 2em;
text-indent: -2em;
list-style-type: none;
counter-increment: item;
}
ol > li:before {
display: inline-block;
width: 1em;
padding-right: 0.5em;
font-weight: bold;
text-align: right;
content: counter(item) ".";
}
/* Add support for non-numeric lists */
ol[type="a"] > li:before {
content: counter(item, lower-alpha) ".";
}
ol[type="i"] > li:before {
content: counter(item, lower-roman) ".";
}
The above code adds support for lowercase letters, lowercase roman numerals. At the time of writing browsers do not differentiate between upper and lower case selectors for type so you can only pick uppercase or lowercase for your alternate ol types I guess.
This can also be done with a timeout:
# Ping until timeout or 1 successful packet
ping -w (timeout) -c 1
In mysqli_query(first parameter should be connection,your sql statement) so
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');
but best practice is
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);
There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:
std::string(5, '.')
This is a contrived example of how you might use an ostringstream to repeat a string n times:
#include <sstream>
std::string repeat(int n) {
std::ostringstream os;
for(int i = 0; i < n; i++)
os << "repeat";
return os.str();
}
Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.
Please do yourself a favor and just hit the easy button:
download Web Inspector (Open Source) from the Play store.
A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:
console.log('one', 'two', 'three');
you will only see
one
logged to the console. You'll need to manually wrap the params in an Array and join, like so:
console.log([ 'one', 'two', 'three' ].join(' '));
to see the expected output.
But the app is open source! A patch may be imminent! The patcher could even be you!
Why not have the original drop down on the page be a 2 digit value only? Credit cards only cover a small span when looking at the year especially if the CC vendor only takes in 2 digits already.
actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:
In case of an horizontal scroll view, your code will work.
Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:
@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })
That works for me. The '@' is used to escape keywords so they are treated as variables/properties.
First of all, in C++ linked-lists shouldn't be much more trouble to work with than an array. You can use the std::list or the boost pointer list for linked lists. The key issues with linked lists vs arrays are extra space required for pointers and terrible random access. You should use a linked list if you
The df.plot()
function returns a matplotlib.axes.AxesSubplot
object. You can set the labels on that object.
ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")
Or, more succinctly: ax.set(xlabel="x label", ylabel="y label")
.
Alternatively, the index x-axis label is automatically set to the Index name, if it has one. so df2.index.name = 'x label'
would work too.
I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.
position: fixed
to the CSS definition, but I see this won't work for youtop
.UPDATED:
CSS
#ActionBox {
position: relative;
float: right;
}
Script
var alert_top = 0;
var alert_margin_top = 0;
$(function() {
alert_top = $("#ActionBox").offset().top;
alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);
$(window).scroll(function () {
var scroll_top = $(window).scrollTop();
if (scroll_top > alert_top) {
$("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
} else {
$("#ActionBox").css("margin-top", alert_margin_top+"px");
};
});
});
Also it is important to add a base (10 in this case) to your parseInt()
, e.g.
parseInt($("#ActionBox").css("top"),10);
You need to override the following properties:
Broker Configs($KAFKA_HOME/config/server.properties)
Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine
Restart the server.
look at this documentation for more info: http://kafka.apache.org/08/configuration.html
I translated the code sample in this blog post into Python: How to detect when the client closes the connection?, and it works well for me:
from ctypes import (
CDLL, c_int, POINTER, Structure, c_void_p, c_size_t,
c_short, c_ssize_t, c_char, ARRAY
)
__all__ = 'is_remote_alive',
class pollfd(Structure):
_fields_ = (
('fd', c_int),
('events', c_short),
('revents', c_short),
)
MSG_DONTWAIT = 0x40
MSG_PEEK = 0x02
EPOLLIN = 0x001
EPOLLPRI = 0x002
EPOLLRDNORM = 0x040
libc = CDLL(None)
recv = libc.recv
recv.restype = c_ssize_t
recv.argtypes = c_int, c_void_p, c_size_t, c_int
poll = libc.poll
poll.restype = c_int
poll.argtypes = POINTER(pollfd), c_int, c_int
class IsRemoteAlive: # not needed, only for debugging
def __init__(self, alive, msg):
self.alive = alive
self.msg = msg
def __str__(self):
return self.msg
def __repr__(self):
return 'IsRemoteClosed(%r,%r)' % (self.alive, self.msg)
def __bool__(self):
return self.alive
def is_remote_alive(fd):
fileno = getattr(fd, 'fileno', None)
if fileno is not None:
if hasattr(fileno, '__call__'):
fd = fileno()
else:
fd = fileno
p = pollfd(fd=fd, events=EPOLLIN|EPOLLPRI|EPOLLRDNORM, revents=0)
result = poll(p, 1, 0)
if not result:
return IsRemoteAlive(True, 'empty')
buf = ARRAY(c_char, 1)()
result = recv(fd, buf, len(buf), MSG_DONTWAIT|MSG_PEEK)
if result > 0:
return IsRemoteAlive(True, 'readable')
elif result == 0:
return IsRemoteAlive(False, 'closed')
else:
return IsRemoteAlive(False, 'errored')
If you only want the time string you can use this expression (with a simple RegEx):
new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"
Looking at the source code I also think there must be some issue with the private key.
What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.
If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.
(see source code from class SecureChannnel, method EnsurePrivateKey)
So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.
You can activate Network Tracing to try to debug this. It will give you output like this:
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
Considering you have 3 nodes.
export ES_HOST=localhost:9200
# Disable shard allocation
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
"persistent": {
"cluster.routing.allocation.enable": "none"
}
}
'
# Stop non-essential indexing and perform a synced flush
curl -X POST "$ES_HOST/_flush/synced"
# check nodes
export ES_HOST=localhost:9200
curl -X GET "$ES_HOST/_cat/nodes"
# node 1
systemctl stop elasticsearch.service
# node 2
systemctl stop elasticsearch.service
# node 3
systemctl stop elasticsearch.service
# start
systemctl start elasticsearch.service
# Reenable shard allocation once the node has joined the cluster
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
"persistent": {
"cluster.routing.allocation.enable": null
}
}
'
Tested on Elasticseach 6.5
Source:
When I clicked "Open Module Settings", there was no "Source" tab, I think because that's been removed for newer versions of Android Studio (I'm on 0.8.14). So I had to do this instead:
Add these lines to the build.gradle
file inside the android { ... }
block:
android {
...
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
After editing the file, click Tools > Android > Sync Project with Gradle Files.
Credit to this answer and this comment.
Select the range of cells, type in the value and press Ctrl + Enter.
This, of course, is true if you want to do it manually.
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
DateTime is a value type, which means it always has some value.
It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".
If you want a DateTime that can take the value Nothing, use a Nullable DateTime.
You can retrieve them from memory.
So first you get the rows in a DataSet, and then get the last 5 out of the DataSet.
document.getElementById("fName").style.border="1px solid black";
It's Magic is it's ability to reduce having to write code for every Variable Type passed into specific functions. Consider a Python similar print() function in it's C base.
#include <iostream>
#include <string>
#include <array>
using namespace std;
void print(auto arg) {
cout<<arg<<" ";
}
int main()
{
string f = "String";//tok assigned
int x = 998;
double a = 4.785;
string b = "C++ Auto !";
//In an opt-code ASCII token stream would be iterated from tok's as:
print(a);
print(b);
print(x);
print(f);
}
One need to set NavigateItem
checked true whenever item in NavigateView
is clicked
//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(mNavItemId).setChecked(true);
Add NavigationItemSelectedListener
on NavigationView
@Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
// update highlighted item in the navigation menu
menuItem.setChecked(true);
mNavItemId = menuItem.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
mDrawerLayout.closeDrawer(GravityCompat.START);
mDrawerActionHandler.postDelayed(new Runnable() {
@Override
public void run() {
navigate(menuItem.getItemId());
}
}, DRAWER_CLOSE_DELAY_MS);
return true;
}
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
On some apps you need to remove the slashes to make it work.
/(.)\1{9,}/
or this:
(.)\1{9,}
Try using the property ForeColor. Like this :
TextBox1.ForeColor = Color.Red;
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
QString str;
str.sprintf("%s %d", "string", 213);
Another random reason for why your images might not show up is because of something called base href="http://..."
this can make it so that the images
file doesn't work the way it should. Delete that line and you should be good.
If you want client IP and your server is behind aws elb, then user the following code. Tested for laravel 5.3
$elbSubnet = '172.31.0.0/16';
Request::setTrustedProxies([$elbSubnet]);
$clientIp = $request->ip();
If you have a single-threaded application, you can use a simple try/catch in the Main function, however, this does not cover exceptions that may be thrown outside of the Main function, on other threads, for example (as noted in other comments). This code demonstrates how an exception can cause the application to terminate even though you tried to handle it in Main (notice how the program exits gracefully if you press enter and allow the application to exit gracefully before the exception occurs, but if you let it run, it terminates quite unhappily):
static bool exiting = false;
static void Main(string[] args)
{
try
{
System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
demo.Start();
Console.ReadLine();
exiting = true;
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception");
}
}
static void DemoThread()
{
for(int i = 5; i >= 0; i--)
{
Console.Write("24/{0} =", i);
Console.Out.Flush();
Console.WriteLine("{0}", 24 / i);
System.Threading.Thread.Sleep(1000);
if (exiting) return;
}
}
You can receive notification of when another thread throws an exception to perform some clean up before the application exits, but as far as I can tell, you cannot, from a console application, force the application to continue running if you do not handle the exception on the thread from which it is thrown without using some obscure compatibility options to make the application behave like it would have with .NET 1.x. This code demonstrates how the main thread can be notified of exceptions coming from other threads, but will still terminate unhappily:
static bool exiting = false;
static void Main(string[] args)
{
try
{
System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
demo.Start();
Console.ReadLine();
exiting = true;
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception");
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Notified of a thread exception... application is terminating.");
}
static void DemoThread()
{
for(int i = 5; i >= 0; i--)
{
Console.Write("24/{0} =", i);
Console.Out.Flush();
Console.WriteLine("{0}", 24 / i);
System.Threading.Thread.Sleep(1000);
if (exiting) return;
}
}
So in my opinion, the cleanest way to handle it in a console application is to ensure that every thread has an exception handler at the root level:
static bool exiting = false;
static void Main(string[] args)
{
try
{
System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
demo.Start();
Console.ReadLine();
exiting = true;
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception");
}
}
static void DemoThread()
{
try
{
for (int i = 5; i >= 0; i--)
{
Console.Write("24/{0} =", i);
Console.Out.Flush();
Console.WriteLine("{0}", 24 / i);
System.Threading.Thread.Sleep(1000);
if (exiting) return;
}
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception on the other thread");
}
}
Using mordernizr to detect browsers that are not supporting Placeholder, I created this short code to fix them.
//If placeholder is not supported
if (!Modernizr.input.placeholder){
//Loops on inputs and place the placeholder attribute
//in the textbox.
$("input[type=text]").each( function() {
$(this).val($(this).attr('placeholder'));
})
}
Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like
preg_replace('/[^a-zA-Z0-9]/', '', $str)
Here is how POST HTTP request works for iOS 8+ using NSURLSession:
- (void)call_PostNetworkingAPI:(NSURL *)url withCompletionBlock:(void(^)(id object,NSError *error,NSURLResponse *response))completion
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
config.timeoutIntervalForRequest = 5.0f;
config.timeoutIntervalForResource =10.0f;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
NSMutableURLRequest *Req=[NSMutableURLRequest requestWithURL:url];
[Req setHTTPMethod:@"POST"];
NSURLSessionDataTask *task = [session dataTaskWithRequest:Req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
completion(dict,error,response);
}
}else
{
completion(nil,error,response);
}
}];
[task resume];
}
Hope this will satisfy your following requirement.
Follow the steps:
npm install --save-dev nodemon
Add the following two lines to "script" section of package.json:
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
as shown below:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
}
npm run devstart
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website
With a bit of JavaScript:
<input
value="Enter username..."
onfocus="if (this.value === 'Enter username...') this.value=''" ... />
HTML5 has a nice attribute for this, called placeholder
:
<input placeholder="Enter username.." ... />
but this attribute is not supported in old browsers.
It should run properly at cron also. Please check below things.
1- You are editing proper file to set cron.
2- You have given proper permission(execute permission) to script mean your script is executable.
As a service
You can set this one by:
Going first to your installation directory (in my case it’s c:\xampplite
). It could be somewhere else depending on your installation. Have also my full version in c:\x2\xampp
.
Once your in the installation directory, find xampp-control.exe
and click/double-click to launch it.
You should first stop all running instances of your apache2
and mysqld
/mysql
processes to do this.
Click the checkmark next to Apache and MySQL with the header name service. It will warn you that it’s installing as a service which of course is what we like it to do. Click Yes.
Also do step 5 with MySQL. We’re almost done.
Click Start ? Run
Type services.msc (it can also be done in the control panel under administrative tools which is a way lot of click than this one). Find the Apache 2 and MySQL services.
Double click each one and set the startup type to Automatic (you will be presented with three options: Automatic, Manual, and Disabled):
net start apache2
Be warned though that any change in the services just like the registry can cause your system to stall.
Click the start button to manually start it (just for the session though). At the next restart it’ll be automated.
Do the same with MySQL.
As a startup program
Find xampp_start.exe from your installation directory.
Press Ctrl + C to copy it or right-click the file and hit copy.
Go to C:\Documents and Settings\Administrator\Start Menu\Programs\Startup and right click on it and hit Paste Shortcut.
When you restart it’ll be starting also and you’ll see something like this:
You can stop it by issuing the xampp_stop.exe
command in your installation directory.
Also worth mentioning is that if you right click again on the shortcut and hit properties, try to change the run option to minimized. This way the shortcut will be on your taskbar once started.
Your declaration is int ttTreeInsert(int value);
However, your definition/implementation is
ttTree::ttTreeInsert(int value)
{
}
Notice that the return type int
is missing in the implementation. Instead it should be
int ttTree::ttTreeInsert(int value)
{
return 1; // or some valid int
}
This is a maven specific problem I think. Maven does not copy the files form /src/main/resources
to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.
An easier way is to instead put a test specific context definition in the /src/test/resources
directory and load via:
@ContextConfiguration(locations = { "classpath:mycontext.xml" })
Html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />
vs Php:
<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />
You need to change your Ajax call to
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
contentType: "json",
processData: false,
success:function(data) {
$('#save_message').html(data.message);
}
});
change the dataType
to contentType
and add the processData
option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());
The point we are missing is that before you set the color on the button, it's important to work on the value you want for this color. So you can go to values > color. You will find the default ones, but you can also create colors by copping and pasting them, changing the colors and names. Then... when you go to change the color of the floating button (in activity_main), you can choose the one you have created
Exemple - code on values > colors with default colors + 3 more colors I've created:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="corBotaoFoto">#f52411</color>
<color name="corPar">#8e8f93</color>
<color name="corImpar">#494848</color>
</resources>
Now my Floating Action Button with the color I've created and named "corPar":
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_input_add"
android:tint="#ffffff"
app:backgroundTint="@color/corPar"/>
It worked for me. Good Luck!
What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.
public class BaseView {
protected UserLister userLister;
public BaseView() {
userLister = new UserListerDB(); // only line of code that needs changing
}
}
public class SomeView extends BaseView {
public SomeView() {
super();
}
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!
So what is Spring for? It's for:
Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter size of an array");
int n=s.nextInt();
double arr[] = new double[n];
System.out.println("Please enter elements of array:");
for (int i=0; i<n; i++)
{
arr[i] = s.nextDouble();
}
}
SQLite has a printf
function which does exactly that:
SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable
Try on this way
function timenow(){
var now= new Date(),
ampm= 'am',
h= now.getHours(),
m= now.getMinutes(),
s= now.getSeconds();
if(h>= 12){
if(h>12) h -= 12;
ampm= 'pm';
}
if(m<10) m= '0'+m;
if(s<10) s= '0'+s;
return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
toLocaleDateString()
is a function to change the date time format like toLocaleDateString("en-us")
In C, unlike say C++, you would need a format specifier that states the datatype of the variable you want to print-in this case %d as the data type is an integer . Try printf("%d",addNumbers(a,b));
If you would like to do this in Swift
with a delay try this:
delay(1.0) {
UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
self.yourLabel.text = "2"
}, completion: { finished in
self.delay(1.0) {
UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
self.yourLabel.text = "1"
}, completion: { finished in
})
}
})
}
using the following function created by @matt - https://stackoverflow.com/a/24318861/1982051:
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
which will become this in Swift 3
func delay(_ delay:Double, closure:()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.after(when: when, execute: closure)
}
You can use the function MROUND(<reference cell>, <round to multiple of digit needed>)
.
Example:
For a value A1 = 21
round to multiple of 10 it would be written as
=MROUND(A1,10)
for which Result = 20
For a value Z4 = 55.1
round to multiple of 10 it would be written as
=MROUND(Z4,10)
for which Result = 60
To make sure a click only actions once use this:
$(".bet").unbind().click(function() {
//Stuff
});
How about:
^([A-Za-z]|[0-9]|_)+$
...if you want to be explicit, or:
^\w+$
...if you prefer concise (Perl syntax).
You can just read from stdin unless the user supply a filename ?
If not, treat the special "filename" -
as meaning "read from stdin". The user would have to start the program like cat file | myprogram -
if he wants to pipe data to it, and myprogam file
if he wants it to read from a file.
int main(int argc,char *argv[] ) {
FILE *input;
if(argc != 2) {
usage();
return 1;
}
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"rb");
//check for errors
}
If you're on *nix, you can check whether stdin is a fifo:
struct stat st_info;
if(fstat(0,&st_info) != 0)
//error
}
if(S_ISFIFO(st_info.st_mode)) {
//stdin is a pipe
}
Though that won't handle the user doing myprogram <file
You can also check if stdin is a terminal/console
if(isatty(0)) {
//stdin is a terminal
}
This should work (from a few alterations to your code above).
function tableCreate() {_x000D_
var body = document.getElementsByTagName('body')[0];_x000D_
var tbl = document.createElement('table');_x000D_
tbl.style.width = '100%';_x000D_
tbl.setAttribute('border', '1');_x000D_
var tbdy = document.createElement('tbody');_x000D_
for (var i = 0; i < 3; i++) {_x000D_
var tr = document.createElement('tr');_x000D_
for (var j = 0; j < 2; j++) {_x000D_
if (i == 2 && j == 1) {_x000D_
break_x000D_
} else {_x000D_
var td = document.createElement('td');_x000D_
td.appendChild(document.createTextNode('\u0020'))_x000D_
i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null;_x000D_
tr.appendChild(td)_x000D_
}_x000D_
}_x000D_
tbdy.appendChild(tr);_x000D_
}_x000D_
tbl.appendChild(tbdy);_x000D_
body.appendChild(tbl)_x000D_
}_x000D_
tableCreate();
_x000D_
Use this PHP script:
$version = apache_get_version();
echo "$version\n";
That is not an nginx
configuration file. It is part of an nginx
configuration file.
The nginx
configuration file (usually called nginx.conf
) will look like:
events {
...
}
http {
...
server {
...
}
}
The server
block is enclosed within an http
block.
Often the configuration is distributed across multiple files, by using the include
directives to pull in additional fragments (for example from the sites-enabled
directory).
Use sudo nginx -t
to test the complete configuration file, which starts at nginx.conf
and pulls in additional fragments using the include
directive. See this document for more.
the split() method takes a regular expression as an argument
You are missing a parameter in the command. It should be in this order:
composer create-project [PACKAGE] [DESTINATION PATH] [--FLAGS]
You're mistakingly specifying your local path as the Composer/Packagist package you wish to create a project from. Hence the "Could not find package" message.
Simply make sure you're specifying the Laravel package and you should be good to go:
composer create-project laravel/laravel /Applications/MAMP/htdocs/test_laravel
The correct way to do this is:
typedef void (*callback_function)(void); // type for conciseness
callback_function disconnectFunc; // variable to store function pointer type
void D::setDisconnectFunc(callback_function pFunc)
{
disconnectFunc = pFunc; // store
}
void D::disconnected()
{
disconnectFunc(); // call
connected = false;
}
A different scenario but the same error: I got this error when I was trying to insert records into a temporary table using a stored procedure. It turned out there was a parameter mismatch. I was trying to insert a BIGINT into an INT.
Credit goes to Vicky Harp: http://vickyharp.com/2012/03/troubleshooting-a-severe-error-occurred-on-the-current-command/
To truly force maven to only use your local repo, you can run with mvn <goals> -o
. The -o
tells maven to let you work "offline", and it will stay off the network.
If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1
, column2
, column3
like in this code snippet
while IFS=$'\t' read -r column1 column2 column3 ; do
printf "%b\n" "column1<${column1}>"
printf "%b\n" "column2<${column2}>"
printf "%b\n" "column3<${column3}>"
done < "myfile"
to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN
is not a good idea to do so).
Generally speaking, in the presence of a garbage collector, it is never good practice to manually call the GC. A GC is organized around heuristic algorithms which work best when left to their own devices. Calling the GC manually often decreases performance.
Occasionally, in some relatively rare situations, one may find that a particular GC gets it wrong, and a manual call to the GC may then improves things, performance-wise. This is because it is not really possible to implement a "perfect" GC which will manage memory optimally in all cases. Such situations are hard to predict and depend on many subtle implementation details. The "good practice" is to let the GC run by itself; a manual call to the GC is the exception, which should be envisioned only after an actual performance issue has been duly witnessed.
If you just need to remove the last set color, the following might suit you.
In my situation, I needed to add a color class to the body tag on a click event and remove the last color that was set. In that case, you store the current color, and then look up the data tag to remove the last set color.
Code:
var colorID = 'Whatever your new color is';
var bodyTag = $('body');
var prevColor = bodyTag.data('currentColor'); // get current color
bodyTag.removeClass(prevColor);
bodyTag.addClass(colorID);
bodyTag.data('currentColor',colorID); // set the new color as current
Might not be exactly what you need, but for me it was and this was the first SO question I looked at, so thought I would share my solution in case it helps anyone.
Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore
Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore
Try this:
public class ConnectionProvider
{
DbConnection conn;
string connectionString;
DbProviderFactory factory;
// Constructor that retrieves the connectionString from the config file
public ConnectionProvider()
{
this.connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString.ToString();
factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[0].ProviderName.ToString());
}
// Constructor that accepts the connectionString and Database ProviderName i.e SQL or Oracle
public ConnectionProvider(string connectionString, string connectionProviderName)
{
this.connectionString = connectionString;
factory = DbProviderFactories.GetFactory(connectionProviderName);
}
// Only inherited classes can call this.
public DbConnection GetOpenConnection()
{
conn = factory.CreateConnection();
conn.ConnectionString = this.connectionString;
conn.Open();
return conn;
}
}
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
The problem in the jsfiddle is that your dummy text is all one word. If you use your lorem ipsum given in the question, then the text wraps fine.
If you want large words to be broken mid-word and wrap around, add this to your .title css:
word-wrap: break-word;
If you look into the source of java.lang.Runtime, you'll see exec finally call protected method: execVM, which means it uses Virtual memory. So for Unix-like system, VM depends on amount of swap space + some ratio of physical memory.
Michael's answer did solve your problem but it might (or to say, would eventually) cause the O.S. deadlock in memory allocation issue since 1 tell O.S. less careful of memory allocation & 0 is just guessing & obviously that you are lucky that O.S. guess you can have memory THIS TIME. Next time? Hmm.....
Better approach is that you experiment your case & give a good swap space & give a better ratio of physical memory used & set value to 2 rather than 1 or 0.
I had a problem with changing the upload size on my phpmyadmin and OS X 10.9.4 Mavericks. At first I didn't know where the php.ini is so used locate
locate php.ini
which came back with
/private/etc/php.ini.default
/usr/local/etc/php/5.4/php.ini
I've tried editing /usr/local/etc/php/5.4/php.ini and then restart in the server put this didn't work.
I remembered that there is a better way to find out this file I'm looking for or and least where php is looking for php.ini.
<?php phpinfo() ?>
came back saying that it expects /etc/php.ini but I didn't have one there. The below is from the phpinfo():
Configuration File (php.ini) Path: /etc
It turns out that the first result in the locate command above is what I'm looking for.
At least in OS X 10.9.4 Mavericks (OS X is something new to me) /etc is actually a link, etc -> private/etc, and by the looks of it PHP assumes default values unless php.ini is actually present.
I copied /private/etc/php.ini.default
cp /private/etc/php.ini.default /private/etc/php.ini
Then checked the variables in the new /etc/php.ini as per Aditya Bhatt advice above and it worked. In my case the values were:
memory_limit =128M
post_max_size = 64M
upload_max_filesize = 64M
Obviously, the apache service has to be restarted to see the changes.
Set the columns Width
property to be a proportional width such as *
Just for completion, the best solution here is often to require a factory function argument:
T GetObject<T>(Func<T> factory)
{ return factory(); }
and call it something like this:
string s = GetObject(() => "result");
You can use that to require or make use of available parameters, if needed.
For environments such as Webstorm where the node
command cannot be changed to ts-node
or npx
:
npm install ts-node typescript
(Install dependencies)node --require ts-node/register src/foo.ts
(Add --require ts-node/register
to "Node parameters")Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider
In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.
Use the str
accessor with square brackets:
df['col'] = df['col'].str[:9]
Or str.slice:
df['col'] = df['col'].str.slice(0, 9)
If your project is imported as an existing maven project then --> Just right click on project and do maven update. It resolved my similar issue.
If your data resides on HDFS, perhaps the fastest approach is to use hadoop streaming. Apache Pig's COUNT UDF, operates on a bag, and therefore uses a single reducer to compute the number of rows. Instead you can manually set the number of reducers in a simple hadoop streaming script as follows:
$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar -Dmapred.reduce.tasks=100 -input <input_path> -output <output_path> -mapper /bin/cat -reducer "wc -l"
Note that I manually set the number of reducers to 100, but you can tune this parameter. Once the map-reduce job is done, the result from each reducer is stored in a separate file. The final count of rows is the sum of numbers returned by all reducers. you can get the final count of rows as follows:
$HADOOP_HOME/bin/hadoop fs -cat <output_path>/* | paste -sd+ | bc
select right('000' + convert(varchar(3),id),3) from table
example
declare @i int
select @i =1
select right('000' + convert(varchar(3),@i),3)
BTW if it is an int column then it will still not keep the zeros Just do it in the presentation layer or if you really need to in the SELECT
I made the mistake to install some packages using sudo and other without privileges , this fixed my problem.
sudo chown -R $(whoami) $HOME/.npm
hope it helps someone.
List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
if(s.equals(value)){
//do something
}
}
or
for (int i = 0; i < arrayList.size(); i++) {
if(arrayList.get(i).equals(value)){
//do something
}
}
But be carefull ArrayList can hold null values. So comparation should be
value.equals(arrayList.get(i))
when you are sure that value is not null or you should check if given element is null.
Expanding on Alex Martelli's performance tests with Adam Parkin's comments...
$ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' 'd.has_key(12)'
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 301, in main
x = t.timeit(number)
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 178, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
d.has_key(12)
AttributeError: 'dict' object has no attribute 'has_key'
$ python2.7 -mtimeit -s'd=dict.fromkeys(range( 99))' 'd.has_key(12)'
10000000 loops, best of 3: 0.0872 usec per loop
$ python2.7 -mtimeit -s'd=dict.fromkeys(range(1999))' 'd.has_key(12)'
10000000 loops, best of 3: 0.0858 usec per loop
$ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' '12 in d'
10000000 loops, best of 3: 0.031 usec per loop
$ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d'
10000000 loops, best of 3: 0.033 usec per loop
$ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' '12 in d.keys()'
10000000 loops, best of 3: 0.115 usec per loop
$ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d.keys()'
10000000 loops, best of 3: 0.117 usec per loop
In most answers it is recommended to fill
the array because otherwise "you can't iterate over it", but this is not true. You can iterate an empty array, just not with forEach
. While loops, for of loops and for i loops work fine.
const count = Array(5);
Does not work.
console.log('---for each loop:---');
count.forEach((empty, index) => {
console.log(`counting ${index}`);
});
These work:
console.log('---for of loop:---');
for (let [index, empty] of count.entries()) {
console.log(`counting for of loop ${index}`);
}
console.log('---for i loop:---');
for (let i = 0, il = count.length; i < il; ++i) {
console.log(`counting for i loop ${i}`);
}
console.log('---while loop:---');
let index = 0;
while (index < count.length) {
console.log(`counting while loop ${index}`);
index++;
}
Check this fiddle with the above examples.
Also angulars *ngFor
works fine with an empty array:
<li *ngFor="let empty of count; let i = index" [ngClass]="
<span>Counting with *ngFor {{i}}</span>
</li>
import matplotlib.pyplot as plt
def maximize():
plot_backend = plt.get_backend()
mng = plt.get_current_fig_manager()
if plot_backend == 'TkAgg':
mng.resize(*mng.window.maxsize())
elif plot_backend == 'wxAgg':
mng.frame.Maximize(True)
elif plot_backend == 'Qt4Agg':
mng.window.showMaximized()
Then call function maximize()
before plt.show()
You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser
(man runuser
). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.
I provide a detailed answer how to use cron in this stackoverflow post.
How to write a cron that will run a script every day at midnight?
You would want to use a set
instead of a list
.
Update April 2018: There's now a native way to do this:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
This is currently only supported in the most bleeding edge browsers.
For older browser support, you can use this jQuery technique:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
And here's the fiddle: http://jsfiddle.net/9SDLw/
If your target element does not have an ID, and you're linking to it by its name
, use this:
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
For increased performance, you should cache that $('html, body')
selector, so that it doesn't run every single time an anchor is clicked:
var $root = $('html, body');
$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
If you want the URL to be updated, do it within the animate
callback:
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
Well, this solution will help you select only current month, current week and only today
SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;
For Weekly added posts:
WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())
For Monthly added posts:
MONTH(addedon_gm) = MONTH(NOW())
For Yearly added posts:
YEAR(addedon_gm) = YEAR(NOW())
you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.
For local commits which are not being pushed, you can also use git rebase -i
to delete or squash a commit.
You can parse the pom file with JDOM (http://www.jdom.org/).
The best method would be to take the code the sqlite3 db dump would do, excluding schema parts.
Example pseudo code:
SELECT 'INSERT INTO ' || tableName || ' VALUES( ' ||
{for each value} ' quote(' || value || ')' (+ commas until final)
|| ')' FROM 'tableName' ORDER BY rowid DESC
See: src/shell.c:838
(for sqlite-3.5.9) for actual code
You might even just take that shell and comment out the schema parts and use that.
To get an actual working example going that returns what one would expect:
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)
Somewhat relevent.. I was getting
"[ERROR] Failed to execute goal on project testproject: Could not resolve dependencies for project myjarname:jar:1.0-0: Failure to find myjarname-core:bundle:1.0-0 in
http://repo1.maven.org/maven2
was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]"
This error was caused by accidentally using Maven 3
instead of Maven 2
. Just figured it might save someone some time, because my initial google search led me to this page.
The solution I came up with is basically the same solution used before the introduction of storyboards.
Create a new, empty interface class file. Drag a UIView on to the canvas, layout as desired.
Load the nib manually, assign to the appropriate header/footer section in viewForHeaderInSection or viewForFooterInSection delegate methods.
I had hope that Apple simplified this scenario with storyboards and kept looking for a better or simpler solution. For example custom table headers and footers are straight forward to add.
Another way of approaching circle (and other shapes) drawing is by using masks. You draw circles or other shapes by, first, making masks of the shapes you need, second, provide squares of your color and, third, apply masks to those squares of color. You can change either mask or color to get a new custom circle or other shape.
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *area1;
@property (weak, nonatomic) IBOutlet UIView *area2;
@property (weak, nonatomic) IBOutlet UIView *area3;
@property (weak, nonatomic) IBOutlet UIView *area4;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.area1.backgroundColor = [UIColor blueColor];
[self useMaskFor: self.area1];
self.area2.backgroundColor = [UIColor orangeColor];
[self useMaskFor: self.area2];
self.area3.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:1.0];
[self useMaskFor: self.area3];
self.area4.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:0.5];
[self useMaskFor: self.area4];
}
- (void)useMaskFor: (UIView *)colorArea {
CALayer *maskLayer = [CALayer layer];
maskLayer.frame = colorArea.bounds;
UIImage *maskImage = [UIImage imageNamed:@"cirMask.png"];
maskLayer.contents = (__bridge id)maskImage.CGImage;
colorArea.layer.mask = maskLayer;
}
@end
Here is the output of the code above:
As I know, there is no direct support, but you can use plain-ol' javascript for that:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
With text-wrap, browser support is relatively weak (as you might expect from from a draft spec).
You are better off taking steps to ensure the data doesn't have long strings of non-white-space.
Updated for Swift 3
This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:
Width and Height
Center in Container
override func viewDidLoad() {
super.viewDidLoad()
// set up the view
let myView = UIView()
myView.backgroundColor = UIColor.blue
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
// Add constraints code here (choose one of the methods below)
// ...
}
// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint
Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint
Style.You can obfuscate it, but there's no way of protecting it completely.
example obfuscator: https://obfuscator.io
Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.
Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.
import urllib
base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
return base_url + ticker_symbol
output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
return output_path + "/" + directory + "/" + ticker_symbol + ".csv"
def pull_historical_data(ticker_symbol, directory="S&P"):
try:
urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
except urllib.ContentTooShortError as e:
outfile = open(make_filename(ticker_symbol, directory), "w")
outfile.write(e.content)
outfile.close()
hg strip
will completely remove a revision (and any descendants) from the repository.
To use strip you'll need to install MqExtension by adding the following lines to your .hgrc (or mercurial.ini):
[extensions]
mq =
In TortoiseHg the strip command is available in the workbench. Right click on a revision and choose 'Modify history' -> 'Strip'.
Since strip
changes the the repository's history you should only use it on revisions which haven't been shared with anyone yet. If you are using mercurial 2.1+ you can uses phases to track this information. If a commit is still in the draft phase it hasn't been shared with other repositories so you can safely strip it. (Thanks to Zasurus for pointing this out).
You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
$files = [
'./first.jpg',
'./second.jpg',
'./third.jpg'
];
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
} else {
// File not found.
}
}
val saveButton:Button = findViewById(R.id.button_save)
saveButton.setOnClickListener{
// write code for click event
}
with view object
saveButton.setOnClickListener{
view -> // write code for click event
}
You can pass in wildcards in instead of specifying file names or using stdin.
grep hello *.h *.cc
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
Use your mydate object and call getMonth() and getFullYear()
See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp
Aight fam, after some research and experimenting, I think the best approach is to have the thing's height at 0px
, and let it transition to an exact height. You get the exact height with JavaScript. The JavaScript isn't doing the animating, it's just changing the height value. Check it:
function setInfoHeight() {
$(window).on('load resize', function() {
$('.info').each(function () {
var current = $(this);
var closed = $(this).height() == 0;
current.show().height('auto').attr('h', current.height() );
current.height(closed ? '0' : current.height());
});
});
Whenever the page loads or is resized, the element with class info
will get its h
attribute updated. Then you could have a button trigger the style="height: __"
to set it to that previously set h
value.
function moreInformation() {
$('.icon-container').click(function() {
var info = $(this).closest('.dish-header').next('.info'); // Just the one info
var icon = $(this).children('.info-btn'); // Select the logo
// Stop any ongoing animation loops. Without this, you could click button 10
// times real fast, and watch an animation of the info showing and closing
// for a few seconds after
icon.stop();
info.stop();
// Flip icon and hide/show info
icon.toggleClass('flip');
// Metnod 1, animation handled by JS
// info.slideToggle('slow');
// Method 2, animation handled by CSS, use with setInfoheight function
info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');
});
};
Here's the styling for the info
class.
.info {
display: inline-block;
height: 0px;
line-height: 1.5em;
overflow: hidden;
padding: 0 1em;
transition: height 0.6s, padding 0.6s;
&.active {
border-bottom: $thin-line;
padding: 1em;
}
}
I used this on one of my projects so class names are specific. You can change them up however you like.
The styling might not be supported cross-browser. Works fine in chrome.
Below is the live example for this code. Just click on the ?
icon to start the animation
Have you tried to increase output_buffering in your php.ini?
In my case, it's related to the Toggle Vrapper Icon in the Eclipse.
If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity.
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Toast;
import com.example.fyp.R;
import java.util.Locale;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class textTospeech_class extends AppCompatActivity {
TextToSpeech textToSpeech;
String text;
int result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_tospeech);
textToSpeech = new TextToSpeech(textTospeech_class.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
}
}
});
}
public void tts(View view)
{
switch (view.getId()) {
case R.id.speechid:
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak("a for apple", TextToSpeech.QUEUE_FLUSH, null);
}
break;
case R.id.bid:
{
if(result==TextToSpeech.LANG_MISSING_DATA || result== TextToSpeech.LANG_NOT_SUPPORTED)
{
Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
}
else
{
textToSpeech.speak("b for ball",TextToSpeech.QUEUE_FLUSH,null);
}
break;
}
}
There's a fmod function too, that can be used : fmod($my_var, 1) will return the same result, but sometime with a small round error.
You'll have to set the enctype
attribute of the form
to multipart/form-data
;
then you can access the uploaded file using the HttpRequest.Files
collection.
My understanding is that HEAD points the current branch, while ORIG_HEAD is used to store the previous HEAD before doing "dangerous" operations.
For example git-rebase and git-am record the original tip of branch before they apply any changes.
I think the best answer that I've seen has been @MD_Sayem_Ahmed.
Your question is "How can I parse Json with C#", but it seems like you are wanting to decode Json. If you are wanting to decode it, Ahmed's answer is good.
If you are trying to accomplish this in ASP.NET Web Api, the easiest way is to create a data transfer object that holds the data you want to assign:
public class MyDto{
public string Name{get; set;}
public string Value{get; set;}
}
You have simply add the application/json header to your request (if you are using Fiddler, for example). You would then use this in ASP.NET Web API as follows:
//controller method -- assuming you want to post and return data
public MyDto Post([FromBody] MyDto myDto){
MyDto someDto = myDto;
/*ASP.NET automatically converts the data for you into this object
if you post a json object as follows:
{
"Name": "SomeName",
"Value": "SomeValue"
}
*/
//do some stuff
}
This helped me a lot when I was working in my Web Api and made my life super easy.
Thanks to Sam Stokes. According to his answer you can solve the problem with different way (I used this way). After updating your develop directory you should reinitialize it
git init
Then you can commit and push updates to master
What you really want to do is to remove any string that starts with either http://
or https://
plus any combination of non white space characters. Here is how I would solve it. My solution is very similar to that of @tolgayilmaz
#Define the text from which you want to replace the url with "".
text ='''The link to this post is https://stackoverflow.com/questions/11331982/how-to-remove-any-url-within-a-string-in-python'''
import re
#Either use:
re.sub('http://\S+|https://\S+', '', text)
#OR
re.sub('http[s]?://\S+', '', text)
And the result of running either code above is
>>> 'The link to this post is '
I prefer the second one because it is more readable.
SELinux prevents Apache (and therefore all Apache modules) from making remote connections by default.
# setsebool -P httpd_can_network_connect=1
Use this instead
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
<a href="javascript:timedRefresh(2000)">image</a>
Given you use JQuery, you can do something like below :
<form id="myform">
syn<input type="checkbox" name="checkfield" id="g01-01" onclick="doalert()"/>
</form>
function doalert() {
if ($("#g01-01").is(":checked")) {
alert ("hi");
} else {
alert ("bye");
}
}
You could use org.apache.commons.lang.ArrayUtils :
ArrayUtils.reverse(array)
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine
. They offer pip
out of the box (and have a smaller footprint which leads to faster builds etc).
Something like this should remove it
document.getElementById('x').style.visibility='hidden';
If you are going to do alot of this dom manipulation might be worth looking at jquery
Turning off HyperV on windows 8.1 did the trick for me
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true
void Main(){
Console.WriteLine(BitConverter.IsLittleEndian);
byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
//Console.WriteLine(bytes);
string hexStr = ByteArrayToHex(bytes);
Console.WriteLine(hexStr);
}
public static string ByteArrayToHex(byte[] data)
{
char[] c = new char[data.Length * 2];
byte b;
if(BitConverter.IsLittleEndian)
{
//read the byte array in reverse
for (int y = data.Length -1, x = 0; y >= 0; --y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
else
{
for (int y = 0, x = 0; y < data.Length; ++y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
return String.Concat("0x",new string(c));
}
It returns this:
True
0xDCBAABCDFFFE1608
which is the exact hex that went into the byte array.
Although @ruakh gave a good answer, I will add some alternatives for completeness:
You could in fact use even var Omega = 'Ω'
in JavaScript, but only if your JavaScript code is:
onclick="var Omega = 'Ω';
alert(Omega)"
or script
element inside an XHTML (or XHTML + XML) document
served with an XML content type.In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like Ω
are recognized. The restrictions make this an impractical approach in most cases.
You can also enter the O character as such, as in var Omega = 'O'
, but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.
Using the \u
notation, as in var Omega = '\u03A9'
, works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff
, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)
You can also construct a character using the String.fromCharCode()
method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937)
or in hexadecimal as in var Omega = String.fromCharCode(0x3A9)
. This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.