In the case of some programs, these errors are normal and should not be fixed.
I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.
If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
Rather than keeping the values to be plotted in an array, store them in a matrix. By default the entire matrix will be treated as one data set. However if you add the same number of modifiers to the plot, e.g. the col(), as you have rows in the matrix, R will figure out that each row should be treated independently. For example:
x = matrix( c(21,50,80,41), nrow=2 )
y = matrix( c(1,2,1,2), nrow=2 )
plot(x, y, col("red","blue")
This should work unless your data sets are of differing sizes.
I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.
Simple way to do it would be:
int n = 4; // Or whatever value - n has to be global so that the event handler can access it
private void btnDisplay_Click(object sender, EventArgs e)
{
TextBox[] textBoxes = new TextBox[n];
Label[] labels = new Label[n];
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
// Here you can modify the value of the textbox which is at textBoxes[i]
labels[i] = new Label();
// Here you can modify the value of the label which is at labels[i]
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
The code above assumes that you have a button btnDisplay
and it has a onClick
event assigned to btnDisplay_Click
event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.
To do it using a User Control simply do this.
Okay, first of all go and create a new user control and put a text box and label in it.
Lets say they are called txtSomeTextBox
and lblSomeLabel
. In the code behind add this code:
public string GetTextBoxValue()
{
return this.txtSomeTextBox.Text;
}
public string GetLabelValue()
{
return this.lblSomeLabel.Text;
}
public void SetTextBoxValue(string newText)
{
this.txtSomeTextBox.Text = newText;
}
public void SetLabelValue(string newText)
{
this.lblSomeLabel.Text = newText;
}
Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):
private void btnDisplay_Click(object sender, EventArgs e)
{
MyUserControl[] controls = new MyUserControl[n];
for (int i = 0; i < n; i++)
{
controls[i] = new MyUserControl();
controls[i].setTextBoxValue("some value to display in text");
controls[i].setLabelValue("some value to display in label");
// Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(controls[i]);
}
}
Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:
public TextBox myTextBox;
public Label myLabel;
In the constructor of the user control do this:
myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;
Then in your program if you want to modify the text value of either just do this.
control[i].myTextBox.Text = "some random text"; // Same applies to myLabel
Hope it helped :)
We use a simple fail task to force the user to specify the Ansible limit option, so that we don't execute on all hosts by default/accident.
The easiest way I found is this:
---
- name: Force limit
# 'all' is okay here, because the fail task will force the user to specify a limit on the command line, using -l or --limit
hosts: 'all'
tasks:
- name: checking limit arg
fail:
msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
when: ansible_limit is not defined
run_once: true
Now we must use the -l
(= --limit
option) when we run the playbook, e.g.
ansible-playbook playbook.yml -l www.example.com
Limit to one or more hosts This is required when one wants to run a playbook against a host group, but only against one or more members of that group.
Limit to one host
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1"
Limit to multiple hosts
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1,host2"
Negated limit.
NOTE: Single quotes MUST be used to prevent bash interpolation.
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!host1'
Limit to host group
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'group1'
I tried on rooted Android 4.2.2 and this method works for me:
private void installApk(String filename) {
File file = new File(filename);
if(file.exists()){
try {
final String command = "pm install -r " + file.getAbsolutePath();
Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I really like Tovask's answer but it doesn't work due to the function having the name download
(this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".
The following code has been tested in Chrome and Firefox and seems to work fine in both.
JavaScript:
function prepDownload(a, canvas, name) {
a.download = name
a.href = canvas.toDataURL()
}
HTML:
<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>
The reason this puts NaN
into a column is because df.index
and the Index
of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas
tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN
wherever they aren't aligned. Play around with the reindex
and align
methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align()
works with partially aligned indices:
In [7]: from pandas import DataFrame
In [8]: from numpy.random import randint
In [9]: df = DataFrame({'a': randint(3, size=10)})
In [10]:
In [10]: df
Out[10]:
a
0 0
1 2
2 0
3 1
4 0
5 0
6 0
7 0
8 0
9 0
In [11]: s = df.a[:5]
In [12]: dfa, sa = df.align(s, axis=0)
In [13]: dfa
Out[13]:
a
0 0
1 2
2 0
3 1
4 0
5 0
6 0
7 0
8 0
9 0
In [14]: sa
Out[14]:
0 0
1 2
2 0
3 1
4 0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
Name: a, dtype: float64
Another alternative for this (older) question:
import datetime
import pytz
import time
pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'
The above is a good way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1.) Anyway, the real work is being done by time.strftime("%H:%M:%S", time.gmtime(36901))
which does work on the output of gmtime()
.
>>> time.strftime("%H:%M:%S",time.gmtime(36901)) # secs = 36901
'10:15:01'
And, that's it! (NOTE: Here's a link to format specifiers for time.strftime()
. ...)
public static string FromSqlType(string sqlTypeString)
{
if (! Enum.TryParse(sqlTypeString, out Enums.SQLType typeCode))
{
throw new Exception("sql type not found");
}
switch (typeCode)
{
case Enums.SQLType.varbinary:
case Enums.SQLType.binary:
case Enums.SQLType.filestream:
case Enums.SQLType.image:
case Enums.SQLType.rowversion:
case Enums.SQLType.timestamp://?
return "byte[]";
case Enums.SQLType.tinyint:
return "byte";
case Enums.SQLType.varchar:
case Enums.SQLType.nvarchar:
case Enums.SQLType.nchar:
case Enums.SQLType.text:
case Enums.SQLType.ntext:
case Enums.SQLType.xml:
return "string";
case Enums.SQLType.@char:
return "char";
case Enums.SQLType.bigint:
return "long";
case Enums.SQLType.bit:
return "bool";
case Enums.SQLType.smalldatetime:
case Enums.SQLType.datetime:
case Enums.SQLType.date:
case Enums.SQLType.datetime2:
return "DateTime";
case Enums.SQLType.datetimeoffset:
return "DateTimeOffset";
case Enums.SQLType.@decimal:
case Enums.SQLType.money:
case Enums.SQLType.numeric:
case Enums.SQLType.smallmoney:
return "decimal";
case Enums.SQLType.@float:
return "double";
case Enums.SQLType.@int:
return "int";
case Enums.SQLType.real:
return "Single";
case Enums.SQLType.smallint:
return "short";
case Enums.SQLType.uniqueidentifier:
return "Guid";
case Enums.SQLType.sql_variant:
return "object";
case Enums.SQLType.time:
return "TimeSpan";
default:
throw new Exception("none equal type");
}
}
public enum SQLType
{
varbinary,//(1)
binary,//(1)
image,
varchar,
@char,
nvarchar,//(1)
nchar,//(1)
text,
ntext,
uniqueidentifier,
rowversion,
bit,
tinyint,
smallint,
@int,
bigint,
smallmoney,
money,
numeric,
@decimal,
real,
@float,
smalldatetime,
datetime,
sql_variant,
table,
cursor,
timestamp,
xml,
date,
datetime2,
datetimeoffset,
filestream,
time,
}
This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.
Thought I'd contribute the one I use:
testin <- function(package){if (!package %in% installed.packages())
install.packages(package)}
testin("packagename")
In Sender Activity Side:
Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);
In Receiver Activity Side:
int receiveValue = getIntent().getIntExtra("value", 0);
I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using
Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering
It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.
use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering
SELECT GrondOfLucht
FROM dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)
While creating new Blank UWP project in Visual Studio 2017 Community, this error came up.
After the suggested remedy (restoring NuGet cache) the reference resurfaced in the Project.
If you need to process huge amount of data with high performance
OR
If data model is not predetermined
then
NoSQL database is a better choice.
If you have node
then you can use fs
like in this answer to get all the files:
const { resolve } = require('path'),
{ readdir } = require('fs').promises;
async function getFiles(dir) {
const dirents = await readdir(dir, { withFileTypes: true });
const files = await Promise.all(dirents.map((dirent) => {
const res = resolve(dir, dirent.name);
return dirent.isDirectory() ? getFiles(res) : res;
}));
return Array.prototype.concat(...files);
}
And you might use that like this:
const directory = "./Documents/";
getFiles(directory).then(results => {
const html = `<ul>` +
results.map(fileOrDirectory => `<li>${fileOrDirectory}</li>`).join('\n') +
`</ul>`;
process.stdout.write(html);
// or you could use something like fs.writeFile to write the file directly
});
You could call it at the command-line with something like this:
$ node thatScript.js > index.html
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
I use this solution which I reproduce below:
#define MACROSTR(k) #k
#define X_NUMBERS \
X(kZero ) \
X(kOne ) \
X(kTwo ) \
X(kThree ) \
X(kFour ) \
X(kMax )
enum {
#define X(Enum) Enum,
X_NUMBERS
#undef X
} kConst;
static char *kConstStr[] = {
#define X(String) MACROSTR(String),
X_NUMBERS
#undef X
};
int main(void)
{
int k;
printf("Hello World!\n\n");
for (k = 0; k < kMax; k++)
{
printf("%s\n", kConstStr[k]);
}
return 0;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (range.length==0) {
if ([text isEqualToString:@"\n"]) {
[txtView resignFirstResponder];
if(textView.returnKeyType== UIReturnKeyGo){
[self PreviewLatter];
return NO;
}
return NO;
}
} return YES;
}
Starting with version 3.5.0 of Mockito and using the InlineMockMaker
, you can now mock object constructions:
try (MockedConstruction mocked = mockConstruction(A.class)) {
A a = new A();
when(a.check()).thenReturn("bar");
}
Inside the try-with-resources
construct all object constructions are returning a mock.
Although having the parameters in the path has some advantages, there are, IMO, some outweighing factors.
Not all characters needed for a search query are permitted in a URL. Most punctuation and Unicode characters would need to be URL encoded as a query string parameter. I'm wrestling with the same problem. I would like to use XPath in the URL, but not all XPath syntax is compatible with a URI path. So for simple paths, /cars/doors/driver/lock/combination
would be appropriate to locate the 'combination
' element in the driver's door XML document. But /car/doors[id='driver' and lock/combination='1234']
is not so friendly.
There is a difference between filtering a resource based on one of its attributes and specifying a resource.
For example, since
/cars/colors
returns a list of all colors for all cars (the resource returned is a collection of color objects)
/cars/colors/red,blue,green
would return a list of color objects that are red, blue or green, not a collection of cars.
To return cars, the path would be
/cars?color=red,blue,green
or /cars/search?color=red,blue,green
Parameters in the path are more difficult to read because name/value pairs are not isolated from the rest of the path, which is not name/value pairs.
One last comment. I prefer /garages/yyy/cars
(always plural) to /garage/yyy/cars
(perhaps it was a typo in the original answer) because it avoids changing the path between singular and plural. For words with an added 's', the change is not so bad, but changing /person/yyy/friends
to /people/yyy
seems cumbersome.
LIMIT limit OFFSET offset
will work.
But you need a stable ORDER BY
clause, or the values may be ordered differently for the next call (after any write on the table for instance).
SELECT *
FROM msgtable
WHERE cdate = '2012-07-18'
ORDER BY msgtable_id -- or whatever is stable
LIMIT 10
OFFSET 50; -- to skip to page 6
Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.
Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.
To avoid that shift or for better performance with big tables use smarter paging strategies:
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name
The standard technique in plugin form would look something like this:
(function($) {
$.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this; // for chaining...
}
})(jQuery);
Then you could just say $('#div_element2').goTo();
to scroll to <div id="div_element2">
. Options handling and configurability is left as an exercise for the reader.
/data/data/"your app package name "
but you wont able to read that unless you have a rooted device
I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.
By all means, please use set()
to create an empty set.
But, if you want to impress people, tell them that you can create an empty set using literals and *
with Python >= 3.5 (see PEP 448) by doing:
>>> s = {*()} # or {*{}} or {*[]}
>>> print(s)
set()
this is basically a more condensed way of doing {_ for _ in ()}
, but, don't do this.
Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.
I suggest the use of htop, as a better alternative to top.
You can try to use the methods winfo_screenwidth
and winfo_screenheight
, which return respectively the width and height (in pixels) of your Tk
instance (window), and with some basic math you can center your window:
import tkinter as tk
from PyQt4 import QtGui # or PySide
def center(toplevel):
toplevel.update_idletasks()
# Tkinter way to find the screen resolution
# screen_width = toplevel.winfo_screenwidth()
# screen_height = toplevel.winfo_screenheight()
# PyQt way to find the screen resolution
app = QtGui.QApplication([])
screen_width = app.desktop().screenGeometry().width()
screen_height = app.desktop().screenGeometry().height()
size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
x = screen_width/2 - size[0]/2
y = screen_height/2 - size[1]/2
toplevel.geometry("+%d+%d" % (x, y))
toplevel.title("Centered!")
if __name__ == '__main__':
root = tk.Tk()
root.title("Not centered")
win = tk.Toplevel(root)
center(win)
root.mainloop()
I am calling update_idletasks
method before retrieving the width and the height of the window in order to ensure that the values returned are accurate.
Tkinter doesn't see if there are 2 or more monitors extended horizontal or vertical. So, you 'll get the total resolution of all screens together and your window will end-up somewhere in the middle of the screens.
PyQt from the other hand, doesn't see multi-monitors environment either, but it will get only the resolution of the Top-Left monitor (Imagine 4 monitors, 2 up and 2 down making a square). So, it does the work by putting the window on center of that screen. If you don't want to use both, PyQt and Tkinter, maybe it would be better to go with PyQt from start.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
ProgressBar color can be changed as follows:
/res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorAccent">#FF4081</color>
</resources>
/res/values/styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorAccent">@color/colorAccent</item>
</style>
onCreate:
progressBar = (ProgressBar) findViewById(R.id.progressBar);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Drawable drawable = progressBar.getIndeterminateDrawable().mutate();
drawable.setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.SRC_IN);
progressBar.setIndeterminateDrawable(drawable);
}
Close the terminal(End the current session). Open it again.
Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse
to convert a string into a JavaScript object. You cannot use JSON.parse
to convert a JavaScript object into a JavaScript object.
//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log
the following...
console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'
You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]
. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.
Why does this happen? Because you are starting with a string "'"
, then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'"
.
Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.
See this fiddle: http://jsfiddle.net/NrnK5/
install below libraries
var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');
connect ur mongo db :
mongoose.connect(‘url_here’);
Define database Schema
var Item = new ItemSchema({
img: {
data: Buffer,
contentType: String
}
}
);
var Item = mongoose.model('Clothes',ItemSchema);
using the middleware Multer to upload the photo on the server side.
app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename;
},
}));
post req to our db
app.post(‘/api/photo’,function(req,res){
var newItem = new Item();
newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
newItem.img.contentType = ‘image/png’;
newItem.save();
});
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
Both syntaxes are correct. But the result would be Array
. You probably want to do something like this:
foreach ($tmpArray[1] as $value) {
echo $value[0];
foreach($value[1] as $val){
echo $val;
}
}
This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).
consider using
df['column name'].astype('Int64')
nan
will be changed to NaN
Generally, it's considered a bad practice to style standard form controls because the output looks so different on each browser. See: http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-single/ for some rendered examples.
That being said, I've had some luck making the background color an RGBA value:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: #d00;
}
select {
background: rgba(255,255,255,0.1) url('http://www.google.com/images/srpr/nav_logo6g.png') repeat-x 0 0;
padding:4px;
line-height: 21px;
border: 1px solid #fff;
}
</style>
</head>
<body>
<select>
<option>Foo</option>
<option>Bar</option>
<option>Something longer</option>
</body>
</html>
Google Chrome still renders a gradient on top of the background image in the color that you pass to rgba(r,g,b,0.1) but choosing a color that compliments your image and making the alpha 0.1 reduces the effect of this.
What you need is nm
and its -D
option:
$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
U atanf
U calloc
.
.
.
Exported sumbols are indicated by a T
. Required symbols that must be loaded from other shared objects have a U
. Note that the symbol table does not include just functions, but exported variables as well.
See the nm
manual page for more information.
On some system, instead of the .bashrc file, you can edit your profils' specific by editing:
sudo nano /etc/profile
You should do this using jQuery.ajaxStart
and jQuery.ajaxStop
.
jQuery.ajaxStart
jQuery.ajaxStop
<div id="loading" style="display:none">Your Image</div>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
$(function () {
var loading = $("#loading");
$(document).ajaxStart(function () {
loading.show();
});
$(document).ajaxStop(function () {
loading.hide();
});
$("#startAjaxRequest").click(function () {
$.ajax({
url: "http://www.google.com",
// ...
});
});
});
</script>
<button id="startAjaxRequest">Start</button>
PUT = replace the ENTIRE RESOURCE with the new representation provided
PATCH = replace parts of the source resource with the values provided AND|OR other parts of the resource are updated that you havent provided (timestamps) AND|OR updating the resource effects other resources (relationships)
c:\> node.exe %CD%\hello.js
%CD% captures the current directory under DOS
From Oracle 18c
you could use Inline External Tables:
Inline external tables enable the runtime definition of an external table as part of a SQL statement, without creating the external table as persistent object in the data dictionary.
With inline external tables, the same syntax that is used to create an external table with a CREATE TABLE statement can be used in a SELECT statement at runtime. Specify inline external tables in the FROM clause of a query block. Queries that include inline external tables can also include regular tables for joins, aggregation, and so on.
INSERT INTO target_table(time_id, prod_id, quantity_sold, amount_sold)
SELECT time_id, prod_id, quantity_sold, amount_sold
FROM EXTERNAL (
(time_id DATE NOT NULL,
prod_id INTEGER NOT NULL,
quantity_sold NUMBER(10,2),
amount_sold NUMBER(10,2))
TYPE ORACLE_LOADER
DEFAULT DIRECTORY data_dir1
ACCESS PARAMETERS (
RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY '|')
LOCATION ('sales_9.csv') REJECT LIMIT UNLIMITED) sales_external;
Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm
$('#myFile').change(function () {
LoadFile("myFile");//function to do processing of file.
$('#myFile').val('');// set the value to empty of myfile control.
});
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
Using Java 8 lambda expression:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
This is a much easier way to do it within Hive's SQL:
set hive.execution.engine=tez;
set hive.merge.tezfiles=true;
set hive.exec.compress.output=false;
INSERT OVERWRITE DIRECTORY '/tmp/job/'
ROW FORMAT DELIMITED
FIELDS TERMINATED by ','
NULL DEFINED AS ''
STORED AS TEXTFILE
SELECT * from table;
You can stash your local changes first, then pull, then pop the stash.
git stash
git pull origin master
git stash pop
Anything that overrides changes from remote will have conflicts which you will have to manually resolve.
You can just add the number to the cell with the date.
so if A1: 12/3/2012
and A2: =A1+7
then A2 would display 12/10/2012
For dynamic SQL use:
'IN(' ||array_to_string(some_array, ',')||')'
DO LANGUAGE PLPGSQL $$
DECLARE
some_array bigint[];
sql_statement text;
BEGIN
SELECT array[1, 2] INTO some_array;
RAISE NOTICE '%', some_array;
sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
RAISE NOTICE '%', sql_statement;
END;
$$;
Result:
NOTICE: {1,2}
NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)
I liked some of the answers where it reads strace
checks how you interacts with your operating system.
This is exactly what we can see. The system calls. If you compare strace
and ltrace
the difference is more obvious.
$>strace -c cd
Desktop Documents Downloads examples.desktop Music Pictures Public Templates Videos
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
0.00 0.000000 0 7 read
0.00 0.000000 0 1 write
0.00 0.000000 0 11 close
0.00 0.000000 0 10 fstat
0.00 0.000000 0 17 mmap
0.00 0.000000 0 12 mprotect
0.00 0.000000 0 1 munmap
0.00 0.000000 0 3 brk
0.00 0.000000 0 2 rt_sigaction
0.00 0.000000 0 1 rt_sigprocmask
0.00 0.000000 0 2 ioctl
0.00 0.000000 0 8 8 access
0.00 0.000000 0 1 execve
0.00 0.000000 0 2 getdents
0.00 0.000000 0 2 2 statfs
0.00 0.000000 0 1 arch_prctl
0.00 0.000000 0 1 set_tid_address
0.00 0.000000 0 9 openat
0.00 0.000000 0 1 set_robust_list
0.00 0.000000 0 1 prlimit64
------ ----------- ----------- --------- --------- ----------------
100.00 0.000000 93 10 total
On the other hand there is ltrace
that traces functions.
$>ltrace -c cd
Desktop Documents Downloads examples.desktop Music Pictures Public Templates Videos
% time seconds usecs/call calls function
------ ----------- ----------- --------- --------------------
15.52 0.004946 329 15 memcpy
13.34 0.004249 94 45 __ctype_get_mb_cur_max
12.87 0.004099 2049 2 fclose
12.12 0.003861 83 46 strlen
10.96 0.003491 109 32 __errno_location
10.37 0.003303 117 28 readdir
8.41 0.002679 133 20 strcoll
5.62 0.001791 111 16 __overflow
3.24 0.001032 114 9 fwrite_unlocked
1.26 0.000400 100 4 __freading
1.17 0.000372 41 9 getenv
0.70 0.000222 111 2 fflush
0.67 0.000214 107 2 __fpending
0.64 0.000203 101 2 fileno
0.62 0.000196 196 1 closedir
0.43 0.000138 138 1 setlocale
0.36 0.000114 114 1 _setjmp
0.31 0.000098 98 1 realloc
0.25 0.000080 80 1 bindtextdomain
0.21 0.000068 68 1 opendir
0.19 0.000062 62 1 strrchr
0.18 0.000056 56 1 isatty
0.16 0.000051 51 1 ioctl
0.15 0.000047 47 1 getopt_long
0.14 0.000045 45 1 textdomain
0.13 0.000042 42 1 __cxa_atexit
------ ----------- ----------- --------- --------------------
100.00 0.031859 244 total
Although I checked the manuals several time, I haven't found the origin of the name strace
but it is likely system-call trace, since this is obvious.
There are three bigger notes to say about strace
.
Note 1: Both these functions strace
and ltrace
are using the system call ptrace
. So ptrace
system call is effectively how strace
works.
The ptrace() system call provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers. It is primarily used to implement breakpoint debugging and system call tracing.
Note 2: There are different parameters you can use with strace
, since strace
can be very verbose. I like to experiment with -c
which is like a summary of things. Based on -c
you can select one system-call like -e trace=open
where you will see only that call. This can be interesting if you are examining what files will be opened during the command you are tracing.
And of course, you can use the grep
for the same purpose but note you need to redirect like this 2>&1 | grep etc
to understand that config files are referenced when the command was issued.
Note 3: I find this very important note. You are not limited to a specific architecture. strace
will blow you mind, since it can trace over binaries of different architectures.
Probably the mymobileNO.titleLabel.text value doesn't include the scheme tel://
Your code should look like this:
NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
This is because, in the constructor, you declared a local variable with the same name as an attribute.
To allocate an integer array which all elements are initialized to zero, write this in the constructor:
data = new int[3];
To allocate an integer array which has other initial values, put this code in the constructor:
int[] temp = {2, 3, 7};
data = temp;
or:
data = new int[] {2, 3, 7};
Try to run it at Framework64.
Example:
32 bit
C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe D:\DemoIconOverlaySln\Demo\bin\Debug\HandleOverlayWarning\AsmOverlayIconWarning.dll /codebase
64 bit
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\RegAsm.exe D:\DemoIconOverlaySln\Demo\bin\Debug\HandleOverlayWarning\AsmOverlayIconWarning.dll /codebase
I would just add an alternative to all those HeaderRecyclerViewAdapter implementation. CompoundAdapter:
https://github.com/negusoft/CompoundAdapter-android
It is a more flexible approach, since you can create a AdapterGroup out of Adapters. For the header example, use your adapter as it is, along with an adapter containing one item for the header:
AdapterGroup adapterGroup = new AdapterGroup();
adapterGroup.addAdapter(SingleAdapter.create(R.layout.header));
adapterGroup.addAdapter(new MyAdapter(...));
recyclerView.setAdapter(adapterGroup);
It is fairly simple and readable. You can implement more complex adapter easily using the same principle.
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
@ModelAttribute can be used as the method arguments / parameter or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to an model object
For me i put this codes in public\index.php
file. and it worked just fine for all CRUD operations.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");
You can use URLConnection
with setDoOutput
(true)
, getOutputStream()
(for sending data), and getInputStream()
(for receiving). Sun has an example for exactly this.
If the response code isn't 200 or 2xx, use getErrorStream()
instead of getInputStream().
Just noting this here in case anyone else has a similar issue.
If you're directing a request directly to a JSP, using Apache Tomcat web.xml configuration, then ${requestScope.attr}
doesn't seem to work, instead ${param.attr}
contains the request attribute attr
.
Open Reg HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\
make a loop to get all subkeys
the subkeys you are interested with are those started with [S-1-5-21-] which means user (see key name [ProfileImagePath] they are always started with a path c:\Users)
Those starting with [S-1-5-21-12] are all local users
Those starting with [S-1-5-21-13] are all network users [if joined to Domained network] that are previously logged on the machine.
like this
\begin{align}
x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\
y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber
\end{align}
If you are working in JS, here is a very terse version
myString = myString.replace(/[^A-Za-z0-9 -]/g, "");
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:
>>> 42
42
>>> n
17
>>> n + 25
42
When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n. When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values.
You can use this site to find subdomains Find subdomains
This tool will try a zone transfer and also query search engines for list of subdomains.
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json);
you can use. The blob will most likely be of type JsonObject
which is derived from JsonValue
, but could be JsonArray
. Check the blob.JsonType
if you need to know.
And to answer you question, YES, you may replace json
with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
Update as of npm 5:
As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.
Original Answer:
To add package in dependencies:
npm install my_dep --save
or
npm install my_dep -S
or
npm i my_dep -S
To add package in devDependencies
npm install my_test_framework --save-dev
or
npm install my_test_framework -D
or
npm i my_test_framework -D
Working fine for windows by navigating to %APPDATA%\syntevo\SmartGit\ and delete all settings.xml, then open the installed software
100% Working!
To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,
export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html
File: body_html.html
<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>
Note: Tested in RHEL, CentOS, Ubuntu.
It can also be solved using the following query along with other answers.
WITH purchase_data AS (
SELECT address_id, purchased_at, product_id,
row_number() OVER (PARTITION BY address_id ORDER BY purchased_at DESC) AS row_number
FROM purchases
WHERE product_id = 1)
SELECT address_id, purchased_at, product_id
FROM purchase_data where row_number = 1
print $input."<hr>".ereg_replace('/&/', ':::', $input);
becomes
print $input."<hr>".preg_replace('/&/', ':::', $input);
More example :
$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );
is changed to
$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );
Here is an easier way you can write the time format (hh:mm:ss tt)
and display them separately if you wish.
string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00") + DateTime.Now.ToString(" tt");
or just simply:
DateTime.Now.ToString("hh:mm:ss tt")
Old question now, but if anyone else comes across this through a search as I did, it appears that IE9 will be making use of this to configure the behaviour of resources when using the back and forward buttons. When max-age=0 is used, the browser will use the last version when viewing a resource on a back/forward press. If no-cache is used, the resource will be refetched.
Further details about IE9 caching can be seen on this msdn caching blog post.
In Scala it is very comfortable with https://github.com/lloydmeta/enumeratum
Project is really good with examples and documentation
Just this example from their docs should makes you interested in
import enumeratum._
sealed trait Greeting extends EnumEntry
object Greeting extends Enum[Greeting] {
/*
`findValues` is a protected method that invokes a macro to find all `Greeting` object declarations inside an `Enum`
You use it to implement the `val values` member
*/
val values = findValues
case object Hello extends Greeting
case object GoodBye extends Greeting
case object Hi extends Greeting
case object Bye extends Greeting
}
// Object Greeting has a `withName(name: String)` method
Greeting.withName("Hello")
// => res0: Greeting = Hello
Greeting.withName("Haro")
// => java.lang.IllegalArgumentException: Haro is not a member of Enum (Hello, GoodBye, Hi, Bye)
// A safer alternative would be to use `withNameOption(name: String)` method which returns an Option[Greeting]
Greeting.withNameOption("Hello")
// => res1: Option[Greeting] = Some(Hello)
Greeting.withNameOption("Haro")
// => res2: Option[Greeting] = None
// It is also possible to use strings case insensitively
Greeting.withNameInsensitive("HeLLo")
// => res3: Greeting = Hello
Greeting.withNameInsensitiveOption("HeLLo")
// => res4: Option[Greeting] = Some(Hello)
// Uppercase-only strings may also be used
Greeting.withNameUppercaseOnly("HELLO")
// => res5: Greeting = Hello
Greeting.withNameUppercaseOnlyOption("HeLLo")
// => res6: Option[Greeting] = None
// Similarly, lowercase-only strings may also be used
Greeting.withNameLowercaseOnly("hello")
// => res7: Greeting = Hello
Greeting.withNameLowercaseOnlyOption("hello")
// => res8: Option[Greeting] = Some(Hello)
As @moeffju suggests, this can be achieved with CSS. The issue I ran into (which I'm surprised I haven't seen discussed) is the trick of overlapping previous elements with padding or a transparent border prevents hover and click actions at the bottom of those sections because the following one comes higher in the z-order.
The best fix I found was to place section content in a div
that is at z-index: 1
:
// Apply to elements that serve as anchors
.offset-anchor {
border-top: 75px solid transparent;
margin: -75px 0 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
}
// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
position: relative;
z-index: 1;
}
update: added safer method
check out the previous (unchanged) state of your file; notice the double dash
git checkout HEAD^ -- /path/to/file
commit it:
git commit -am "revert changes on this file, not finished with it yet"
push it, no force needed:
git push
get back to your unfinished work, again do (3 times arrow up):
git checkout HEAD^ -- /path/to/file
To modify the last commit of the repository HEAD, obfuscating your accidentally pushed work, while potentially running into a conflict with your colleague who may have pulled it already, and who will grow grey hair and lose lots of time trying to reconcile his local branch head with the central one:
To remove file change from last commit:
to revert the file to the state before the last commit, do:
git checkout HEAD^ /path/to/file
to update the last commit with the reverted file, do:
git commit --amend
to push the updated commit to the repo, do:
git push -f
Really, consider using the preferred method mentioned before.
try this...
$file = $_POST['file']; //your data in base64 'data:image/png....';
$img = str_replace('data:image/png;base64,', '', $file);
file_put_contents('img/imag.png', base64_decode($img));
I created the below function to generate random number of fix length:
function getRandomNum(length) {
var randomNum =
(Math.pow(10,length).toString().slice(length-1) +
Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
return randomNum;
}
This will basically add 0's at the beginning to make the length of the number as required.
As Already mentioned we have two ways!
And it's done interactively! And take effect immediately!
CTRL + A followed by : And we type scrollback 1000000
And hit ENTER
You detach from the screen and come back! It will be always the same.
You open another new screen! And the value is reset again to default! So it's not a global setting!
Which is done by adding defscrollback 1000000
to .screenrc
(in home)
defscrollback
and not scrollback
(def stand for default)
What you need to know is if the file is not created ! You create it !
> cd ~ && vim .screenrc
And you add defscrollback 1000000
to it!
Or in one command
> echo "defscrollback 1000000" >> .screenrc
(if not created already)
When you add the default to .screenrc
! The already running screen at re-attach will not take effect! The .screenrc
run at the screen creation! And it make sense! Just as with a normal console and shell launch!
And all the new created screens will have the set value!
To check type CTRL + A followed by i
And The result will be as
Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)
Note too that when you change it interactively! The effect is immediate and take over the default value!
CTRL+ A followed by ESC (to enter the copy mode).
Then navigate with Up,Down or PgUp PgDown
And ESC again to quit that mode.
(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)
Now the buffer is bigger!
And that's sum it up for the important details!
You can use Will Dean's suggestion [
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[])
is really some_function(string *parameter)
.
There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using
statements and has to be fully qualified.
Consider:
namespace MyNamespace
{
using System;
using MyAlias = System.DateTime;
class MyClass
{
}
}
versus:
using System;
namespace MyNamespace
{
using MyAlias = DateTime;
class MyClass
{
}
}
This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):
using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;
With using
statements inside the namespace, it suddenly becomes:
using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;
Not pretty.
You don't.
Firstly, your question is ambiguous - do you mean the format in which it is displayed to the user, or the format in which it is transmitted to the web server?
If you mean the format in which it is displayed to the user, then this is down to the end-user interface, not anything you specify in the HTML. Usually, I would expect it to be based on the date format that it is set in the operating system locale settings. It makes no sense to try to override it with your own preferred format, as the format it displays in is (generally speaking) the correct one for the user's locale and the format that the user is used to writing/understanding dates in.
If you mean the format in which it's transmitted to the server, you're trying to fix the wrong problem. What you need to do is program the server-side code to accept dates in yyyy-mm-dd format.
Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value
<select name="gender">
<option value="default">Select </option>
<option value="male"> Male </option>
<option value="female"> Female </option>
</select>
OR
<select name="gender">
<option value="male" selected="selected"> Male </option>
<option value="female"> Female </option>
</select>
When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.
Most important thing, AVOID SQL INJECTIONS:
//....
$fname = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$email = mysql_real_escape_string($_POST['email']);
}
else
{
//die ('invalid email address');
// or whatever, a default value? $email = '';
}
$paswod = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';
$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
echo 'userid is already there';
}
else
{
$sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';
132
in digits (base 10) is 1000_0100
in bits (base 2) and Java stores int
in 32 bits:
0000_0000_0000_0000_0000_0000_1000_0100
Algorithm for int-to-byte is left-truncate; Algorithm for System.out.println
is two's-complement (Two's-complement is if leftmost bit is 1
, interpret as negative one's-complement (invert bits) minus-one.); Thus System.out.println(int-to-byte(
))
is:
0000_0000_0000_0000_0000_0000_1000_0100
) [)))] )1000_0100
[)))] )1000_0100
))))1000_0011
)))0111_1100
))Well, this should really be broken into 2 parts:
I'm not sure how you do it in Windows land, but in *nix land there are functions buried in the Bluez stack that let you receive notifications about when a new device appears, and send it the pairing code (clearly there have to be these functions: those are what the user interface use). Given sufficient time and experience I'm sure you could figure out how to write your own version of the Bluetooth Settings app that somehow:
All without having to pop up a user interface.
If you go ahead and write the code I'd LOVE to get my hands on it.
You do not need to create sub directory. Just create blob container and use file name like the variable filename as below code:
string filename = "document/tech/user-guide.pdf";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(ConnectionString);
CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(filename);
blob.StreamWriteSizeInBytes = 20 * 1024;
blob.UploadFromStream(fileStream); // fileStream is System.IO.Stream
Bash supports all sorts of wildcards and expansions.
Your exact case would be handled by brace expansion, like so:
$ rm -rf abc.log.2012-03-{14,27,28}
The above would expand to a single command with all three arguments, and be equivalent to typing:
$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28
It's important to note that this expansion is done by the shell, before rm
is even loaded.
You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = @"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!
As I stated in comment i would use a box layout for this.
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout());
JButton button = new JButton("Button1");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);
button = new JButton("Button2");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);
button = new JButton("Button3");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);
add(panel);
public static class UnixTime
{
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
public static DateTime UnixTimeToDateTime(double unixTimeStamp)
{
return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();
}
}
you can call UnixTime.UnixTimeToDateTime(double datetime))
Another DISTINCT
answer, but with multiple values:
SELECT DISTINCT `field1`, `field2`, `field3` FROM `some_table` WHERE `some_field` > 5000 ORDER BY `some_field`
This approach works well very till 2.3 And by adding hardwareaccelerated=true it even works from 3.0 to ICS One problem i am facing currently is upon second launch of media player application is getting crashed because i have not stopped playback and released Media player. As VideoSurfaceView object, which we get in onShowCustomView function from 3.0 OS, are specific to browser and not a VideoView object as in, till 2.3 OS How can i access it and stopPlayback and release resources?
I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
open dconf Editor and go to org > gnome > desktop > application > terminal and change gnome-terminal to terminator
In the top level of the IIS Manager (above Sites), you should see the Application Pools tree node. Right click on "Application Pools", choose "Add Application Pool".
Give it a name, choose .NET Framework 4.0 and either Integrated or Classic mode.
When you add or edit a web site, your new application pools will now show up in the list.
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
Many ways this can be achieved.
Simple approach should be taking Substring
of an input string.
var result = input.Substring(input.Length - 3);
Another approach using Regular Expression
to extract last 3 characters.
var result = Regex.Match(input,@"(.{3})\s*$");
Working Demo
Here is another, more general solution assuming you don't have a list of rows (maybe they don't fit in memory) or a copy of the headers (maybe the write_csv
function is generic):
def gen_rows():
yield OrderedDict(name='bob', age=25, weight=200)
yield OrderedDict(name='jim', age=31, weight=180)
def write_csv():
it = genrows()
first_row = it.next() # __next__ in py3
with open("people.csv", "w") as outfile:
wr = csv.DictWriter(outfile, fieldnames=list(first_row))
wr.writeheader()
wr.writerow(first_row)
wr.writerows(it)
Note: the OrderedDict constructor used here only preserves order in python >3.4. If order is important, use the OrderedDict([('name', 'bob'),('age',25)])
form.
There is one good answer for what a general purpose language like Haskell is good for: writing programs in general.
For what it is used for in practice, I've three approaches to establishing that:
Indicates that it is good for graphics, networking, systems programming, data structures, databases, development, text processing ...
And finally, my opinion on what it is really strong at:
I hope that gives you a sense on how broad your question is, if it is to be answered with any specificity.
I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.
First, you might need to edit your system's PATH
sudo vi /etc/paths
Add 2 following lines:
/opt/local/bin
/opt/local/sbin
Reboot your terminal
Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.
public void schedule(TimerTask task,long delay)
Schedules the specified task for execution after the specified delay.
you want:
public void schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
You can't use margin:auto;
on position:absolute;
elements, just remove it if you don't need it, however, if you do, you could use left:30%;
((100%-40%)/2) and media queries for the max and min values:
.container {
position: absolute;
top: 15px;
left: 30%;
z-index: 2;
width:40%;
height: 60px;
overflow: hidden;
background: #fff;
}
@media all and (min-width:960px) {
.container {
left: 50%;
margin-left:-480px;
width: 960px;
}
}
@media all and (max-width:600px) {
.container {
left: 50%;
margin-left:-300px;
width: 600px;
}
}
Use the zip function to decouple elements:
>>> inpt = [(1, u'abc'), (2, u'def')]
>>> unzipped = zip(*inpt)
>>> print unzipped
[(1, 2), (u'abc', u'def')]
>>> print list(unzipped[0])
[1, 2]
Edit (@BradSolomon):
The above works for Python 2.x, where zip
returns a list.
In Python 3.x, zip
returns an iterator and the following is equivalent to the above:
>>> print(list(list(zip(*inpt))[0]))
[1, 2]
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
For bash (OSX) ping google.com -c 1
(incase search brought you here)
Look at the START command, you can do this:
START rest-of-your-program-name
For instance, this batch-file will wait until notepad exits:
@echo off
notepad c:\test.txt
However, this won't:
@echo off
start notepad c:\test.txt
#include"stdio.h"
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int i;
srand(time(&t));
for(i=1;i<=10;i++)
printf("%c\t",rand()%10);
getch();
}
I got this error this morning, I just did a fresh install of Fedora 14 and was trying to get my local projects back online. I was missing php-mysql, I installed it via yum and the error is now gone.
I don't know if it has an official name, but I call it the Right-Left Thingy(TM).
Start at the variable, then go right, and left, and right...and so on.
int* arr1[8];
arr1
is an array of 8 pointers to integers.
int (*arr2)[8];
arr2
is a pointer (the parenthesis block the right-left) to an array of 8 integers.
int *(arr3[8]);
arr3
is an array of 8 pointers to integers.
This should help you out with complex declarations.
I use the following method when sending a List<MySerializableObject>
via intent:
List<Thumbnail> thumbList = new ArrayList<>();
//Populate ...
Intent intent = new Intent(context, OtherClass.class);
intent.putExtra("ThumbArray", thumbList.toArray(new Thumbnail[0]));
//Send intent...
And retrieving it like so:
Thumbnail[] thumbArr = (Thumbnail[]) getIntent().getSerializableExtra("ThumbArray");
if (thumbArr != null) {
List<Thumbnail> thumbList = Arrays.asList(thumbArr);
}
Try setting: "AllowOverride All".
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
I use ng-class directive with $location to achieve it.
<ul class="nav">
<li data-ng-class="{active: ($location.path() == '/') }">
<a href="#/">Carpeta Amarilla</a>
</li>
<li class="dropdown" data-ng-class="{active: ($location.path() == '/auditoria' || $location.path() == '/auditoria/todos') }">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
Auditoria
<b class="caret"></b>
</a>
<ul class="dropdown-menu pull-right">
<li data-ng-class="{active: ($location.path() == '/auditoria') }">
<a href="#/auditoria">Por Legajo</a>
</li>
<li data-ng-class="{active: ($location.path() == '/auditoria/todos') }">
<a href="#/auditoria/todos">General</a>
</li>
</ul>
</li>
</ul>
It requires the navbar to be inside a main Controller with access to $location service like this:
bajasApp.controller('MenuCntl', ['$scope','$route', '$routeParams', '$location',
function MenuCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}]);
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
yes you will have to extend JPanel
and override the paintcomponent(Graphics g)
function to do so.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
You can use other component which allows to add image as icon directly e.g. JLabel
if you want.
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?
You could use the ones on CodePlex or http://www.enterprisedt.com/general/press/20060818.html
I got this error today because the "Source" is missing the ApacheJmeter.jar. I downloaded it again from "Binaries" and everything works as expected.
By using document.getElementById()
function you don't have to pass #
before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo: JSFiddle
Example outputs *.csv files in directory recursive searching Subdirectories using Files.find() from java.nio:
String path = "C:/Daten/ibiss/ferret/";
logger.debug("Path:" + path);
try (Stream<Path> fileList = Files.find(Paths.get(path), Integer.MAX_VALUE,
(filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.toString().endsWith("csv"))) {
List<String> someThingNew = fileList.sorted().map(String::valueOf).collect(Collectors.toList());
for (String t : someThingNew) {
t.toString();
logger.debug("Filename:" + t);
}
}
Posting this example, as I had trouble understanding howto pass the filename parameter in the #1 example given by Bryan, using foreach on Stream-result -
Hope this helps.
i had the same problem today at work.
npm rebuild node-sass
done the job for me
Windows + Apache 2.4, for example:
uncomment ssl_module in your httpd.conf
file.
LoadModule ssl_module modules/mod_ssl.so
listen 443 port just like 80 port in your httpd.conf
file.
Listen 80
Listen 443
uncomment Include Virtual hosts in your httpd.conf
file.
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
add VirtualHost in your conf/extra/httpd-vhosts.conf
<VirtualHost _default_:443>
DocumentRoot "D:/www" #your site directory path
ServerName localhost
#ServerAlias localhost.com localhost2.com
SSLEngine on
SSLCertificateFile "${SRVROOT}/conf/ssl/server.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/server.key"
<Directory "D:/www">
Options -Indexes +FollowSymLinks +ExecCGI
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
only the port number 443
and SSL......
lines are different from normal http config.
save you config file and restart apache service. then you can visit https://localhost/
The web browser will warn you that it's unsafe at the first time, just choose go on.
Here is the solution
import boto3
s3=boto3.resource('s3')
BUCKET_NAME = 'Your S3 Bucket Name'
allFiles = s3.Bucket(BUCKET_NAME).objects.all()
for file in allFiles:
print(file.key)
Above solutions do not appropriately round numbers. I use:
double dp(double val, int places){
double mod = pow(10.0, places);
return ((val * mod).round().toDouble() / mod);
}
A simple way of creating an array of random integers is:
matrix = np.random.randint(maxVal, size=(rows, columns))
The following outputs a 2 by 3 matrix of random integers from 0 to 10:
a = np.random.randint(10, size=(2,3))
I tried the answer but it didn't worked for me. This is what i ended up doing:
Create a new controller DefaultController. In index action, i wrote one line redirect:
return Redirect("~/Default.aspx")
In RouteConfig.cs, change controller="Default" for the route.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
No need too these. Just simply add div id to href of a < a > tag
<li><a id = "aboutlink" href="#about">auck</a></li>
Just like that.
Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr()
.
import os
class Log(object):
def __init__(self):
self.os = os.name
def __getattr__(self, name):
""" look for a 'save' attribute, or just
return whatever attribute was specified """
if name == 'save':
try:
# try to dynamically return a save
# method appropriate for the user's system
return getattr(self, self.os)
except:
# bail and try to return
# a default save method
return getattr(self, '_save')
else:
return getattr(self, name)
# each of these methods could have save logic specific to
# the system on which the script is executed
def posix(self): print 'saving on a posix machine'
def nt(self): print 'saving on an nt machine'
def os2(self): print 'saving on an os2 machine'
def ce(self): print 'saving on a ce machine'
def java(self): print 'saving on a java machine'
def riscos(self): print 'saving on a riscos machine'
def _save(self): print 'saving on an unknown operating system'
def which_os(self): print os.name
Now let's use this class in an example:
logger = Log()
# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along
# somewhere else as 1st class:
save_func()
# or you can just call it directly:
logger.save()
# other attributes will hit the else
# statement and still work as expected
logger.which_os()
The difference is more prominent when you are passing a big struct/class.
struct MyData {
int a,b,c,d,e,f,g,h;
long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);
when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.
in both cases, the original data cannot be modified from inside the function.
EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.
Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.
At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ
In Python, any immutable object (such as an integer, boolean, string, tuple) is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.
This is why Python requires us to use immutable datatypes for the keys in a dictionary.
Syntax refers to the structure of a language, tracing its etymology to how things are put together.
For example you might require the code to be put together by declaring a type then a name and then a semicolon, to be syntactically correct.
Type token;
On the other hand, the semantics is about meaning. A compiler or interpreter could complain about syntax errors. Your co-workers will complain about semantics.
You can find the codes in the DB2 Information Center. Here's a definition of the -302
from the z/OS Information Center:
THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE
On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW
, if it's negative, you'll look for SQLxxxxN
, where xxxx is the code you're looking up.
If you want to show time on textview then better use Chronometer or TextClock
Using Chronometer:This was added in API 1. It has lot of option to customize it.
Your xml
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
Your activity
Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.
Your xml
<TextClock
android:id="@+id/textClock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:format12Hour="hh:mm:ss a"
android:gravity="center_horizontal"
android:textColor="#d41709"
android:textSize="44sp"
android:textStyle="bold" />
Thats it, you are done.
You can use any of these two widgets. This will make your life easy.
When I go to the control panel of my webhost, open up phpMyAdmin, and click on "Show MySQL runtime information", I get:
This MySQL server has been running for 53 days, 15 hours, 28 minutes and 53 seconds. It started up on Oct 24, 2008 at 04:03 AM.
Query statistics: Since its startup, 3,444,378,344 queries have been sent to the server.
Total 3,444 M
per hour 2.68 M
per minute 44.59 k
per second 743.13
That's an average of 743 mySQL queries every single second for the past 53 days!
I don't know about you, but to me that's fast! Very fast!!
Try this On window load submit your form.
window.onload = function(){
document.forms['member_signup'].submit();
}
I am surprised why everyone recommends to pass a comparator function to sort()
, that makes sorting really slow!
To sort numbers, just create any TypedArray:
var numArray = new Float64Array([140000, 104, 99]);
numArray = numArray.sort();
console.log(numArray)
_x000D_
Try this
$('textarea').trigger('change');
$("textarea").bind('cut paste', function(e) { });
Funny you mention that, I did a blog post on this very subject.
See Oracle vs MySQL vs SQL Server: Aggregation vs Joins
Short answer: you have to test it and individual databases vary a lot.
You can use: if(-e $base_path)
Fast canvas resample with good quality: http://jsfiddle.net/9g9Nv/442/
Update: version 2.0 (faster, web workers + transferable objects) - https://github.com/viliusle/Hermite-resize
/**
* Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
*
* @param {HtmlElement} canvas
* @param {int} width
* @param {int} height
* @param {boolean} resize_canvas if true, canvas will be resized. Optional.
*/
function resample_single(canvas, width, height, resize_canvas) {
var width_source = canvas.width;
var height_source = canvas.height;
width = Math.round(width);
height = Math.round(height);
var ratio_w = width_source / width;
var ratio_h = height_source / height;
var ratio_w_half = Math.ceil(ratio_w / 2);
var ratio_h_half = Math.ceil(ratio_h / 2);
var ctx = canvas.getContext("2d");
var img = ctx.getImageData(0, 0, width_source, height_source);
var img2 = ctx.createImageData(width, height);
var data = img.data;
var data2 = img2.data;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
var x2 = (i + j * width) * 4;
var weight = 0;
var weights = 0;
var weights_alpha = 0;
var gx_r = 0;
var gx_g = 0;
var gx_b = 0;
var gx_a = 0;
var center_y = (j + 0.5) * ratio_h;
var yy_start = Math.floor(j * ratio_h);
var yy_stop = Math.ceil((j + 1) * ratio_h);
for (var yy = yy_start; yy < yy_stop; yy++) {
var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
var center_x = (i + 0.5) * ratio_w;
var w0 = dy * dy; //pre-calc part of w
var xx_start = Math.floor(i * ratio_w);
var xx_stop = Math.ceil((i + 1) * ratio_w);
for (var xx = xx_start; xx < xx_stop; xx++) {
var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
var w = Math.sqrt(w0 + dx * dx);
if (w >= 1) {
//pixel too far
continue;
}
//hermite filter
weight = 2 * w * w * w - 3 * w * w + 1;
var pos_x = 4 * (xx + yy * width_source);
//alpha
gx_a += weight * data[pos_x + 3];
weights_alpha += weight;
//colors
if (data[pos_x + 3] < 255)
weight = weight * data[pos_x + 3] / 250;
gx_r += weight * data[pos_x];
gx_g += weight * data[pos_x + 1];
gx_b += weight * data[pos_x + 2];
weights += weight;
}
}
data2[x2] = gx_r / weights;
data2[x2 + 1] = gx_g / weights;
data2[x2 + 2] = gx_b / weights;
data2[x2 + 3] = gx_a / weights_alpha;
}
}
//clear and resize canvas
if (resize_canvas === true) {
canvas.width = width;
canvas.height = height;
} else {
ctx.clearRect(0, 0, width_source, height_source);
}
//draw
ctx.putImageData(img2, 0, 0);
}
This kind of worked for me. Though FAB doesn't float independently, but now it isn't getting pushed down.
Observe the weights given inside the LinearLayout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/andsanddkasd">
<android.support.v7.widget.RecyclerView
android:id="@+id/sharedResourcesRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="bottom|right"
android:src="@android:drawable/ic_input_add"
android:layout_weight="1"/>
</LinearLayout>
Hope this helps :)
You can use built-in nodejs web server.
Add file server.js
for example and put following code:
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
});
And after start server from console with command node server.js
. Your index.html page will be available on URL http://localhost:8080
Try
CAST(STR(DATEPART(year, DATE))+'-'+ STR(DATEPART(month, DATE)) +'-'+ STR(DATEPART(day, DATE)) AS DATETIME)
Now , Facebook need SSL
-> Important added S, https -> https://graph.facebook.com/userId/?fields=picture&type=large
Works In June / 2014
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
It seems like you are expecting int
and unsigned int
to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.
Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:
unsigned int x = 65529;
int y = (short) x; // If short is a 16-bit integer.
or alternatively:
unsigned int x = 65529;
int y = (int16_t) x; // This is defined in <stdint.h>
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
Implement in this way
String i="hi";
Intent i = new Intent(this, ActivityTwo.class);
//Create the bundle
Bundle b = new Bundle();
//Add your data to bundle
b.putString(“stuff”, i);
i.putExtras(b);
startActivity(i);
Begin that second activity
, inside this class
to utilize the Bundle values use this code
Bundle bundle = getIntent().getExtras();
String text= bundle.getString("stuff");
Just include this line
android:selectAllOnFocus="false"
in the XML segment corresponding to the EditText layout.
Make sure you have selected your mysql storage engine as Innodb and not MYISAM as Innodb storage engine supports foreign keys in Mysql.
Steps to create foreign keys in phpmyadmin:
INDEX
for the column you want to use as foreign key.UPDATE CASCADE specifies that the column will be updated when the referenced column is updated,
DELETE CASCADE specified rows will be deleted when the referenced rows are deleted.
Alternatively, you can also trigger sql query for the same
ALTER TABLE table_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (foreign_key_name)
REFERENCES target_table(target_key_name);
On Mac OS X using the python.org installer as you apparently have, you need to invoke Python 3 with python3
, not python
. That is currently reserved for Python 2 versions. You could also use python3.2
to specifically invoke that version.
$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ cd /Library/Frameworks/Python.framework/Versions/3.2/bin/
$ ls -l
total 384
lrwxr-xr-x 1 root admin 8 Apr 28 15:51 2to3@ -> 2to3-3.2
-rwxrwxr-x 1 root admin 140 Feb 20 11:14 2to3-3.2*
lrwxr-xr-x 1 root admin 7 Apr 28 15:51 idle3@ -> idle3.2
-rwxrwxr-x 1 root admin 138 Feb 20 11:14 idle3.2*
lrwxr-xr-x 1 root admin 8 Apr 28 15:51 pydoc3@ -> pydoc3.2
-rwxrwxr-x 1 root admin 123 Feb 20 11:14 pydoc3.2*
-rwxrwxr-x 2 root admin 25624 Feb 20 11:14 python3*
lrwxr-xr-x 1 root admin 12 Apr 28 15:51 python3-32@ -> python3.2-32
lrwxr-xr-x 1 root admin 16 Apr 28 15:51 python3-config@ -> python3.2-config
-rwxrwxr-x 2 root admin 25624 Feb 20 11:14 python3.2*
-rwxrwxr-x 1 root admin 13964 Feb 20 11:14 python3.2-32*
lrwxr-xr-x 1 root admin 17 Apr 28 15:51 python3.2-config@ -> python3.2m-config
-rwxrwxr-x 1 root admin 25784 Feb 20 11:14 python3.2m*
-rwxrwxr-x 1 root admin 1865 Feb 20 11:14 python3.2m-config*
lrwxr-xr-x 1 root admin 10 Apr 28 15:51 pythonw3@ -> pythonw3.2
lrwxr-xr-x 1 root admin 13 Apr 28 15:51 pythonw3-32@ -> pythonw3.2-32
-rwxrwxr-x 1 root admin 25624 Feb 20 11:14 pythonw3.2*
-rwxrwxr-x 1 root admin 13964 Feb 20 11:14 pythonw3.2-32*
If you also installed a Python 2 from python.org, it would have a similar framework bin directory with no overlapping file names (except for 2to3).
$ open /Applications/Python\ 2.7/Update\ Shell\ Profile.command
$ sh -l
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.2/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ cd /Library/Frameworks/Python.framework/Versions/2.7/bin
$ ls -l
total 288
-rwxrwxr-x 1 root admin 150 Jul 3 2010 2to3*
lrwxr-x--- 1 root admin 7 Nov 8 23:14 idle@ -> idle2.7
-rwxrwxr-x 1 root admin 138 Jul 3 2010 idle2.7*
lrwxr-x--- 1 root admin 8 Nov 8 23:14 pydoc@ -> pydoc2.7
-rwxrwxr-x 1 root admin 123 Jul 3 2010 pydoc2.7*
lrwxr-x--- 1 root admin 9 Nov 8 23:14 python@ -> python2.7
lrwxr-x--- 1 root admin 16 Nov 8 23:14 python-config@ -> python2.7-config
-rwxrwxr-x 1 root admin 33764 Jul 3 2010 python2.7*
-rwxrwxr-x 1 root admin 1663 Jul 3 2010 python2.7-config*
lrwxr-x--- 1 root admin 10 Nov 8 23:14 pythonw@ -> pythonw2.7
-rwxrwxr-x 1 root admin 33764 Jul 3 2010 pythonw2.7*
lrwxr-x--- 1 root admin 11 Nov 8 23:14 smtpd.py@ -> smtpd2.7.py
-rwxrwxr-x 1 root admin 18272 Jul 3 2010 smtpd2.7.py*
Bottom line at the top: Get newer programs or get an older computer.
The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.
<style>
#frame{
position: fixed;
top: 5%;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 6px #B2B2B2;
display: inline-block;
padding: 8px 8px;
width: 98%;
height: 92%;
display: none;
z-index: 1000;
}
#map{
position: fixed;
display: inline-block;
width: 99%;
height: 93%;
display: none;
z-index: 1000;
}
#loading{
position: fixed;
top: 50%;
left: 50%;
opacity: 1!important;
margin-top: -100px;
margin-left: -150px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 6px #B2B2B2;
display: inline-block;
padding: 8px 8px;
max-width: 66%;
display: none;
color: #000;
}
#mytitle{
color: #FFF;
background-image: linear-gradient(to bottom,#d67631,#d67631);
// border-color: rgba(47, 164, 35, 1);
width: 100%;
cursor: move;
}
#closex{
display: block;
float:right;
position:relative;
top:-10px;
right: -10px;
height: 20px;
cursor: pointer;
}
.pointer{
cursor: pointer !important;
}
</style>
<div id="loading">
<i class="fa fa-circle-o-notch fa-spin fa-2x"></i>
Loading...
</div>
<div id="frame">
<div id="headerx"></div>
<div id="map" >
</div>
</div>
<?php
$url = Yii::app()->baseUrl . '/reports/reports/transponderdetails';
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function clode() {
$('#frame').hide();
$('#frame').html();
}
function track(id) {
$('#loading').show();
$('#loading').parent().css("opacity", '0.7');
$.ajax({
type: "POST",
url: '<?php echo $url; ?>',
data: {'id': id},
success: function(data) {
$('#frame').show();
$('#headerx').html(data);
$('#loading').parents().css("opacity", '1');
$('#loading').hide();
var thelat = parseFloat($('#lat').text());
var long = parseFloat($('#long').text());
$('#map').show();
var lat = thelat;
var lng = long;
var orlat=thelat;
var orlong=long;
//Intialize the Path Array
var path = new google.maps.MVCArray();
var service = new google.maps.DirectionsService();
var myLatLng = new google.maps.LatLng(lat, lng), myOptions = {zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var poly = new google.maps.Polyline({map: map, strokeColor: '#4986E7'});
var marker = new google.maps.Marker({position: myLatLng, map: map});
function initialize() {
marker.setMap(map);
movepointer(map, marker);
var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);
}
function movepointer(map, marker) {
marker.setPosition(new google.maps.LatLng(lat, lng));
map.panTo(new google.maps.LatLng(lat, lng));
var src = myLatLng;//start point
var des = myLatLng;// should be the destination
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
;
// function()
setInterval(function() {
lat = Math.random() + orlat;
lng = Math.random() + orlong;
console.log(lat + "-" + lng);
myLatLng = new google.maps.LatLng(lat, lng);
movepointer(map, marker);
}, 1000);
},
error: function() {
$('#frame').html('Sorry, no details found');
},
});
return false;
}
$(function() {
$("#frame").draggable();
});
</script>
We can use this method:
CONVERT(VARCHAR(10), GETDATE(), 120)
Last parameter changes the format to only to get time or date in specific formats.
There is also a way to add an attribute to an XmlNode
object, that can be useful in some cases.
I found this other method on msdn.microsoft.com.
using System.Xml;
[...]
//Assuming you have an XmlNode called node
XmlNode node;
[...]
//Get the document object
XmlDocument doc = node.OwnerDocument;
//Create a new attribute
XmlAttribute attr = doc.CreateAttribute("attributeName");
attr.Value = "valueOfTheAttribute";
//Add the attribute to the node
node.Attributes.SetNamedItem(attr);
[...]
It's indeed a very bad design, let alone singleton by itself is bad design.
However, if you really do need to delay execution, here's what you may do:
BackgroundWorker barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
{
Thread.Sleep(TimeSpan.FromSeconds(1));
bar();
};
barInvoker.RunWorkerAsync();
This will, however, invoke bar()
on a separate thread. If you need to call bar()
in the original thread you might need to move bar()
invocation to RunWorkerCompleted
handler or do a bit of hacking with SynchronizationContext
.
You can do it in multiple ways:
1. Using greater
as comparison function :
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<< " ";
}
return 0;
}
2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :
int main()
{
priority_queue<int>pq2;
pq2.push(-1); //for +1
pq2.push(-2); //for +2
pq2.push(-3); //for +3
pq2.push(4); //for -4
while(!pq2.empty())
{
int r = pq2.top();
pq2.pop();
cout<<-r<<" ";
}
return 0;
}
3. Using custom structure or class :
struct compare
{
bool operator()(const int & a, const int & b)
{
return a>b;
}
};
int main()
{
priority_queue<int,vector<int>,compare> pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<<" ";
}
return 0;
}
4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.
struct people
{
int age,salary;
};
struct compare{
bool operator()(const people & a, const people & b)
{
if(a.salary==b.salary)
{
return a.age>b.age;
}
else
{
return a.salary>b.salary;
}
}
};
int main()
{
priority_queue<people,vector<people>,compare> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Same result can be obtained by operator overloading :
struct people
{
int age,salary;
bool operator< (const people & p)const
{
if(salary==p.salary)
{
return age>p.age;
}
else
{
return salary>p.salary;
}
}};
In main function :
priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
You have to log the responseText:
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
}
})
.done(
function (data) {
//your code
}
)
.fail(function (data) {
console.log( "Ajax failed: " + data['responseText'] );
})
You should implement a Comparator<Map<String, String>>
which basically extracts the "name" value from the two maps it's passed, and compares them.
Then use Collections.sort(list, comparator)
.
Are you sure a Map<String, String>
is really the best element type for your list though? Perhaps you should have another class which contains a Map<String, String>
but also has a getName()
method?
Once I met Sam Hartman, he is a famous Debian developer since 2000, and blind. On this interview he talks about accessibility for a Linux user. He uses Debian, and gnome-orca as screen reader, it works with Gnome, and "does a relatively good job of speaking Iceweasel/Firefox and Libreoffice".
Specifically speaking about programming he says:
While [gnome-orca] does speak gnome-terminal, it’s not really good enough at speaking terminal programs that I am comfortable using it. So, I run Emacs with the Emacspeak package. Within that, I run the Emacs terminal emulator, and within that, I tend to run Screen. For added fun, I often run additional instances of Emacs within the inner screens.
If you still get the exception in the server startup after changing listen port, you should try changing Pointbase server port and debug port in setDomainEnv.cmd
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
In addition to cozeJ4's answer, here's updated version of that gist
Original one lacked imports and contained some errors. This one is ready to use.
Here is what I used to get today's date with time set to 00:00:00
:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date today = new Date();
Date todayWithZeroTime = formatter.parse(formatter.format(today));
Try data = new int[] {10,20,30,40,50,60,71,80,90,91 };
In case you want to take care the edge conditions carefully (compute mean only from available elements at edges), the following function will do the trick.
import numpy as np
def running_mean(x, N):
out = np.zeros_like(x, dtype=np.float64)
dim_len = x.shape[0]
for i in range(dim_len):
if N%2 == 0:
a, b = i - (N-1)//2, i + (N-1)//2 + 2
else:
a, b = i - (N-1)//2, i + (N-1)//2 + 1
#cap indices to min and max indices
a = max(0, a)
b = min(dim_len, b)
out[i] = np.mean(x[a:b])
return out
>>> running_mean(np.array([1,2,3,4]), 2)
array([1.5, 2.5, 3.5, 4. ])
>>> running_mean(np.array([1,2,3,4]), 3)
array([1.5, 2. , 3. , 3.5])
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
Neither!
If you're asking; "what would a website visitor rather type, htm or html" - it's much better to give them a nice descriptive URL with no extension. If they get used to going to yoursite/contact.html and you change it to yoursite/contact.php you've broken that link. If you use yoursite/contact/ then there's no problem when you switch technology.
Why not use properly formulated geospatial queries???
Here is the SQL server reference page on the STContains geospatial function:
or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:
DECLARE @CurrentLocation geography;
SET @CurrentLocation = geography::Point(12.822222, 80.222222, 4326)
SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km
There should be similar functionality for almost any database out there.
If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using
Padding is an operation to increase the size of the input data. In case of 1-dimensional data you just append/prepend the array with a constant, in 2-dim you surround matrix with these constants. In n-dim you surround your n-dim hypercube with the constant. In most of the cases this constant is zero and it is called zero-padding.
Here is an example of zero-padding with p=1
applied to 2-d tensor:
You can use arbitrary padding for your kernel but some of the padding values are used more frequently than others they are:
k
k
, this padding is equal to k - 1
.To use arbitrary padding in TF, you can use tf.pad()
Upload files using AJAX in ASP.Net MVC
Things have changed since HTML5
JavaScript
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
Controller
public JsonResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
}
return Json("Uploaded " + Request.Files.Count + " files");
}
EDIT : The HTML
<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="submit" value="Upload file" />
</form>
This is something I always wanted, especially while setting up test fixtures. Finally, I decided to write a simple fluent builder of my own that could build any Map implementation - https://gist.github.com/samshu/b471f5a2925fa9d9b718795d8bbdfe42#file-mapbuilder-java
/**
* @param mapClass Any {@link Map} implementation type. e.g., HashMap.class
*/
public static <K, V> MapBuilder<K, V> builder(@SuppressWarnings("rawtypes") Class<? extends Map> mapClass)
throws InstantiationException,
IllegalAccessException {
return new MapBuilder<K, V>(mapClass);
}
public MapBuilder<K, V> put(K key, V value) {
map.put(key, value);
return this;
}
public Map<K, V> build() {
return map;
}
TLDR: simple defined variables (without var
, let
, const
) could be deleted with delete
. If you use var
, let
, const
- they could not be deleted neither with delete
nor with Reflect.deleteProperty
.
Chrome 55:
simpleVar = "1";
"1"
delete simpleVar;
true
simpleVar;
VM439:1 Uncaught ReferenceError: simpleVar is not defined
at <anonymous>:1:1
(anonymous) @ VM439:1
var varVar = "1";
undefined
delete varVar;
false
varVar;
"1"
let letVar = "1";
undefined
delete letVar;
true
letVar;
"1"
const constVar="1";
undefined
delete constVar;
true
constVar;
"1"
Reflect.deleteProperty (window, "constVar");
true
constVar;
"1"
Reflect.deleteProperty (window, "varVar");
false
varVar;
"1"
Reflect.deleteProperty (window, "letVar");
true
letVar;
"1"
FF Nightly 53.0a1 shows same behaviour.
FOR MAC USERS if you are working with open cv
import cv2
cv2.imwrite('path_to_folder/image.jpg',image)
Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.
Also in
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
this.mainInput
doesn't refer the input since mainInput is an id
, you need to specify a ref to the input
<input
ref={(ref) => this.mainInput= ref}
onChange={this.onHandleChange}
placeholder="Get current weather..."
value={this.state.city}
type="text"
/>
In you current state the best way is to clear the state to clear the input value
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({city: ""});
}
However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled
<input
id="mainInput"
onChange={this.onHandleChange}
placeholder="Get current weather..."
type="text"
/>
and update the value in state onChange
and onSubmit
clear the input using ref
onHandleChange(e) {
this.setState({
city: e.target.value
});
}
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.
I get it resolved appending datetime as an random number:
$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
console.log('your get response is new!!!');
});
I recently had to resolve this issue and here's what I did :
First of all, this solution is around tuning Apache server.
Second main think is that there's a bug in the IE9 which means that the meta tag will not work, instead of this solution try this
uncomment/or add the following line
LoadModule headers_module modules/mod_headers.so
add the following lines
<IfModule headers_module>
Header set X-UA-Compatible: IE=EmulateIE8
</IfModule>
save/restart your Apache server,
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
Yet another method is using the LOOP instruction:
mov cx, 3
myloop:
; Your loop content
loop myloop
The loop instruction automatically decrements cx, and only jumps if cx != 0. There are also LOOPE, and LOOPNE variants, if you want to do some additional check for your loop to break out early.
If you want to modify cx during your loop, make sure to push it onto the stack before the loop content, and pop it off after:
mov cx, 3
myloop:
push cx
; Your loop content
pop cx
loop myloop
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
I prefer using a separate file for ie rules, as described earlier.
<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->
And inside it you can set up rules for different versions of ie using this:
.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */
I found a much easier way, which allows you to still use the built in sorting/paging of the standard gridview...
create 2 labels. set them to be visible = false. I called mine lblSort1 and lblSortDirection1
then code 2 simple events... the page sorting, which writes to the text of the invisible labels, and the page index changing, which uses them...
Private Sub gridview_Sorting(sender As Object, e As GridViewSortEventArgs) Handles gridview.Sorting
lblSort1.Text = e.SortExpression
lblSortDirection1.Text = e.SortDirection
End Sub
Private Sub gridview_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gridview.PageIndexChanging
gridview.Sort(lblSort1.Text, CInt(lblSortDirection1.Text))
End Sub
this is a little sloppier than using global variables, but I've found with asp especially that global vars are, well, unreliable...
None of the listed solutions in this thread worked for me. I started getting this error after I made some changes to the connection strings section of the web.config file. (My app connects to multiple databases.) I carefully examined what changes I had made are realized I had removed the tag at the top of my list. I restored the tag at the top of my list of connection strings and the problem went away immediately. This site that was getting the error is a application that resides below the main site (https://www.domain.org/MySite). This might not fix the problem for everyone, but it did resolve the problem for me.
You may try this:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12345");
System.out.println(toPrecision(a, 2));
}
private static BigDecimal toPrecision(BigDecimal dec, int precision) {
String plain = dec.movePointRight(precision).toPlainString();
return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}
OUTPUT:
10.12
Sliding from the right:
$('#example').animate({width:'toggle'},350);
Sliding to the left:
$('#example').toggle({ direction: "left" }, 1000);
I solved it by myself.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
In this case both strconv
and fmt.Sprintf
do the same job but using the strconv
package's Itoa
function is the best choice, because fmt.Sprintf
allocate one more object during conversion.
check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530
see https://play.golang.org/p/hlaz_rMa0D for example.