I've just had this same issue with Ionic.
It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.
After going back into the app, my states worked fine.
I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
I believe the command line switch you are looking for to pass to curl is -I
.
Example usage:
$ curl -I http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:05 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1
Additionally, if you encounter a response HTTP status code of 301, you might like to also pass a -L
argument switch to tell curl
to follow URL redirects, and, in this case, print the headers of all pages (including the URL redirects), illustrated below:
$ curl -I -L http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1
HTTP/1.1 302 Found
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Set-Cookie: UID=b8c37e33defde51cf91e1e03e51657da
Location: noaccess.php
Content-Type: text/html
HTTP/1.1 200 OK
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Content-Type: text/html
Package Level Annotations
I know this question has already been answered a long time ago but another solution to this problem is to use Package Level Annotations.
While its pretty hard to go find all the classes in the JVM its actually pretty easy to browse the package hierarchy.
Package[] ps = Package.getPackages();
for (Package p : ps) {
MyAno a = p.getAnnotation(MyAno.class)
// Recursively descend
}
Then just make your annotation have an argument of an array of Class. Then in your package-info.java for a particular package put the MyAno.
I'll add more details (code) if people are interested but most probably get the idea.
MetaInf Service Loader
To add to @erickson answer you can also use the service loader approach. Kohsuke has an awesome way of generating the the required META-INF stuff you need for the service loader approach:
http://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html
My idea of that program is that:
package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoutingWords {
public static void main(String[] args) throws IOException {
String str;
int cWords = 1;
char ch;
BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text: ");
str = buffor.readLine();
for(int i =0; i<str.length(); i++){
ch = str.charAt(i);
if(Character.isWhitespace(ch)){ cWords++; }
}
System.out.println("There are " + (int)cWords +" words.");
}
}
Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.
Paul Jakubik, Callback Implementations in C++.
The simplest choice I found to solve this problem was using the python lib called networkx
.
It implements the Johnson's algorithm mentioned in the best answer of this question but it makes quite simple to execute.
In short you need the following:
import networkx as nx
import matplotlib.pyplot as plt
# Create Directed Graph
G=nx.DiGraph()
# Add a list of nodes:
G.add_nodes_from(["a","b","c","d","e"])
# Add a list of edges:
G.add_edges_from([("a","b"),("b","c"), ("c","a"), ("b","d"), ("d","e"), ("e","a")])
#Return a list of cycles described as a list o nodes
list(nx.simple_cycles(G))
Answer: [['a', 'b', 'd', 'e'], ['a', 'b', 'c']]
The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.
If the URL of your website is: http://www.example.com/mywebsite/
then starting at the root level starts above the "mywebsite" folder path.
pandas.Series.astype
You can do something like this :
weather["Temp"] = weather.Temp.astype(float)
You can also use pd.to_numeric
that will convert the column from object to float
Example :
s = pd.Series(['apple', '1.0', '2', -3])
print(pd.to_numeric(s, errors='ignore'))
print("=========================")
print(pd.to_numeric(s, errors='coerce'))
Output:
0 apple
1 1.0
2 2
3 -3
=========================
dtype: object
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
In your case you can do something like this:
weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
convert_objects
Example is as follows
>> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can use this as follows:
weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
NaN
... so be careful while using it.On macOS Sierra (10.12) :
Run the following command to see if CLT is installed:
xcode-select -p
this will return the path to the tool if CLT is already installed. Something like this -
/Applications/Xcode.app/Contents/Developer
Run the following command to see the version of CLT:
pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
this will return version info, output will be something like this -
package-id: com.apple.pkg.CLTools_Executables
version: 8.2.0.0.1.1480973914
volume: /
location: /
install-time: 1486372375
Thanks, it worked!
Here's the final code:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
That is because the words are wrapping and are going on new lines hence stretching the TR. This should fix your problem:
overflow:hidden;
Put that in the TR styles Although it should work, why not just let it stretch o0
PS. i aint tested it so dont hate XD
with for-loop:
std::ifstream myFile;
std::string line;
int lines;
myFile.open(path);
for(lines = 0; std::getline(myFile,line); lines++);
std::cout << lines << std::endl;
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
Just for the documentation. You can try the Stack
library and its function Stack
in the following form:
Stack(df_1, df_2)
I have also the impression that it is faster than other methods for large data sets.
This could help, by the way:
The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.
http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
Download the mongodb
C:\data\db
cd
to C:\Program Files\MongoDB\Server\3.2\bin>
mongod
27017
localhost:27017
Your MongoDB is started and connected with RoboMongo (now Robo 3T) - a third party GUI tool
select @@version
Sample Output
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: )
If you just want to get the edition, you can use:
select serverproperty('Edition')
To use in an automated script, you can get the edition ID, which is an integer:
select serverproperty('EditionID')
You can pass via GET. So if you want to pass the value foobar
from PageA.php
to PageB.php
, call it as PageB.php?value=foobar
.
In PageB.php, you can access it this way:
$value = $_GET['value'];
InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);
code,
kbd,
pre,
.img-rounded,
.img-thumbnail,
.img-circle,
.form-control,
.btn,
.btn-link,
.dropdown-menu,
.list-group-item,
.input-group-addon,
.input-group-btn,
.nav-tabs a,
.nav-pills a,
.navbar,
.navbar-toggle,
.icon-bar,
.breadcrumb,
.pagination,
.pager *,
.label,
.badge,
.jumbotron,
.thumbnail,
.alert,
.progress,
.panel,
.well,
.modal-content,
.tooltip-inner,
.popover,
.popover-title,
.carousel-indicators li {
border-radius:0 !important;
}
You are missing PIL (Python Image Library and Imaging package). To install PIL I used
pip install pillow
For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:
$ gunzip Imaging-1.1.6.tar.gz
$ tar xvf Imaging-1.1.6.tar
$ cd Imaging-1.1.6
$ python setup.py install
Or if you have PIP installed in your Mac
pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz
then you can use:
from PIL import Image
in your python code.
You can set environmental variables in Pycharm's run configurations menu.
Open the Run Configuration selector in the top-right and cick Edit Configurations...
Find Environmental variables
and click ...
Add or change variables, then click OK
You can access your environmental variables with os.environ
import os
print(os.environ['SOME_VAR'])
Updated with the theme()
function, ggsave()
and the code for the legend background:
df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
stat_boxplot(aes(x = x, y = y, color = group),
fill = "transparent" # for the inside of the boxplot
)
Fastest way is using using rect
, as all the rectangle elements inherit from rect:
p <- p +
theme(
rect = element_rect(fill = "transparent") # all rectangles
)
p
More controlled way is to use options of theme
:
p <- p +
theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
)
p
To save (this last step is important):
ggsave(p, filename = "tr_tst2.png", bg = "transparent")
To solve this problem just call jQuery file before the bootstrap file
In my experience, it's not quite that simple. The built-in PHP SOAP client didn't work with the .NET-based SOAP server we had to use. It complained about an invalid schema definition. Even though .NET client worked with that server just fine. By the way, let me claim that SOAP interoperability is a myth.
The next step was NuSOAP. This worked for quite a while. By the way, for God's sake, don't forget to cache WSDL! But even with WSDL cached users complained the damn thing is slow.
Then, we decided to go bare HTTP, assembling the requests and reading the responses with SimpleXMLElemnt
, like this:
$request_info = array();
$full_response = @http_post_data(
'http://example.com/OTA_WS.asmx',
$REQUEST_BODY,
array(
'headers' => array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
),
'timeout' => 60,
),
$request_info
);
$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));
foreach ($response_xml->xpath('//@HotelName') as $HotelName) {
echo strval($HotelName) . "\n";
}
Note that in PHP 5.2 you'll need pecl_http, as far as (surprise-surpise!) there's no HTTP client built in.
Going to bare HTTP gained us over 30% in SOAP request times. And from then on we redirect all the performance complains to the server guys.
In the end, I'd recommend this latter approach, and not because of the performance. I think that, in general, in a dynamic language like PHP there's no benefit from all that WSDL/type-control. You don't need a fancy library to read and write XML, with all that stubs generation and dynamic proxies. Your language is already dynamic, and SimpleXMLElement
works just fine, and is so easy to use. Also, you'll have less code, which is always good.
shift
can be used in places where you want to get the first element (index=0
) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
You can do it with the pause
command, example:
dir
pause
echo Now about to end...
pause
Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.
Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master
.
(From nvie.com, Vincent Driessen, post "A successful Git branching model")
Incorporating a finished feature on develop
Finished features may be merged into the develop branch to add them to the upcoming release:
$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop
The
--no-ff
flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.
Jakub Narebski also mentions the config merge.ff
:
By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set tofalse
, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the--no-ff
option from the command line).
When set to 'only
', only such fast-forward merges are allowed (equivalent to giving the--ff-only
option from the command line).
The fast-forward is the default because:
But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.
In this case, you can end up setting this kind of config file:
[branch "master"]
# This is the list of cmdline options that should be added to git-merge
# when I merge commits into the master branch.
# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.
# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.
mergeoptions = --no-commit --no-ff
The OP adds in the comments:
I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?
Jefromi answers:
I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.
To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.
More generally, I add:
it really depends on your development workflow:
- if it is linear, one branch makes sense.
- If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.
See "When should you branch?"
Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".
Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.
If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Hope it helps.
Acepted solution implemented in PyQt5
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
self.pb.clicked.connect(self.button_click)
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print (shost)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time.
Find all info here: http://developer.android.com/tools/help/sqlite3.html
1- Go to your platform-tools folder in a command prompt
2- Enter the command adb devices
to get the list of your devices
C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb devices
List of devices attached
emulator-xxxx device
3- Connect a shell to your device:
C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s emulator-xxxx shell
4a- You can bypass this step on rooted device
run-as <your-package-name>
4b- Navigate to the folder containing your db file:
cd data/data/<your-package-name>/databases/
5- run sqlite3 to connect to your db:
sqlite3 <your-db-name>.db
6- run sqlite3 commands that you like eg:
Select * from table1 where ...;
Note: Find more commands to run below.
There are a few steps to see the tables in an SQLite database:
List the tables in your database:
.tables
List how the table looks:
.schema tablename
Print the entire table:
SELECT * FROM tablename;
List all of the available SQLite prompt commands:
.help
Maybe there is an issue with your composer file. You could try:
composer update always regenerates composer.lock and installs the lastest versions of available packages based on composer.json
composer dump-autoload won’t download a thing. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php). Ideal for when you have a new class inside your project. Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticeable)
To multiply a column of numbers with a constant(same number), I have done like this.
Let C2
to C12
be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2
to C12.
In D2
type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT)
. SELECT RIGHT ICON TO APPLY. NOW DRAG E2
THROUGH E12
. YOU HAVE DONE IT.
C D E=PRODUCT(C2:C12,20)
25 1 500
30 600
35 700
40 800
45 900
50 1000
55 1100
60 1200
65 1300
70 1400
75 1500
On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType
along with the necessary null checks:
public T GetColumnValue<T>(DataRow row, string columnName)
{
T value = default(T);
if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
{
value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
}
return value;
}
try this
bool focus = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (focus)
{
textBox1.BorderStyle = BorderStyle.None;
Pen p = new Pen(Color.Red);
Graphics g = e.Graphics;
int variance = 3;
g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
}
else
{
textBox1.BorderStyle = BorderStyle.FixedSingle;
}
}
private void textBox1_Enter(object sender, EventArgs e)
{
focus = true;
this.Refresh();
}
private void textBox1_Leave(object sender, EventArgs e)
{
focus = false;
this.Refresh();
}
For this true mysql style use this function below: 2019/02/28 15:33:12
function getDateTime() {_x000D_
var now = new Date(); _x000D_
var year = now.getFullYear();_x000D_
var month = now.getMonth()+1; _x000D_
var day = now.getDate();_x000D_
var hour = now.getHours();_x000D_
var minute = now.getMinutes();_x000D_
var second = now.getSeconds(); _x000D_
if(month.toString().length == 1) {_x000D_
month = '0'+month;_x000D_
}_x000D_
if(day.toString().length == 1) {_x000D_
day = '0'+day;_x000D_
} _x000D_
if(hour.toString().length == 1) {_x000D_
hour = '0'+hour;_x000D_
}_x000D_
if(minute.toString().length == 1) {_x000D_
minute = '0'+minute;_x000D_
}_x000D_
if(second.toString().length == 1) {_x000D_
second = '0'+second;_x000D_
} _x000D_
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second; _x000D_
return dateTime;_x000D_
}_x000D_
_x000D_
// example usage: realtime clock_x000D_
setInterval(function(){_x000D_
currentTime = getDateTime();_x000D_
document.getElementById("digital-clock").innerHTML = currentTime;_x000D_
}, 1000);
_x000D_
<div id="digital-clock"></div>
_x000D_
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.
Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/
Since I need to post code here is what each collapsible "section" should look like ->
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>1</td>
<td>05 May 2013</td>
<td>Credit Account</td>
<td class="text-success">$150.00</td>
<td class="text-error"></td>
<td class="text-success">$150.00</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="demo1">Demo1</div>
</td>
</tr>
When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.
A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.
Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.
If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).
As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.
In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive
@TargetApi(nn)
tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:
@TargetApi(11)
public void refreshActionBarIfApi11OrHigher() {
//If the API is 11 or higher, set up the actionBar and display it
if(Build.VERSION.SDK_INT >= 11) {
//ActionBar only exists at API level 11 or higher
ActionBar actionBar = getActionBar();
//This should cause onPrepareOptionsMenu() to be called.
// In versions of the API prior to 11, this only occurred when the user pressed
// the dedicated menu button, but at level 11 and above, the action bar is
// typically displayed continuously and so you will need to call this
// each time the options on your menu change.
invalidateOptionsMenu();
//Show the bar
actionBar.show();
}
}
You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.
An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.
minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.
An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.
If you don't want to SELECT SLEEP(1);
, you can also DO SLEEP(1);
It's useful for those situations in procedures where you don't want to see output.
e.g.
SELECT ...
DO SLEEP(5);
SELECT ...
you should man date
first
date +%Y-%m-%d
date +%Y-%m-%d -d yesterday
You can use %%~nf
to get the filename only as described in the reference for for
:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause
The following options are available:
Variable with modifier Description %~I Expands %I which removes any surrounding quotation marks (""). %~fI Expands %I to a fully qualified path name. %~dI Expands %I to a drive letter only. %~pI Expands %I to a path only. %~nI Expands %I to a file name only. %~xI Expands %I to a file extension only. %~sI Expands path to contain short names only. %~aI Expands %I to the file attributes of file. %~tI Expands %I to the date and time of file. %~zI Expands %I to the size of file. %~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.
I was able to fix it by running
"C:\Program Files\dotnet\dotnet.exe" "C:\fullpath\PROJECT.dll"
on the command prompt, which gave me a much more meaningful error:
"The specified framework 'Microsoft.NETCore.App', version '1.0.1' was not found. - Check application dependencies and target a framework version installed at: C:\Program Files\dotnet\shared\Microsoft.NETCore.App - The following versions are installed: 1.0.0 - Alternatively, install the framework version '1.0.1'.
As you can see, I had the wrong NET Core version installed on my server. I was able to run my application after uninstalling the previous version 1.0.0 and installing the correct version 1.0.1.
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static
and I used the same STATIC_URL in my dev settings.py file.
This causes a silent failure in django/conf/urls/static.py.
The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.
It would be thoughtful if Django spit out an error message stating you can't use a http(s)://
with DEBUG = True
I had to change STATIC_URL to be '/static/'
import os
os.system('pip install requests')
I tried above for temporary solution instead of changing docker file. Hope these might be useful to some
It should be:
$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)
Check the size of the columns in the table you are doing bulk insert/copy. the varchar or other string columns might needs to be extended or the value your are inserting needs to be trim. Column order also should be same as in table.
e.g, Increase size of varchar column 30 to 50 =>
ALTER TABLE [dbo].[TableName] ALTER COLUMN [ColumnName] Varchar(50)
A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):
curl -s -X POST --user 'myuser:mypass'
--data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
http://yourhost.domain.com/jmx-console/HtmlAdaptor
Beware: the method index may change with changes to the software. And the implementation of the web form could change.
The above is based on source of the JMX service page for the operation you want to perform:
http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName
Source of the form:
form method="post" action="HtmlAdaptor">
<input type="hidden" name="action" value="invokeOp">
<input type="hidden" name="name" value="App:service=ThisServiceOp">
<input type="hidden" name="methodIndex" value="3">
<hr align='left' width='80'>
<h4>void ThisOperation()</h4>
<p>Operation exposed for management</p>
<table cellspacing="2" cellpadding="2" border="1">
<tr class="OperationHeader">
<th>Param</th>
<th>ParamType</th>
<th>ParamValue</th>
<th>ParamDescription</th>
</tr>
<tr>
<td>p1</td>
<td>java.lang.String</td>
<td>
<input type="text" name="arg0">
</td>
<td>(no description)</td>
</tr>
<tr>
<td>p2</td>
<td>arg1Type</td>
<td>
<input type="text" name="arg1">
</td>
<td>(no description)</td>
</tr>
</table>
<input type="submit" value="Invoke">
</form>
you just try to clean maven by command
mvn clean
and after that following command
mvn eclipse:clean eclipse:eclipse
and rebuild your project....
There's a difference between pausing a thread and stopping/killing it. If stopping for you mean killing the thread, then a restart simply means creating a new thread and launching.
There are methods for killing threads from a different thread (e.g., your spawner), but they are unsafe in general. It might be safer if your thread constantly checks some flag to see if it should continue (I assume there is some loop in your thread), and have the external "controller" change the state of that flag.
You can see a little more in: http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
May I ask why you want to kill the thread and restart it? Why not just have it wait until its services are needed again? Java has synchronization mechanisms exactly for that purpose. The thread will be sleeping until the controller notifies it to continue executing.
Factory pattern is also used for loading beans through BeanFactory and Application context.
Any crawler or spider will read your index.htm
or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm
or equivalent file, it will not list all the files in such folder.
If by mistake, the programmer never included an index.htm
file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/
and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.
Except, of course, if they can enter your FTP or access your site control panel.
Pandas
is great for time series in general, and has direct support for date ranges.
For example pd.date_range()
:
import pandas as pd
from datetime import datetime
datelist = pd.date_range(datetime.today(), periods=100).tolist()
It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range
.
In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.
EDIT by OP:
If you need actual python datetimes, as opposed to Pandas timestamps:
import pandas as pd
from datetime import datetime
pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()
#OR
pd.date_range(start="2018-09-09",end="2020-02-02")
This uses the "end" parameter to match the original question, but if you want descending dates:
pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()
You also can use destroy() function. Like this
if( window.myBar!==undefined)
window.myBar.destroy();
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true,
});
For those who don't know, npp has a lot of support from plugins and other projects. You can download those plugins from SourceForge.
You need XML Tools
to format your text in n++
After you have downloaded XML Tools
..
Exit Notepad++
Go To C:\Program File\Notepad++
.... Your N++ installed folder.
copy replace
..\Plugins
subfolder and place below downloaded fileRestart and enjoy!!!
Ctrl + Alt + Shft + B to format.
This issue is far too common to still be persistent. And most answers and instructions fail to address it. Here's what to do on Windows 10:
Type environment variables
in the start search bar, and open Edit the System Environment Variables.
Click Environment Variables...
In the System Variables section, locate the variable with the key Path
and double click it.
Look for paths pointing to python files. Likely there are none. If there are, select and delete them.
Create a new variable set to the path to your python executable. Normally this is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Python38
. Ensure this by checking via your File Explorer.
Note: If you can't see AppData
, it's because you've not enabled viewing of hidden items: click the View tab and tick the Hidden Items checkbox.
Create another variable pointing to the Scripts
directory. Typically it is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Scripts
.
Restart your terminal and try typing py
, python
, python3
, or python.exe
.
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
In windows, my cmd window was already open when I set the GOPATH environment variable. First I had to close the cmd and then reopen for it to become effective.
You can use bubbling in your favor:
$('.foobar').on('click', function(e) {
// do your thing.
}).on('click', 'div', function(e) {
// clicked on descendant div
e.stopPropagation();
});
Check that the socket file exists.
$ ls -l /tmp/.s.PGSQL.5432
srwxrwxrwx 1 you wheel 0 Nov 16 09:22 /tmp/.s.PGSQL.5432
If it doesn't then check your postgresql.conf for unix_socket_directory change.
$ grep unix_socket /usr/local/var/postgres/postgresql.conf
#unix_socket_directory = '' # (change requires restart)
#unix_socket_group = '' # (change requires restart)
#unix_socket_permissions = 0777 # begin with 0 to use octal notation
Assuming you've posted valid JSON with the application/json
content type, request.json
will have the parsed JSON data.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/echo', methods=['POST'])
def hello():
return jsonify(request.json)
The modulo operator evaluates to the remainder of the division of the two integer operands. Here are a few examples:
23 % 10 evaluates to 3 (because 23/10 is 2 with a remainder of 3)
50 % 50 evaluates to 0 (50/50 is 1 with a remainder of 0)
9 % 100 evaluates to 9 (9/100 is 0 with a remainder of 9)
Since you tagged it with javascript, I would go with a timer control since your function names are 3, 5, and 8 seconds. So start your timer, 3 seconds in, call the first, 5 seconds in call the second, 8 seconds in call the third, then when it's done, stop the timer.
Normally in Javascript what you have is correct for the functions are running one after another, but since it looks like you're trying to do timed animation, a timer would be your best bet.
Ok, first of all, use the str() function in python to turn 'number' into a string
number = 9876543210 #declaring and assigning
number = str(number) #converting
Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number
print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'
if you like it in the short form
print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'
Use INDIRECT()
=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))
You can put the values as the table's keys. For example:
function addToSet(set, key)
set[key] = true
end
function removeFromSet(set, key)
set[key] = nil
end
function setContains(set, key)
return set[key] ~= nil
end
There's a more fully-featured example here.
docker images
docker rmi image_name
docker rmi -f image_name
docker ps -a
docker rm container_id
docker rm -f container_id
This is easily extendable and readable:
switch (foo) {
case 1:
case 3:
case 12:
// ...
break
case 4:
case 5:
case 6:
// something else
break
}
But not necessarily easier :)
var d = new Date();
var n = d.getFullYear();
Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:
var final = n.toString().substring(2);
This will give you the last two digits of the year (2013 will become 13, etc...)
If there's a better way, hopefully someone posts it! This is the only way I can think of. Let us know if it works!
Let's start by the following example:
Now we have 3 options to merge changes of feature branch into master branch:
Merge commits
Will keep all commits history of the feature branch and move them into the master branch
Will add extra dummy commit.
Rebase and merge
Will append all commits history of the feature branch in the front of the master branch
Will NOT add extra dummy commit.
Squash and merge
Will group all feature branch commits into one commit then append it in the front of the master branch
Will add extra dummy commit.
You can find below how the master branch will look after each one of them.
In all cases:
We can safely DELETE the feature branch.
sing the CSS @import Rule here
@import url('/css/header.css') screen;
@import url('/css/content.css') screen;
@import url('/css/sidebar.css') screen;
@import url('/css/print.css') print;
A simple for loop which tests the checked
property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked
further if needed.
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");
The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.
sudo apt-get install ruby-all-dev
worked for me.
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
A related issue:
Wasted 3 hours spanning several days.
On a AWS EC2 machine, below worked:
sudo chown -R $(whoami) /home/ubuntu/.cache
sudo chown -R $(whoami) /home/ubuntu/.config
sudo chown -R $(whoami) /home/ubuntu/.local
sudo chown -R $(whoami) /home/ubuntu/.npm
sudo chown -R $(whoami) /home/ubuntu/.pm2
Hope that helps.
1) The first step is to if you have Java installed and running your system.
which java
Usually, it should be /usr/bin/java.
2) JAVA_HOME is essentially the full path of the directory that contains a sub-directory named bin which in turn contains the java.
cd /Library/Java/
3.1) If you want to set the path only for the current session then execute this command in your terminal export JAVA_HOME=/Library/Java
3.2) If you want it to persist, you will have to add the command to your ~/.bash_profile
file
vi ~/.bash_profile
export JAVA_HOME=/Library/Java/Home
and save itsource ~/.bash_profile
4) Verify you have correctly added JAVA_HOME path. Below command should give you the proper Java version.
That's it and your ready to use!!
Please check your web.xml again. You might be making some silly mistake. As my application is working fine with the same init-param configuration...
Please copy paste the web.xml, if the problem still persists.
The problem here starts with how you're creating the string in the first place.
a = "d:\stuff\morestuff\furtherdown\THEFILE.txt"
Done this way, Python is trying to special case these: \s
, \m
, \f
, and \T
. In your case, \f
is being treated as a formfeed (0x0C) while the other backslashes are handled correctly. What you need to do is one of these:
b = "d:\\stuff\\morestuff\\furtherdown\\THEFILE.txt" # doubled backslashes
c = r"d:\stuff\morestuff\furtherdown\THEFILE.txt" # raw string, no doubling necessary
Then once you split either of these, you'll get the result you want.
Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
Please refer to the glossary: hash()
is used as a shortcut to comparing objects, an object is deemed hashable if it can be compared to other objects. that is why we use hash()
. It's also used to access dict
and set
elements which are implemented as resizable hash tables in CPython.
hash()
function is an order of magnitude (or several) less expensive.If you read about how dictionaries are implemented, they use hash tables, which means deriving a key from an object is a corner stone for retrieving objects in dictionaries in O(1)
. That's however very dependent on your hash function to be collision-resistant. The worst case for getting an item in a dictionary is actually O(n)
.
On that note, mutable objects are usually not hashable. The hashable property means you can use an object as a key. If the hash value is used as a key and the contents of that same object change, then what should the hash function return? Is it the same key or a different one? It depends on how you define your hash function.
Imagine we have this class:
>>> class Person(object):
... def __init__(self, name, ssn, address):
... self.name = name
... self.ssn = ssn
... self.address = address
... def __hash__(self):
... return hash(self.ssn)
... def __eq__(self, other):
... return self.ssn == other.ssn
...
Please note: this is all based on the assumption that the SSN never changes for an individual (don't even know where to actually verify that fact from authoritative source).
And we have Bob:
>>> bob = Person('bob', '1111-222-333', None)
Bob goes to see a judge to change his name:
>>> jim = Person('jim bo', '1111-222-333', 'sf bay area')
This is what we know:
>>> bob == jim
True
But these are two different objects with different memory allocated, just like two different records of the same person:
>>> bob is jim
False
Now comes the part where hash() is handy:
>>> dmv_appointments = {}
>>> dmv_appointments[bob] = 'tomorrow'
Guess what:
>>> dmv_appointments[jim] #?
'tomorrow'
From two different records you are able to access the same information. Now try this:
>>> dmv_appointments[hash(jim)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in __eq__
AttributeError: 'int' object has no attribute 'ssn'
>>> hash(jim) == hash(hash(jim))
True
What just happened? That's a collision. Because hash(jim) == hash(hash(jim))
which are both integers btw, we need to compare the input of __getitem__
with all items that collide. The builtin int
does not have an ssn
attribute so it trips.
>>> del Person.__eq__
>>> dmv_appointments[bob]
'tomorrow'
>>> dmv_appointments[jim]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: <__main__.Person object at 0x7f611bd37110>
In this last example, I show that even with a collision, the comparison is performed, the objects are no longer equal, which means it successfully raises a KeyError
.
Yes: replace_all
is one of the boost string algorithms:
Although it's not a standard library, it has a few things on the standard library:
replace_all
nested inside a trim
). That's a bit more involved for the standard library functions.Now, it is 2012, and jQuery has append and prepend functions that do exactly this, add content without effecting current content. Very useful.
Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page:
<iframe src="//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>
Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.
raw_input()
in python 2.7 or input()
in python 3.0, The program waits for the user to press a key.kbhit()
function in msvcrt
module.Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link
I think the following links would also help you to understand in much better way.
I hope this helps you to get your job done.
Use
var rootObject = JsonConvert.DeserializeObject<RootObject>(string json);
Create your classes on JSON 2 C#
Json.NET documentation: Serializing and Deserializing JSON with Json.NET
A tad late, but even though the following is a work-around, it solves the requirement as this works just fine:
<?
function get_sys_usr()
{
$unique_name = uniqid(); // not-so-unique id
$native_path = "./temp/$unique_name.php";
$public_path = "http://example.com/temp/$unique_name.php";
$php_content = "<? echo get_current_user(); ?>";
$process_usr = "apache"; // fall-back
if (is_readable("./temp") && is_writable("./temp"))
{
file_put_contents($native_path,$php_content);
$process_usr = trim(file_get_contents($public_path));
unlink($native_path);
}
return $process_usr;
}
echo get_sys_usr(); // www-data
?>
The code-highlighting above is not accurate, please copy & paste in your favorite editor and view as PHP code, or save and test it yourself.
As you probably know, get_current_user()
returns the owner of the "current running script" - so if you did not "chown" a script on the server to the web-server-user it will most probably be "nobody", or if the developer-user exists on the same OS, it will rather display that username.
To work around this, we create a file with the current running process. If you just require()
this into the current running script, it will return the same as the parent-script as mentioned; so, we need to run it as a separate request to take effect.
In order to make this effective, consider running a design pattern that incorporates "runtime-mode", so when the server is in "development-mode or test-mode" then only it could run this function and save its output somewhere in an include, -or just plain text or database, or whichever.
Of course you can change some particulars of the code above as you wish to make it more dynamic, but the logic is as follows:
how can I fill a multidimensional array in Java without using a loop?
Multidimensional arrays are just arrays of arrays and fill(...)
doesn't check the type of the array and the value you pass in (this responsibility is upon the developer).
Thus you can't fill a multidimensional array reasonably well without using a loop.
Be aware of the fact that, unlike languages like C or C++, Java arrays are objects and in multidimensional arrays all but the last level contain references to other Array
objects. I'm not 100% sure about this, but most likely they are distributed in memory, thus you can't just fill a contiguous block without a loop, like C/C++ would allow you to do.
//It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ...
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style = "visibility:hidden";
}
if (navigator.msSaveBlob) { // IE 10+
link.addEventListener("click", function (event) {
var blob = new Blob([CSV], {
"type": "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, fileName);
}, false);
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
//Regards
There's a small problem with the formula that you found on Google.
It should be:
(int)(Math.random() * (max - min + 1) + min)
not
(int)(Math.random() * (max - min) + min)
.
max - min + 1
is the range in which random numbers can be generated
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
I have implemented a class that works as a timer.
I leave the link here in case anyone needs it: https://github.com/ivanhalencp/python/tree/master/xTimer
There are three towers namely source tower, destination tower and helper tower. The source tower has all the disks and your target is to move all the disks to the destination tower and make sure in doing so, you never put a larger disk on top of a smaller disk. We can solve this problem using recursion in the steps below:
We have n numbers of disks on source tower
Base case: n=1 If there is only one disk in source tower, move it to destination tower.
Recursive case: n >1
Source code in Java:
private void towersOfHanoi(int n, char source, char destination, char helper) {
//Base case, If there is only one disk move it direct from source to destination
if(n==1){
System.out.println("Move from "+source+" to "+destination);
}
else{
//Step1: Move the top n-1 disks from source to helper
towersOfHanoi(n-1, source, helper, destination);
//Step2: Move the nth disk from source to destination
System.out.println("Move from "+source+" to "+destination);
/*Step3: Move the n-1 disks(those you moved from source to helper in step1)
* from helper to destination, using source(empty after step2) as helper
*/
towersOfHanoi(n-1, helper, destination, source);
}
}
After trying a number of options and running into various issue with newer versions of Excel (2016) I came across this post from MS that worked like a charm. I enhanced it bit using some code from a post by danwagner.co
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr
Function CreateGuidString(Optional IncludeHyphens As Boolean = True, Optional IncludeBraces As Boolean = False)
Dim Guid As GUID_TYPE
Dim strGuid As String
Dim retValue As LongPtr
Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
retValue = CoCreateGuid(Guid)
If retValue = 0 Then
strGuid = String$(guidLength, vbNullChar)
retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength)
If retValue = guidLength Then
' valid GUID as a string
' remove them from the GUID
If Not IncludeHyphens Then
strGuid = Replace(strGuid, "-", vbNullString, Compare:=vbTextCompare)
End If
' If IncludeBraces is switched from the default False to True,
' leave those curly braces be!
If Not IncludeBraces Then
strGuid = Replace(strGuid, "{", vbNullString, Compare:=vbTextCompare)
strGuid = Replace(strGuid, "}", vbNullString, Compare:=vbTextCompare)
End If
CreateGuidString = strGuid
End If
End If
End Function
Public Sub TestCreateGUID()
Dim Guid As String
Guid = CreateGuidString() '<~ default
Debug.Print Guid
End Sub
There are additional options in the original MS post found here: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-msoffice_custom-mso_2010/guid-run-time-error-70-permission-denied/c9ee4076-98af-4032-bc87-40ad7aa7cb38
A slight edit on an example provided in http://matplotlib.org/users/shell.html:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(np.random.rand(100), '-', picker=5) # 5 points tolerance
def onpick(event):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick points:', *zip(xdata[ind], ydata[ind]))
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
This plots a straight line plot, as Sohaib was asking
myvariable = 4
mystring = str(myvariable) # '4'
also, alternatively try repr:
mystring = repr(myvariable) # '4'
This is called "conversion" in python, and is quite common.
You need to say the following (since you befriend a whole template instead of just a specialization of it, in which case you would just need to add a <>
after the operator<<
):
template<typename T>
friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);
Actually, there is no need to declare it as a friend unless it accesses private or protected members. Since you just get a warning, it appears your declaration of friendship is not a good idea. If you just want to declare a single specialization of it as a friend, you can do that like shown below, with a forward declaration of the template before your class, so that operator<<
is regognized as a template.
// before class definition ...
template <class T>
class MyClass;
// note that this "T" is unrelated to the T of MyClass !
template<typename T>
std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);
// in class definition ...
friend std::ostream& operator<< <>(std::ostream& out, const MyClass<T>& classObj);
Both the above and this way declare specializations of it as friends, but the first declares all specializations as friends, while the second only declares the specialization of operator<<
as a friend whose T
is equal to the T
of the class granting friendship.
And in the other case, your declaration looks OK, but note that you cannot +=
a MyClass<T>
to a MyClass<U>
when T
and U
are different type with that declaration (unless you have an implicit conversion between those types). You can make your +=
a member template
// In MyClass.h
template<typename U>
MyClass<T>& operator+=(const MyClass<U>& classObj);
// In MyClass.cpp
template <class T> template<typename U>
MyClass<T>& MyClass<T>::operator+=(const MyClass<U>& classObj) {
// ...
return *this;
}
I faced the same issue while submitting the app using Xcode 4.6. It does not recognise the icons with dimension 120x120, 58x58, 29x29, etc. So when I tried to add these icons into the info.plist and submit the app for review, Xcode 4.6 did not allow me to do so. On submitting the app without the above icons, I got a mail saying -
"Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format."
Since, it was recommended and not necessary, I submitted the app anyhow. I added the above recommended icons to the bundle but did not specify them in the Info.plist. I got the same mail again. This time I ignored it and to my surprise the app was accepted.
I wanted my app to run on iOS 5 and above and therefore, I had to use Xcode 4.6 and not the latest Xcode 5 which properly allows only apps for iOS7 and above only.
UPDATE:
NOTE: "Starting February 1st 2014 new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK". https://developer.apple.com/news/?id=12172013a#top
Thus, this scenario will be invalid in future.
You should use PDO Prepare
From the link:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
make sure environment variables are set properly.
control panel-> system->advanced system settings-> select advanced Tab->
click on environment variables
and make sure in the path below line is available
`C:\Users\username\AppData\Roaming\npm`
here username will get changed based on the user
.
still if its not working yourenvironment variables are not getting reflected so please restart your machine it will work fine
if still you are facing issue your angular cli is not installed properly
please run below commands for reinstalling
npm uninstall -g @angular/cli
npm cache clean or npm cache clean --force
npm install -g @angular/cli@latest
If you're using a Frame (Class Extends Frame) you'll not get the
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
First of all you need to create a surface once and keep it somewhere handy. Example:
var surface = dojox.gfx.createSurface(domNode, widthInPx, heightInPx);
domNode
is usually an unadorned <div>
, which is used as a placeholder for a surface.
You can clear everything on the surface in one go (all existing shape objects will be invalidated, don't use them after that):
surface.clear();
All surface-related functions and methods can be found in the official documentation on dojox.gfx.Surface. Examples of use can be found in dojox/gfx/tests/
.
One option is to set up cluster logging via Fluentd/ElasticSearch as described at https://kubernetes.io/docs/user-guide/logging/elasticsearch/. Once logs are in ES, it's easy to apply filters in Kibana to view logs from certain containers.
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:
INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'
In the above query, there are 2 extra columns named email & current_time.
1) you can extract the file into a folder called
jarname.jar
and then replace the file in the folder, handy if you are updating the class a lot while debugging
2) you can extract the jar replace the file then the jar it up again
3) Open the jar with 7 zip and drag and drop your new class in to copy over the old one
I tried both
npm rebuild node-sass
and
npm install --save node-sass
Later by seeing EACCESS, i checked the folder permission of /node_modules, which was not 777 permission
Then I gave
chmod -R 777 *
-R for recursively(setting the same permission not in the dir but also inside nested sub dir) * is for all files in current directory
What is file permission
To check for permission you can use
ls -l
If u don't know about it, first see here, then check the url
Every file and directory has permission of 'rwx'(read, write, execute). and if 'x' permission is not there, then you can not execture, if no 'w', you can not write into the file. if some thing is missiing it will show in place of r/w/x with '-'. So, if 'x' permission is not there, it will show like 'rw-'
And there will be 3 category of user Owner(who created the file/directory), Group(some people who shares same permission and user previlege), Others(general public)
So 1st letter is 'd'(if it is a directory) or '-'(if it is not a directory), followed by rwx for owner, followed by for group, followed by other
drwxrwxrwx
For example, for 'node_modules'directory I want to give permission to owner all permission and for rest only read, then it will be
drwxr--r--
And about the number assume for 'r/w/x' it is 1 and for '-' it is 0, 777, first 7 is for owner, followed by group, followed by other
Let's assume the permission is rwxr-xrw-
Now 'rwx' is like '111' and it's equivalent decimal is 1*2^2+1*2^1+1*2^0=7
Now 'r-x' is like '101' and it's equivalent decimal is 1*2^2+0*2^1+1*2^0=5
Now 'rw-' is like '110' and it's equivalent decimal is 1*2^2+1*2^1+0*2^0=6
So, it will be 756
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.
Just find the text ignore: ":hidden" in your jquery validation file and comment it. After comment this it will never loss any hidden elements to validate...
Thanks
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
There is not currently any way to style HTML5 <audio>
players using CSS. Instead, you can leave off the control
attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.
// Provides ANSI C method of delaying x milliseconds
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void delayMillis(unsigned long ms) {
clock_t start_ticks = clock();
unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
while (clock()-start_ticks < ms*millis_ticks) {
}
}
/*
* Example output:
*
* CLOCKS_PER_SEC:[1000000]
*
* Test Delay of 800 ms....
*
* start[2054], end[802058],
* elapsedSec:[0.802058]
*/
int testDelayMillis() {
printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
clock_t start_t, end_t;
start_t = clock();
printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
delayMillis(800);
end_t = clock();
double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);
}
int main() {
testDelayMillis();
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TRIAL
{
public class Class1
{
static void Main(string[] args)
{
string[] fileArray = Directory.GetDirectories("YOUR PATH");
for (int i = 0; i < fileArray.Length; i++)
{
Console.WriteLine(fileArray[i]);
}
Console.ReadLine();
}
}
}
C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.
In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.
Of course, when you try to link, and it can't find foo, then you will get an error.
In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.
Apple have recently made new changes in APNs and now apple insist us to use "Token Based Authentication" instead of the traditional ways which we are using for push notification.
So does not need to worry about their expiration and this p8 certificates are for both development and production so again no need to generate 2 separate certificate for each mode.
To generate p8 just go to your developer account and select this option "Apple Push Notification Authentication Key (Sandbox & Production)"
Then will generate directly p8 file.
I hope this will solve your issue.
Read this new APNs changes from apple: https://developer.apple.com/videos/play/wwdc2016/724/
Also you can read this: https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
Seeing that:
Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.
If the current dateFormat is not recognized, you can still use the Date object using new Date(year, month, day)
In your example, this should work (I didn't test it) :
<script type="text/javascript">
$(function() {
$("#birthdate" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1920:2010',
dateFormat : 'dd-mm-yy',
defaultDate: new Date(1985,01,01)
});
});
</script>
Both do one thing in common - that is serializing an Object. Serialization is used to transfer objects or to store them. But:
So Serialization is part of Marshalling.
CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.
I also use a positive lookahead to trim repeating spaces inside the text:
s/^\s+|\s(?=\s)|\s+$//g
When you are not sure of the number of rows, then you can do it this way:
followers_df.index = range(len(followers_df))
Above are the preferred method but "cat" command can also helpful:
cat -n <filename>
Will show you whole content of file with line numbers.
For me looks better like this:
Some text, Some text, Some text
br {_x000D_
display: inline;_x000D_
content: '';_x000D_
}_x000D_
_x000D_
br:after {_x000D_
content: ', ';_x000D_
display: inline-block;_x000D_
}
_x000D_
<div style="display:block">_x000D_
<span>Some text</span>_x000D_
<br>_x000D_
<span>Some text</span>_x000D_
<br>_x000D_
<span>Some text</span>_x000D_
</div>
_x000D_
Maybe something a bit simpler:
public class Fonts {
public static HashSet<String,Typeface> fonts = new HashSet<>();
public static Typeface get(Context context, String file) {
if (! fonts.contains(file)) {
synchronized (this) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
fonts.put(name, typeface);
}
}
return fonts.get(file);
}
}
// Usage
Typeface myFont = Fonts.get("arial.ttf");
(Note this code is untested, but in general this approach should work well.)
In my case:
First remove tableName.ibd
in your database directory from Mysql and second run:
ALTER TABLE tableName DISCARD TABLESPACE;
DROP TABLE tableName;
JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);
this should work
Another possible usage of Object.create is to clone immutable objects in a cheap and effective way.
var anObj = {
a: "test",
b: "jest"
};
var bObj = Object.create(anObj);
bObj.b = "gone"; // replace an existing (by masking prototype)
bObj.c = "brand"; // add a new to demonstrate it is actually a new obj
// now bObj is {a: test, b: gone, c: brand}
Notes: The above snippet creates a clone of an source object (aka not a reference, as in cObj = aObj). It benefits over the copy-properties method (see 1), in that it does not copy object member properties. Rather it creates another -destination- object with it's prototype set on the source object. Moreover when properties are modified on the dest object, they are created "on the fly", masking the prototype's (src's) properties.This constitutes a fast an effective way of cloning immutable objects.
The caveat here is that this applies to source objects that should not be modified after creation (immutable). If the source object is modified after creation, all the clone's unmasked properties will be modified, too.
Fiddle here(http://jsfiddle.net/y5b5q/1/) (needs Object.create capable browser).
You can use an API call and Sleep:
Put this at the top of your module:
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Then you can call it in a procedure like this:
Sub test()
Dim i As Long
For i = 1 To 10
Debug.Print Now()
Sleep 500 'wait 0.5 seconds
Next i
End Sub
In the layout set your input method options to search.
<EditText
android:imeOptions="actionSearch"
android:inputType="text" />
In the java add the editor action listener.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
The runtime splits the arguments given at the console at each space.
If you call
myApp.exe arg1 arg2 arg3
The Main Method gets an array of
var args = new string[] {"arg1","arg2","arg3"}
<ion-col size="12">
<ion-card class="box-shadow ion-text-center background-size"
*ngIf="data != null"
[ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">
</ion-card>
Use select setval('payments_id_seq', 21, true);
setval
contains 3 parameters:
sequence_name
nextval
The use of true or false in 3rd parameter of setval is as follows:
SELECT setval('payments_id_seq', 21); // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true); // Same as above
SELECT setval('payments_id_seq', 21, false); // Next nextval will return 21
The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:
SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;
where table_name
is the name of the table, id
is the primary key
of the table
You could write:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="button" value="Send" />
<input type="submit" name="button" value="Cancel" />
<% Html.EndForm(); %>
And then in the page check if the name == "Send" or name == "Cancel"...
A refined version of Moob's post. Create a hash of the POST, save it as a session cookie, and compare hashes every session.
// Optionally Disable browser caching on "Back"
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );
$post_hash = md5( json_encode( $_POST ) );
if( session_start() )
{
$post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
$_SESSION[ 'post_hash' ] = $post_hash;
session_write_close();
}
else
{
$post_resubmitted = false;
}
if ( $post_resubmitted ) {
// POST was resubmitted
}
else
{
// POST was submitted normally
}
Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).
Usage: primes = list(create_prime_iterator(1, 30))
import math
import itertools
def create_prime_iterator(rfrom, rto):
"""Create iterator of prime numbers in range [rfrom, rto]"""
prefix = [2] if rfrom < 3 and rto > 1 else [] # include 2 if it is in range separately as it is a "weird" case of even prime
odd_rfrom = 3 if rfrom < 3 else make_odd(rfrom) # make rfrom an odd number so that we can skip all even nubers when searching for primes, also skip 1 as a non prime odd number.
odd_numbers = (num for num in xrange(odd_rfrom, rto + 1, 2))
prime_generator = (num for num in odd_numbers if not has_odd_divisor(num))
return itertools.chain(prefix, prime_generator)
def has_odd_divisor(num):
"""Test whether number is evenly divisable by odd divisor."""
maxDivisor = int(math.sqrt(num))
for divisor in xrange(3, maxDivisor + 1, 2):
if num % divisor == 0:
return True
return False
def make_odd(number):
"""Make number odd by adding one to it if it was even, otherwise return it unchanged"""
return number | 1
There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property
) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py
testString= "A string literal to import and test with"
Note: You could use the .txt
extension instead.
In mainfile.py
, start by opening and getting the contents.
#!usr/bin/env python3
Data=open('data.txt','r+').read()
Now you have the contents as a string, but trying to access data.testString
will cause an error, as data
is an instance of the str
class, and even if it does have a property testString
it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile
class ImportedFile:
And put this into it (with the appropriate indentation):
exec(data)
And finally, re-assign data
like so:
data=ImportedFile()
And that's it! Just access like you would for any-other module, typing print(data.testString)
will print to the console A string literal to import and test with
.
If, however, you want the equivalent of from mod import *
just drop the class, instance assignment, and de-dent the exec
.
Hope this helps:)
-Benji
You can make the single letter optional by adding a ?
after it as:
([A-Z]{1}?)
The quantifier {1}
is redundant so you can drop it.
You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:
protected $fillable = ['name', 'created_at'];
It depends on the context.
"undefined" means this value does not exist. typeof
returns "undefined"
"null" means this value exists with an empty value. When you use typeof
to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.
Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like
myString[2:end]
?
Yes, this actually works if you assign, or bind, the name,end
, to constant singleton, None
:
>>> end = None
>>> myString = '1234567890'
>>> myString[2:end]
'34567890'
Slice notation has 3 important arguments:
Their defaults when not given are None
- but we can pass them explicitly:
>>> stop = step = None
>>> start = 2
>>> myString[start:stop:step]
'34567890'
If leaving the second part means 'till the end', if you leave the first part, does it start from the start?
Yes, for example:
>>> start = None
>>> stop = 2
>>> myString[start:stop:step]
'12'
Note that we include start in the slice, but we only go up to, and not including, stop.
When step is None
, by default the slice uses 1
for the step. If you step with a negative integer, Python is smart enough to go from the end to the beginning.
>>> myString[::-1]
'0987654321'
I explain slice notation in great detail in my answer to Explain slice notation Question.
Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.
Main Notes:
An array with a key (or keys) will be determined as NOT empty by PHP.
As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).
So checking an array with empty()
doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.
So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]"
).
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.
Take these arrays for example:
/* Assigning some arrays */
// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");
// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";
// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';
If you echo out the array keys and values for the above arrays, you get the following:
ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]ARRAY THREE:
[0] => []
[1] => []
And testing the above arrays with empty()
returns the following results:
ARRAY ONE:
$ArrayOne is not emptyARRAY TWO:
$ArrayTwo is not emptyARRAY THREE:
$ArrayThree is not empty
An array will always be empty when you assign an array but don't use it thereafter, such as:
$ArrayFour = array();
This will be empty, ie PHP will return TRUE when using if empty()
on the above.
So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty()
.
In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.
However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).
Here's an approach which uses very little code to check if an array has values:
Using array_filter()
:
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
$EmptyTestArray = array_filter($ArrayOne);
if (!empty($EmptyTestArray))
{
// do some tests on the values in $ArrayOne
}
else
{
// Likely not to need an else,
// but could return message to user "you entered nothing" etc etc
}
Running array_filter()
on all three example arrays (created in the first code block in this answer) results in the following:
ARRAY ONE:
$arrayone is not emptyARRAY TWO:
$arraytwo is not emptyARRAY THREE:
$arraythree is empty
So when there are no values, whether there are keys or not, using array_filter()
to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.
I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter()
and foreach
checking if a value is found.
Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.
Skipping requestAnimationFrame cause not smooth(desired) animation at custom fps.
// Input/output DOM elements_x000D_
var $results = $("#results");_x000D_
var $fps = $("#fps");_x000D_
var $period = $("#period");_x000D_
_x000D_
// Array of FPS samples for graphing_x000D_
_x000D_
// Animation state/parameters_x000D_
var fpsInterval, lastDrawTime, frameCount_timed, frameCount, lastSampleTime, _x000D_
currentFps=0, currentFps_timed=0;_x000D_
var intervalID, requestID;_x000D_
_x000D_
// Setup canvas being animated_x000D_
var canvas = document.getElementById("c");_x000D_
var canvas_timed = document.getElementById("c2");_x000D_
canvas_timed.width = canvas.width = 300;_x000D_
canvas_timed.height = canvas.height = 300;_x000D_
var ctx = canvas.getContext("2d");_x000D_
var ctx2 = canvas_timed.getContext("2d");_x000D_
_x000D_
_x000D_
// Setup input event handlers_x000D_
_x000D_
$fps.on('click change keyup', function() {_x000D_
if (this.value > 0) {_x000D_
fpsInterval = 1000 / +this.value;_x000D_
}_x000D_
});_x000D_
_x000D_
$period.on('click change keyup', function() {_x000D_
if (this.value > 0) {_x000D_
if (intervalID) {_x000D_
clearInterval(intervalID);_x000D_
}_x000D_
intervalID = setInterval(sampleFps, +this.value);_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
function startAnimating(fps, sampleFreq) {_x000D_
_x000D_
ctx.fillStyle = ctx2.fillStyle = "#000";_x000D_
ctx.fillRect(0, 0, canvas.width, canvas.height);_x000D_
ctx2.fillRect(0, 0, canvas.width, canvas.height);_x000D_
ctx2.font = ctx.font = "32px sans";_x000D_
_x000D_
fpsInterval = 1000 / fps;_x000D_
lastDrawTime = performance.now();_x000D_
lastSampleTime = lastDrawTime;_x000D_
frameCount = 0;_x000D_
frameCount_timed = 0;_x000D_
animate();_x000D_
_x000D_
intervalID = setInterval(sampleFps, sampleFreq);_x000D_
animate_timed()_x000D_
}_x000D_
_x000D_
function sampleFps() {_x000D_
// sample FPS_x000D_
var now = performance.now();_x000D_
if (frameCount > 0) {_x000D_
currentFps =_x000D_
(frameCount / (now - lastSampleTime) * 1000).toFixed(2);_x000D_
currentFps_timed =_x000D_
(frameCount_timed / (now - lastSampleTime) * 1000).toFixed(2);_x000D_
$results.text(currentFps + " | " + currentFps_timed);_x000D_
_x000D_
frameCount = 0;_x000D_
frameCount_timed = 0;_x000D_
}_x000D_
lastSampleTime = now;_x000D_
}_x000D_
_x000D_
function drawNextFrame(now, canvas, ctx, fpsCount) {_x000D_
// Just draw an oscillating seconds-hand_x000D_
_x000D_
var length = Math.min(canvas.width, canvas.height) / 2.1;_x000D_
var step = 15000;_x000D_
var theta = (now % step) / step * 2 * Math.PI;_x000D_
_x000D_
var xCenter = canvas.width / 2;_x000D_
var yCenter = canvas.height / 2;_x000D_
_x000D_
var x = xCenter + length * Math.cos(theta);_x000D_
var y = yCenter + length * Math.sin(theta);_x000D_
_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(xCenter, yCenter);_x000D_
ctx.lineTo(x, y);_x000D_
ctx.fillStyle = ctx.strokeStyle = 'white';_x000D_
ctx.stroke();_x000D_
_x000D_
var theta2 = theta + 3.14/6;_x000D_
_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(xCenter, yCenter);_x000D_
ctx.lineTo(x, y);_x000D_
ctx.arc(xCenter, yCenter, length*2, theta, theta2);_x000D_
_x000D_
ctx.fillStyle = "rgba(0,0,0,.1)"_x000D_
ctx.fill();_x000D_
_x000D_
ctx.fillStyle = "#000";_x000D_
ctx.fillRect(0,0,100,30);_x000D_
_x000D_
ctx.fillStyle = "#080";_x000D_
ctx.fillText(fpsCount,10,30);_x000D_
}_x000D_
_x000D_
// redraw second canvas each fpsInterval (1000/fps)_x000D_
function animate_timed() {_x000D_
frameCount_timed++;_x000D_
drawNextFrame( performance.now(), canvas_timed, ctx2, currentFps_timed);_x000D_
_x000D_
setTimeout(animate_timed, fpsInterval);_x000D_
}_x000D_
_x000D_
function animate(now) {_x000D_
// request another frame_x000D_
requestAnimationFrame(animate);_x000D_
_x000D_
// calc elapsed time since last loop_x000D_
var elapsed = now - lastDrawTime;_x000D_
_x000D_
// if enough time has elapsed, draw the next frame_x000D_
if (elapsed > fpsInterval) {_x000D_
// Get ready for next frame by setting lastDrawTime=now, but..._x000D_
// Also, adjust for fpsInterval not being multiple of 16.67_x000D_
lastDrawTime = now - (elapsed % fpsInterval);_x000D_
_x000D_
frameCount++;_x000D_
drawNextFrame(now, canvas, ctx, currentFps);_x000D_
}_x000D_
}_x000D_
startAnimating(+$fps.val(), +$period.val());
_x000D_
input{_x000D_
width:100px;_x000D_
}_x000D_
#tvs{_x000D_
color:red;_x000D_
padding:0px 25px;_x000D_
}_x000D_
H3{_x000D_
font-weight:400;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h3>requestAnimationFrame skipping <span id="tvs">vs.</span> setTimeout() redraw</h3>_x000D_
<div>_x000D_
<input id="fps" type="number" value="33"/> FPS:_x000D_
<span id="results"></span>_x000D_
</div>_x000D_
<div>_x000D_
<input id="period" type="number" value="1000"/> Sample period (fps, ms)_x000D_
</div>_x000D_
<canvas id="c"></canvas><canvas id="c2"></canvas>
_x000D_
Original code by @tavnab.
I'm in the same situation as you and the solution I found for cleaning the data is deleting all the CoreData stuff that my view controllers rely on to draw it's info. But I still found this approach to be very bad, I think that a more elegant way to do this can be accomplished without storyboards and using only code to manage the transitions between view controllers.
I've found this project at Github that does all this stuff only by code and it's quite easy to understand. They use a Facebook-like side menu and what they do is change the center view controller depending if the user is logged-in or not. When the user logs out the appDelegate
removes the data from CoreData and sets the main view controller to the login screen again.
I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.
HTML
<ul>
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
</ul>
CSS
/* reset */
ul, li, a {
margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
display: inline-block;
text-align: center;
}
/* appearance styling */
ul {
/* hacks to make one side slant only */
overflow: hidden;
background: linear-gradient(to right, red, white, white, red);
}
li {
background-color: red;
transform:skewX(-20deg);
-ms-transform:skewX(-20deg);
-webkit-transform:skewX(-20deg);
}
li a {
padding: 3px 6px 3px 6px;
color: #ffffff;
text-decoration: none;
width: 80px;
transform:skewX(20deg);
-ms-transform:skewX(20deg);
-webkit-transform:skewX(20deg);
}
At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload
maybe. Something like this:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function(){
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('I am clicked!');
}
};
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
Use a JEditorPane
with a HyperlinkListener
.
All you need just run a test wait till finish, after that go to Build Setting, Search in to Build Setting Inference, change swift 3 @objc Inference to (Default). that's all what i did and worked perfect.
What you're looking for is
[ConditionalAttribute("DEBUG")]
attribute.
If you for instance write a method like :
[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
Console.WriteLine("This message was brought to you by your debugger : ");
Console.WriteLine(message);
}
any call you make to this method inside your own code will only be executed in debug mode. If you build your project in release mode, even call to the "MyLovelyDebugInfoMethod" will be ignored and dumped out of your binary.
Oh and one more thing if you're trying to determine whether or not your code is currently being debugged at the execution moment, it is also possible to check if the current process is hooked by a JIT. But this is all together another case. Post a comment if this is what you2re trying to do.
For Next button you can use xpath or cssSelector as below:
xpath for Next button: //input[@value='Next']
cssPath for Next button: input[value=Next]
Perhaps you can check it here for the LATEST version always
http://bootstrap-datepicker.readthedocs.org/en/latest/
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
startDate: '-3d'
})
or
$.fn.datepicker.defaults.format = "mm/dd/yyyy";
$('.datepicker').datepicker({
startDate: '-3d'
})
If someone wants to implement using directives then, identify (or create) a div in the index.html (just under the body tag, or at same DOM level)
<div class="google-analytics"/>
and then add the following code in the directive
myApp.directive('googleAnalytics', function ( $location, $window ) {
return {
scope: true,
link: function (scope) {
scope.$on( '$routeChangeSuccess', function () {
$window._gaq.push(['_trackPageview', $location.path()]);
});
}
};
});
@RequestMapping
is a class level
@GetMapping
is a method-level
With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation
Here is an example:
@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
at the class level, specifies the kind of requests
that this controller handles*/
public class OrderController {
@GetMapping("/current")/*@GetMapping paired with the classlevel
@RequestMapping, specifies that when an
HTTP GET request is received for /order,
orderForm() will be called to handle the request..*/
public String orderForm(Model model) {
model.addAttribute("order", new Order());
return "orderForm";
}
}
Prior to Spring 4.3, it was @RequestMapping(method=RequestMethod.GET)
I found this answer helped me the most, but found that there were some edge cases that it didn't seem to handle correctly, in particular negative cases, and also the case where my limits had 0 distance (which can happen if we are grabbing our limits from max/min of data). Testing seems to indicate that this works consistently
I use the following code. Here I assume we have [x1,x2] that we want to transform to [y1,y2]. The way I handled this was to transform [x1,x2] to [0,1] (a simple enough transformaton), then [0,1] to [y1,y2].
climate <- tibble(
Month = 1:12,
Temp = c(-4,-4,0,5,11,15,16,15,11,6,1,-3),
Precip = c(49,36,47,41,53,65,81,89,90,84,73,55)
)
#Set the limits of each axis manually:
ylim.prim <- c(0, 180) # in this example, precipitation
ylim.sec <- c(-4, 18) # in this example, temperature
b <- diff(ylim.sec)/diff(ylim.prim)
#If all values are the same this messes up the transformation, so we need to modify it here
if(b==0){
ylim.sec <- c(ylim.sec[1]-1, ylim.sec[2]+1)
b <- diff(ylim.sec)/diff(ylim.prim)
}
if (is.na(b)){
ylim.prim <- c(ylim.prim[1]-1, ylim.prim[2]+1)
b <- diff(ylim.sec)/diff(ylim.prim)
}
ggplot(climate, aes(Month, Precip)) +
geom_col() +
geom_line(aes(y = ylim.prim[1]+(Temp-ylim.sec[1])/b), color = "red") +
scale_y_continuous("Precipitation", sec.axis = sec_axis(~((.-ylim.prim[1]) *b + ylim.sec[1]), name = "Temperature"), limits = ylim.prim) +
scale_x_continuous("Month", breaks = 1:12) +
ggtitle("Climatogram for Oslo (1961-1990)")
The key parts here are that we transform the secondary y axis with ~((.-ylim.prim[1]) *b + ylim.sec[1])
and then apply the inverse to the actual values y = ylim.prim[1]+(Temp-ylim.sec[1])/b)
. We should also ensure that limits = ylim.prim
.
What you are doing, you are executing test1
$(test1)
in a sub-shell( child shell ) and Child shells cannot modify anything in parent.
You can find it in bash manual
Please Check: Things results in a subshell here
Using Management Studio - you may create a Job (unter SQL Server Agent) One Job may include several Steps from T-SQL scripts up to SSIS Packages
Jeb was faster ;)
You can use methodsolver
to find Ruby functions.
Here is a small script,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
Running this prints
Found 1 methods
- Array#unshift
You can install methodsolver using
gem install methodsolver
First, you can see if the user finished editing the text if the EditText
loses focus or if the user presses the done button (this depends on your implementation and on what fits the best for you).
Second, you can't get an EditText
instance within the TextWatcher
only if you have declared the EditText
as an instance object. Even though you shouldn't edit the EditText
within the TextWatcher
because it is not safe.
EDIT:
To be able to get the EditText
instance into your TextWatcher
implementation, you should try something like this:
public class YourClass extends Activity {
private EditText yourEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourEditText = (EditText) findViewById(R.id.yourEditTextId);
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
// yourEditText...
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
}
Note that the above sample might have some errors but I just wanted to show you an example.
@tux answer is great, just wanted to add that you can use go get to update a specific package:
go get -u full_package_name
Add this line before any output of the body, in the event you aren't using output buffering.
header("HTTP/1.1 200 OK");
Replace the message portion ('OK') with the appropriate message, and the status code with your code as appropriate (404, 501, etc)
I tried all the options mentioned above, but found finally the solution.
On my server the .php file was set to be readable by everyone, but it worked when I set the php-fpm to run under same user as nginx. I changed it in /etc/php/7.2/fpm/pool.d/www.conf
and in the configuration file I set
user = nginx
group = nginx
and then reloaded the php-fpm process Hope this helps
In the MySQL interactive client you can type:
source yourfile.sql
Alternatively you can pipe the data into mysql from the command line:
mysql < yourfile.sql
If the file doesn't specify a database then you will also need to add that:
mysql db_name < yourfile.sql
See the documentation for more details:
public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)
{
if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
return false;
for ( int i = 0; i < tbl1.Rows.Count; i++)
{
for ( int c = 0; c < tbl1.Columns.Count; c++)
{
if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))
return false;
}
}
return true;
}
You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach
.
See commit 4c4ac4d and commit 9f673f9 (Nguy?n Thái Ng?c Duy, aka pclouds):
gc --auto
takes time and can block the user temporarily (but not any less annoyingly).
Make it run in background on systems that support it.
The only thing lost with running in background is printouts. Butgc output
is not really interesting.
You can keep it in foreground by changinggc.autodetach
.
Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguy?n Thái Ng?c Duy (pclouds
).
(Merged by Junio C Hamano -- gitster
-- in commit 076c827, 15 Oct 2015)
gc
: save log from daemonizedgc --auto
and print it next timeWhile commit 9f673f9 (
gc
: config option for running--auto
in background - 2014-02-08) helps reduce some complaints about 'gc --auto
' hogging the terminal, it creates another set of problems.The latest in this set is, as the result of daemonizing,
stderr
is closed and all warnings are lost. This warning at the end ofcmd_gc()
is particularly important because it tells the user how to avoid "gc --auto
" running repeatedly.
Because stderr is closed, the user does not know, naturally they complain about 'gc --auto
' wasting CPU.Daemonized
gc
now savesstderr
to$GIT_DIR/gc.log
.
Followinggc --auto
will not run andgc.log
printed out until the user removesgc.log
.
I'm the one who donated the Ant export filter to Eclipse. I added the auto export feature, but only to my personal plug-in eclipse2ant, which I still maintain to coordinate bug fixes.
Unfortunately I have no time to merge it to the official Eclipse builds.
I recently came across Python 3 interpreter at CompileOnline.
Don't forget to keep the input field on focus for future typing with input.focus();
inside the function.
json_decode
support second argument, when it set to TRUE
it will return an Array
instead of stdClass Object
. Check the Manual page of json_decode
function to see all the supported arguments and its details.
For example try this:
$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
This should do:
samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]
So in short, no there is no alternative to reassigning.
Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:
R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
b c
a 1 A
b 2 B
c 3 C
d 4 D
e 5 E
f 6 F
g 7 G
h 8 H
i 9 I
j 10 J
R>
Can confirm that leaving px out from width and height did the trick for Outlook
<img src="image.png" style="height: 55px;width:139px;border:0;" height="55" width="139">
You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView ...>
<LinearLayout ...>
...
...
</LinearLayout>
</ScrollView>
There are various interpretation and strong opinions of the exact layer that define an ABI (application binary interface).
In my view an ABI is a subjective convention of what is considered a given/platform for a specific API. The ABI is the "rest" of conventions that "will not change" for a specific API or that will be addressed by the runtime environment: executors, tools, linkers, compilers, jvm, and OS.
If you want to use a library like joda-time you must declare a dependency on joda-time-<major>.<minor>.<patch>.jar
. The library follows best practices and use Semantic Versioning. This defines the API compatibility at three levels:
In order for you to use a new major release of the same library a lot of other conventions are still to be respected:
For example, Java standardized all these conventions, not in a tool, but in a formal JVM specification. The specification allowed other vendors to provide a different set of tools that can output compatible libraries.
Java provides two other interesting case studies for ABI: Scala versions and Dalvik virtual machine.
The Dalvik VM needs a different type of bytecode than the Java bytecode. The Dalvik libraries are obtained by converting the Java bytecode (with same API) for Dalvik. In this way you can get two versions of the same API: defined by the original joda-time-1.7.2.jar
. We could call it joda-time-1.7.2.jar
and joda-time-1.7.2-dalvik.jar
. They use a different ABI one is for the stack-oriented standard Java vms: Oracle's one, IBM's one, open Java or any other; and the second ABI is the one around Dalvik.
Scala doesn't have binary compatibility between minor Scala versions: 2.X . For this reason the same API "io.reactivex" %% "rxscala" % "0.26.5" has three versions (in the future more): for Scala 2.10, 2.11 and 2.12. What is changed? I don't know for now, but the binaries are not compatible. Probably the latest versions adds things that make the libraries unusable on the old virtual machines, probably things related to linking/naming/parameter conventions.
Java has problems with the major releases of the JVM too: 4,5,6,7,8,9. They offer only backward compatibility. Jvm9 knows how to run code compiled/targeted (javac's -target
option) for all other versions, while JVM 4 doesn't know how to run code targeted for JVM 5. All these while you have one joda-library. This incompatibility flies bellow the radar thanks to different solutions:
API and ABI are just conventions on how you define compatibility. The lower layers are generic in respect of a plethora of high level semantics. That's why it's easy to make some conventions. The first kind of conventions are about memory alignment, byte encoding, calling conventions, big and little endian encodings, etc. On top of them you get the executable conventions like others described, linking conventions, intermediate byte code like the one used by Java or LLVM IR used by GCC. Third you get conventions on how to find libraries, how to load them (see Java classloaders). As you go higher and higher in concepts you have new conventions that you consider as a given. That's why they didn't made it to the semantic versioning. They are implicit or collapsed in the major version. We could amend semantic versioning with <major>-<minor>-<patch>-<platform/ABI>
. This is what is actually happening already: platform is already a rpm
, dll
, jar
(JVM bytecode), war
(jvm+web server), apk
, 2.11
(specific Scala version) and so on. When you say APK you already talk about a specific ABI part of your API.
The top level of an abstraction (the sources written against the highest API can be recompiled/ported to any other lower level abstraction.
Let's say I have some sources for rxscala. If the Scala tools are changed I can recompile them to that. If the JVM changes I could have automatic conversions from the old machine to the new one without bothering with the high level concepts. While porting might be difficult will help any other client. If a new operating system is created using a totally different assembler code a translator can be created.
There are APIs that are ported in multiple languages like reactive streams. In general they define mappings to specific languages/platforms. I would argue that the API is the master specification formally defined in human language or even a specific programming language. All the other "mappings" are ABI in a sense, else more API than the usual ABI. The same is happening with the REST interfaces.
Just go to File -> Settings -> select Project Interpreter under Project tab -> click on the small gear icon -> Add -> System Interpreter -> select the python version you want in the drop down menu
this seemed to work for me
Consider collections.Counter (available from python 2.7 onwards). https://docs.python.org/2/library/collections.html#collections.Counter
Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
To add that using Jquery:
$('#commentForm').submit(function(){ //listen for submit event
$.each(params, function(i,param){
$('<input />').attr('type', 'hidden')
.attr('name', param.name)
.attr('value', param.value)
.appendTo('#commentForm');
});
return true;
});
I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:
public event EventHandler Foo;
If you need more complicated subscription/unsubscription logic, you can do that explicitly:
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
public static T XmlDeserializeFromString<T>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(this string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
To use it:
//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();
//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>();
In conf/tomcat-users.xml you can see what's your actual user configuration, in my case is usually user="admin" and pass="1234"
A simple Swift implementation, if you use outlets.
@IBOutlet weak var mapView: MKMapView! {
didSet {
let noLocation = CLLocationCoordinate2D()
let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 500, 500)
self.mapView.setRegion(viewRegion, animated: false)
}
}
Based on @Carnal's answer.
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
I found this suggestion useful in my case:
def product_params
params.require(:product).permit(:name).tap do |whitelisted|
whitelisted[:data] = params[:product][:data]
end
end
Check this link of Xavier's comment on github.
This approach whitelists the entire params[:measurement][:groundtruth] object.
Using the original questions attributes:
def product_params
params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
whitelisted[:groundtruth] = params[:measurement][:groundtruth]
end
end
When running python (cpython) on windows the <built-in function system>
os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.
On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.
That said, an important piece of advice comes from os.system docs, which says:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
In below code i have done operation of sum and subtraction: because of using JavaScript if you want to call function, then you have to put your below code outside of document.ready(function{ });
and outside the script end tag.
I have taken one another script tag for this operation.And put below code between script starting tag // your code // script ending tag.
function operation()
{
var txtFirstNumberValue = parseInt(document.getElementById('basic').value);
var txtSecondNumberValue =parseInt(document.getElementById('hra').value);
var txtThirdNumberValue =parseInt(document.getElementById('transport').value);
var txtFourthNumberValue =parseInt(document.getElementById('pt').value);
var txtFiveNumberValue = parseInt(document.getElementById('pf').value);
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
if (txtThirdNumberValue == "")
txtThirdNumberValue = 0;
if (txtFourthNumberValue == "")
txtFourthNumberValue = 0;
if (txtFiveNumberValue == "")
txtFiveNumberValue = 0;
var result = ((txtFirstNumberValue + txtSecondNumberValue +
txtThirdNumberValue) - (txtFourthNumberValue + txtFiveNumberValue));
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
And put onkeyup="operation();"
inside all 5 textboxes in your html form.
This code running in both Firefox and Chrome.
class
is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class
itself.
e.g.
class ANewType
{
// ... details
};
This defines a new type called ANewType
which is a class type.
You can then use this in function declarations:
void function(ANewType object);
You can then pass objects of type ANewType
into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.
If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.
void function(ANewType& object); // object passed by reference
This syntax means that any use of object
in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.
[* The class
keyword is also used in template definitions, but that's a different subject.]
You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.
curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:ACTION_YOU_WANT_TO_CALL" --data @FILE_NAME URL_OF_THE_SERVICE
Above command was helpful for me
Example
curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:urn:GetVehicleLimitedInfo" --data @request.xml http://11.22.33.231:9080/VehicleInfoQueryService.asmx
You don't want to stringify large objects into a single localStorage entry. That would be very inefficient - the whole thing would have to be parsed and re-encoded every time some slight detail changes. Also, JSON can't handle multiple cross references within an object structure and wipes out a lot of details, e.g. the constructor, non-numerical properties of arrays, what's in a sparse entry, etc.
Instead, you can use Rhaboo. It stores large objects using lots of localStorage entries so you can make small changes quickly. The restored objects are much more accurate copies of the saved ones and the API is incredibly simple. E.g.:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
BTW, I wrote it.
You should put your model class before create_all()
call, like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
If your models are declared in a separate module, import them before calling create_all()
.
Say, the User
model is in a file called models.py
,
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
# See important note below
from models import User
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
Important note: It is important that you import your models after initializing the db
object since, in your models.py
_you also need to import the db
object from this module.
I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:
{ "myDateField": { "$date" : <ms-since-epoch> } }
As described here: https://docs.meteor.com/api/ejson.html
Benefits
Conclusion
I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?
This was the only thing that worked for me. As everything had to be an absolute path:
C:\Program Files\MongoDB\Server\3.2\bin>mongod --install --dbpath=c:/data/db --logpath=c:/data/logs/log.txt
I also had to run it from admin cmd