You should not calculate speed from position change per time. GPS may have inaccurate positions, but it has accurate speed (above 5km/h). So use the speed from GPS location stamp. And further you should not do that with course, although it works most of the times.
GPS positions, as delivered, are already Kalman filtered, you probably cannot improve, in postprocessing usually you have not the same information like the GPS chip.
You can smooth it, but this also introduces errors.
Just make sure that your remove the positions when the device stands still, this removes jumping positions, that some devices/Configurations do not remove.
$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
$img = file_get_contents($file);
echo $img;
This is works for me! I have test it on code igniter. if i use readfile, the image won't display. Sometimes only display jpg, sometimes only big file. But after i changed it to "file_get_contents" , I get the flavour, and works!! this is the screenshoot: Screenshot of "secure image" from database
In my case the pod update didn't update the project somehow. So I had to do it by myself, adding the MBProgressHud to OtherLinkerFlags.
Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable
aListOfObjects.Sort((x, y) =>
{
int result = x.A.CompareTo(y.A);
return result != 0 ? result : x.B.CompareTo(y.B);
});
ArrayList<ArrayList<String>>
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).
To add the PPA run:
sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update
To install smartgit
(after adding the PPA) run:
sudo apt-get install smartgit
To install smartgithg
(after adding the PPA) run:
sudo apt-get install smartgithg
This should add a menu option for you
For more information, see Eugene San PPA.
This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release
just an fyi -- if you want to serialize your data to something easy to read and understand like JSON but with more compression and higher performance, you should check out messagepack.
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'name_of_your_table'
var video1;_x000D_
_x000D_
function onYouTubeIframeAPIReady(){_x000D_
player = new YT.Player("video1", {_x000D_
videoId: "id-number",_x000D_
width: 300,_x000D_
height: 200, _x000D_
playerVars: {_x000D_
"autoplay": 1, // and 0 means off_x000D_
"controls": 1,_x000D_
"showinfo": 0,_x000D_
"modestbranding": 0,_x000D_
"loop": 1,_x000D_
"fs": 0,_x000D_
"cc_load_policy": 0,_x000D_
"iv_load_policy": 3,_x000D_
},_x000D_
events: {_x000D_
'onReady': onPlayerReady_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
function onPlayerReady(event) {_x000D_
event.target.mute();_x000D_
event.target.setVolume(0); //this can be set from 0 to 100_x000D_
}
_x000D_
Remember that the sound will not be muted in IE and Safari.
the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.
next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.
in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.
i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (
If you by any chance wants to change the type of your collection you are better served with the Count()
extension. This way you don't have to refactor your code (to use Length
for instance).
Sample Code:
ListView list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object listItem = list.getItemAtPosition(position);
}
});
In the sample code above, the listItem
should contain the selected data for the textView
.
If running Windows 10:
path
If on older Windows:
Show Desktop.
Right Click My Computer shortcut in the desktop.
Click Properties.
You should see a section of control Panel - Control Panel\System and Security\System.
Click Advanced System Settings on the Left menu.
Click Enviornment Variables towards the bottom of the System Properties window.
Select PATH in the user variables list.
Append your PHP Path (C:\myfolder\php) to your PATH variable, separated from the already existing string by a semi colon.
Click OK
Open your "cmd"
Type PATH, press enter
Make sure that you see your PHP folder among the list.
That should work.
Note: Make sure that your PHP folder has the php.exe. It should have the file type CLI. If you do not have the php.exe, go ahead and check the installation guidelines at - http://www.php.net/manual/en/install.windows.manual.php - and download the installation file from there.
This line of yours:
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
Requires an @
symbol before %
like this:
<%@ page import="pageNumber.*, java.util.*, java.io.*" @%>
You can do it like this.
String to byte array
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
http://www.javadb.com/convert-string-to-byte-array
Byte array to String
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.
You can use:
ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));
I think I know what may cause this error.
In google chrome there is an in-built feature to prevent ddos attacks for google chrome extensions.
When ajax requests continuously return 500+ status errors, it starts to throttle the requests.
Hence it is possible to receive status 0 on following requests.
There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
If you set android:singleLine="true"
, automatically the button hides the keyboard¡
To sort the array by the value of the "title" key use:
uasort($myArray, function($a, $b) {
return strcmp($a['title'], $b['title']);
});
strcmp compare the strings.
uasort() maintains the array keys as they were defined.
URI (Uniform Resource Identifier) according to Wikipedia:
a string of characters used to identify a resource.
URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.
URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax
IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.
The metacharacter \b
is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.
There are three different positions that qualify as word boundaries:
Simply put: \b
allows you to perform a "whole words only" search using a regular expression in the form of \bword\b
. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".
In all flavors, the characters [a-zA-Z0-9_]
are word characters. These are also matched by the short-hand character class \w
. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.
\w
stands for "word character", usually [A-Za-z0-9_]
. Notice the inclusion of the underscore and digits.
\B
is the negated version of \b
. \B
matches at every position where \b
does not. Effectively, \B
matches at any position between two word characters as well as at any position between two non-word characters.
\W
is short for [^\w]
, the negated version of \w
.
The best practice is to explicitly list the columns:
Insert Into TableName(col1, col2,col2) Values(?, ?, ?)
Otherwise, your original insert will break if you add another column to your table.
A one liner but without String.format
for all RGB colors:
Color your_color = new Color(128,128,128);
String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);
You can add a .toUpperCase()
if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.
When you have ARGB colors you can use:
Color your_color = new Color(128,128,128,128);
String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);
A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format()
:
.col-xs-2{
background:#00f;
color:#FFF;
}
.col-half-offset{
margin-left:4.166666667%
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row" style="border: 1px solid red">
<div class="col-xs-4" id="p1">One</div>
<div class="col-xs-4 col-half-offset" id="p2">Two</div>
<div class="col-xs-4 col-half-offset" id="p3">Three</div>
<div>Test</div>
</div>
</div>
@ and @@ in modules also work differently when a class extends or includes that module.
So given
module A
@a = 'module'
@@a = 'module'
def get1
@a
end
def get2
@@a
end
def set1(a)
@a = a
end
def set2(a)
@@a = a
end
def self.set1(a)
@a = a
end
def self.set2(a)
@@a = a
end
end
Then you get the outputs below shown as comments
class X
extend A
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "module"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
class Y
include A
def doit
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "class"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
end
Y.new.doit
So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.
Perhaps a more pythonic way of doing so.
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, t, b, t, c)
plt.show()
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
Sub Addrisk()
Dim rActive As Range
Dim Count_Id_Column as long
Set rActive = ActiveCell
Application.ScreenUpdating = False
with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
for i = 1 to .range("A1045783").end(xlup).row
if 'something' = 'something' then
.range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
.range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
.range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
'change I to move on to next row (will get + 1 end of iteration)
i = i + 1
end if
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
next i
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates
End Sub
The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a>
tag:
<Tooltip title="Node.js" >
<a>
<FontAwesomeIcon icon={faNode} size="2x" />
</a>
</Tooltip>
Excel automatically does this whenever you have a vertical column of items. If you select the blank cell below (or above) the column and start typing, it does autocomplete based on everything in the column.
Edit : This option is deprecated : https://mochajs.org/#mochaopts
If you want to do it by still just running mocha
on the command line, but wanted to run the tests in a folder ./server-tests
instead of ./test
, create a file at ./test/mocha.opts
with just this in the file:
server-tests
If you wanted to run everything in that folder and subdirectories, put this into test/mocha.opts
server-tests
--recursive
mocha.opts
are the arguments passed in via the command line, so making the first line just the directory you want to change the tests too will redirect from ./test/
/* Didn't test it but this should work "out of the box" */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//you should edit this to fit your needs
builder.setTitle("Double Edit Text");
final EditText one = new EditText(this);
from.setHint("one");//optional
final EditText two = new EditText(this);
to.setHint("two");//optional
//in my example i use TYPE_CLASS_NUMBER for input only numbers
from.setInputType(InputType.TYPE_CLASS_NUMBER);
to.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout lay = new LinearLayout(this);
lay.setOrientation(LinearLayout.VERTICAL);
lay.addView(one);
lay.addView(two);
builder.setView(lay);
// Set up the buttons
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//get the two inputs
int i = Integer.parseInt(one.getText().toString());
int j = Integer.parseInt(two.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
You can't name a variable with capital letters or Ruby will asume its a constant and will want it to keep it's value constant, in which case changing it's value would be an error an "dynamic constant assignment error". With lower case should be fine
class MyClass
def mymethod
myconstant = "blah"
end
end
Do you mean search and replace a string in all files matched by grep?
perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`
Edit
Since this seems to be a fairly popular question thought I'd update.
Nowadays I mostly use ack-grep
as it's more user-friendly. So the above command would be:
perl -p -i -e 's/old/new/g' `ack -l searchpattern`
To handle whitespace in file names you can run:
ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'
you can do more with ack-grep
. Say you want to restrict the search to HTML files only:
ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'
And if white space is not an issue it's even shorter:
perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
To quote a quote:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
.data()
- jQuery Documentiation
Note that this (Frankly odd) limitation is only withheld to the use of .data()
.
The solution? Use .attr
instead.
Of course, several of you may feel uncomfortable with not using it's dedicated method. Consider the following scenario:
Common sense - Why would they change an already established attribute like that? Just imagine class
begin renamed to group and id
to identifier. The Internet would break.
And even then, Javascript itself has the ability to fix this - And of course, despite it's infamous incompatibility with HTML, REGEX (And a variety of similar methods) could rapidly rename your attributes to this new-mythical 'standard'.
TL;DR
alert($(targetField).attr("data-helptext"));
print('''first line \
second line''')
it will produce
first line second line
You need to set a few extra flags so that curl sends the data as JSON.
$ curl -H "Content-Type: application/json" \
-X POST \
-d '{"JSON": "HERE"}' \
http://localhost:3000/api/url
-H
: custom header, next argument is expected to be header-X
: custom HTTP verb, next argument is expected to be verb-d
: sends the next argument as data in an HTTP POST requestStarting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :
var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
$.ajax({
type: "POST",
url: requrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
I have not added the node class as its not particularly relevant or any test cases, leaving those as an excercise for the reader etc.
void postOrderTraversal(node* root)
{
if(root == NULL)
return;
stack<node*> st;
st.push(root);
//store most recent 'visited' node
node* prev=root;
while(st.size() > 0)
{
node* top = st.top();
if((top->left == NULL && top->right == NULL))
{
prev = top;
cerr<<top->val<<" ";
st.pop();
continue;
}
else
{
//we can check if we are going back up the tree if the current
//node has a left or right child that was previously outputted
if((top->left == prev) || (top->right== prev))
{
prev = top;
cerr<<top->val<<" ";
st.pop();
continue;
}
if(top->right != NULL)
st.push(top->right);
if(top->left != NULL)
st.push(top->left);
}
}
cerr<<endl;
}
running time O(n) - all nodes need to be visited AND space O(n) - for the stack, worst case tree is a single line linked list
Suppose you have TextBox with Id txtName
$("[id*=txtName]").on('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
alert('Tab Pressed');
}
});
This is a simple MaxHeap
implementation based on heapq
. Though it only works with numeric values.
import heapq
from typing import List
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, val):
heapq.heappush(self.data, -val)
def pop(self):
return -heapq.heappop(self.data)
Usage:
max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top()) # 5
But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles
You can check it by compiling,and running this small C++ program.
#include <iostream>
#include <conio.h>
#include <cstdlib>
int show;
int main()
{
while(true)
{
int show = getch();
std::cout << show;
}
getch(); // Just to keep the console open after program execution
}
This error began appearing for me when I added some new methods to my project. I knew that I was nowhere near the 65k method limit and did not want to enable multiDex support for my project if I could help it.
I resolved it by increasing the memory available to the :app:transformClassesForDexForDebug
task. I did this by specifying javaMaxHeapSize in gradle.build
.
gradle.build
android {
...
dexOptions {
javaMaxHeapSize "4g" //specify the heap size for the dex process
}
}
I tried this after having had no success with other common solutions to this problem:
clean
/app/build
and /build
directories from my projectError
Error:Execution failed for task > ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1
Note: increasing the memory available to the DEX task can cause performance problems on systems with lower memory - link.
drop procedure if exists doWhile;
DELIMITER //
CREATE PROCEDURE doWhile()
BEGIN
DECLARE i INT DEFAULT 2376921001;
WHILE (i <= 237692200) DO
INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
SET i = i+1;
END WHILE;
END;
//
CALL doWhile();
Since you have a DataTable already, and since I am assuming you are using SQL Server 2008 or better, this is probably the most straightforward way. First, in your database, create the following two objects:
CREATE TYPE dbo.MyDataTable -- you can be more speciifc here
AS TABLE
(
col1 INT,
col2 DATETIME
-- etc etc. The columns you have in your data table.
);
GO
CREATE PROCEDURE dbo.InsertMyDataTable
@dt AS dbo.MyDataTable READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.RealTable(column list) SELECT column list FROM @dt;
END
GO
Now in your C# code:
DataTable tvp = new DataTable();
// define / populate DataTable
using (connectionObject)
{
SqlCommand cmd = new SqlCommand("dbo.InsertMyDataTable", connectionObject);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
}
If you had given more specific details in your question, I would have given a more specific answer.
Or see cut_number
from the ggplot2
package, e.g.
das$wt_2 <- as.numeric(cut_number(das$wt,3))
Note that cut(...,3)
divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicate what cut_number
does by using quantile
appropriately, but it's a nice convenience function). On the other hand, Hmisc::cut2()
using the g=
argument does split by quantiles, so is more or less equivalent to ggplot2::cut_number
. I might have thought that something like cut_number
would have made its way into dplyr
by so far, but as far as I can tell it hasn't.
You could also use zip
import matplotlib.pyplot as plt
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
x, y = zip(*l)
plt.plot(x, y)
inline
and inline-block
elements are affected by whitespace in the HTML.
The simplest way to fix your problem is to remove the whitespace between </div>
and <div id="col2">
, see: http://jsfiddle.net/XCDsu/15/
There are other possible solutions, see: bikeshedding CSS3 property alternative?
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
You can put your values in ODCIVARCHAR2LIST and then join it as a regular table.
select tabl1.* FROM tabl1 LEFT JOIN
(select column_value txt from table(sys.ODCIVARCHAR2LIST
('%val1%','%val2%','%val3%')
)) Vals ON tabl1.column LIKE Vals.txt WHERE Vals.txt IS NOT NULL
My suggestion?
var arr = $.map($("#mydiv [id]"), function(n, i) {
return n.id;
});
you could also do this as:
var arr = $.map($("#mydiv span"), function(n, i) {
or
var arr = $.map($("#mydiv span[id]"), function(n, i) {
or even just:
var arr = $("#mydiv [id]").map(function() {
return this.id;
});
Lots of ways basically.
Personaly I think it's not the problem caused by type casting but a buffer overflow problem; it is this line
cvCopy(iplimagearray[i], xyz);
that I think will cause segment fault, I suggest that you confirm the array iplimagearray[i] have enough size of buffer to receive copyed data
It's odd how many incorrect answers has been given to asynchronous case! It can be simply shown that checking index does not provide expected behavior:
// INCORRECT
var list = [4000, 2000];
list.forEach(function(l, index) {
console.log(l + ' started ...');
setTimeout(function() {
console.log(index + ': ' + l);
}, l);
});
output:
4000 started
2000 started
1: 2000
0: 4000
If we check for index === array.length - 1
, callback will be called upon completion of first iteration, whilst first element is still pending!
To solve this problem without using external libraries such as async, I think your best bet is to save length of list and decrement if after each iteration. Since there's just one thread we're sure there no chance of race condition.
var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
console.log(l + ' started ...');
setTimeout(function() {
console.log(index + ': ' + l);
counter -= 1;
if ( counter === 0)
// call your callback here
}, l);
});
From the command line, it's simply:
printf "compute sha1" | openssl sha1
You can invoke the library like this:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
unsigned char ibuf[] = "compute sha1";
unsigned char obuf[20];
SHA1(ibuf, strlen(ibuf), obuf);
int i;
for (i = 0; i < 20; i++) {
printf("%02x ", obuf[i]);
}
printf("\n");
return 0;
}
UPDATE mytable SET column=LEFT(column, LEN(column)-5)
Removes the last 5 characters from the column (every row in mytable)
Simply do this
$get = explode('&', $_POST['seri']); // explode with and
foreach ($get as $key => $value) {
$need[substr($value, 0 , strpos($value, '='))] = substr(
$value,
strpos( $value, '=' ) + 1
);
}
// access your query param name=ddd&email=aaaaa&username=wwwww&password=wwww&password=eeee
var_dump($need['name']);
This is how you do CURL with sessions
//initial request with login data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
//another request preserving the session
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
I've seen this on ImpressPages
You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.
public static string GetFileProcessName(string filePath)
{
Process[] procs = Process.GetProcesses();
string fileName = Path.GetFileName(filePath);
foreach (Process proc in procs)
{
if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
{
ProcessModule[] arr = new ProcessModule[proc.Modules.Count];
foreach (ProcessModule pm in proc.Modules)
{
if (pm.ModuleName == fileName)
return proc.ProcessName;
}
}
}
return null;
}
First of all the right syntax is:
<!--[if IE 6]>
<link type="text/css" rel="stylesheet" href="/stylesheets/ie6.css" />
<![endif]-->
Try this post: http://www.quirksmode.org/css/condcom.html and http://css-tricks.com/how-to-create-an-ie-only-stylesheet/
Another thing you can do:
Check browser with jQuery:
if($.browser.msie){ // do something... }
in this case you can change css rules for some elements or add new css link reference:
read this: http://rickardnilsson.net/post/2008/08/02/Applying-stylesheets-dynamically-with-jQuery.aspx
#include <typeinfo>
...
string s = typeid(YourClass).name()
I had a similar problem recently with Oracle 12c. I created a new user with a lower case password and was able to login fine from the database server but all clients failed with an ORA-01017. The fix turned out to be simple in the end (reset the password to upper case) but took a lot of frustrating effort to get there.
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
Store.getRange()
seems to be exactly what you are searching for. It will return you Ext.data.Record[]
- array of records. If no arguments is passed, all the records are returned.
$ alias gpuom='git push origin master'
$ alias
hit Enter.$ vim ~/.bashrc
and hit Enter (I'm guessing you are familiar with vim).#My custom aliases
alias gpuom='git push origin master'
alias gplom='git pull origin master'
$ alias
hit Enter.If you don't care at all do this:
android:contentDescription="@null"
Although I would advise the accepted solutions, this is a hack :D
To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.
set "var=%cd%"
cd var
ipython notebook
An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.
A more 'magic' way, and doesn't need .NET 3.5.
If, for example, DBDatatable
was returning a single column of Guids (uniqueidentifier in SQL) then you could use:
Dim gList As New List(Of Guid)
gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))
I used iTextsharp with c# to combine pdf files. This is the code I used.
string[] lstFiles=new string[3];
lstFiles[0]=@"C:/pdf/1.pdf";
lstFiles[1]=@"C:/pdf/2.pdf";
lstFiles[2]=@"C:/pdf/3.pdf";
PdfReader reader = null;
Document sourceDocument = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage;
string outputPdfPath=@"C:/pdf/new.pdf";
sourceDocument = new Document();
pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
//Open the output file
sourceDocument.Open();
try
{
//Loop through the files list
for (int f = 0; f < lstFiles.Length-1; f++)
{
int pages =get_pageCcount(lstFiles[f]);
reader = new PdfReader(lstFiles[f]);
//Add pages of current file
for (int i = 1; i <= pages; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
reader.Close();
}
//At the end save the output file
sourceDocument.Close();
}
catch (Exception ex)
{
throw ex;
}
private int get_pageCcount(string file)
{
using (StreamReader sr = new StreamReader(File.OpenRead(file)))
{
Regex regex = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
It is worth noting that the accepted answer will round small floats down to zero.
>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03 4.82011728e-08 1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0. , 0. , 0. ])
You can use set_printoptions
and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:
>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
This way, you get the full versatility of format
and maintain the full precision of numpy's datatypes.
Also note that this only affects printing, not the actual precision of the stored values used for computation.
I found this in the Cheetah source code (here)
htmlCodes = [
['&', '&'],
['<', '<'],
['>', '>'],
['"', '"'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
""" Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
for code in codes:
s = s.replace(code[1], code[0])
return s
not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)
i noticed your title asked for encode too, so here is Cheetah's encode function.
def htmlEncode(s, codes=htmlCodes):
""" Returns the HTML encoded version of the given string. This is useful to
display a plain ASCII text string on a web page."""
for code in codes:
s = s.replace(code[0], code[1])
return s
Had to be dealing with whitespaces in pathnames, too. What I finally did was using a recursion and for item in /path/*
:
function recursedir {
local item
for item in "${1%/}"/*
do
if [ -d "$item" ]
then
recursedir "$item"
else
command
fi
done
}
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
change your code to this
$start_date = new DateTime( "@" . $dbResult->db_timestamp );
and it will work fine
Get latest version of MsBuild. Best way, for all types of msbuild installation, for different processor architecture (Power Shell):
function Get-MsBuild-Path
{
$msbuildPathes = $null
$ptrSize = [System.IntPtr]::Size
switch ($ptrSize) {
4 {
$msbuildPathes =
@(Resolve-Path "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\*\*\MSBuild\*\Bin\msbuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:ProgramFiles(x86)}\MSBuild\*\Bin\MSBuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:windir}\Microsoft.NET\Framework\*\MSBuild.exe" -ErrorAction SilentlyContinue)
}
8 {
$msbuildPathes =
@(Resolve-Path "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\*\*\MSBuild\*\Bin\amd64\msbuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:ProgramFiles(x86)}\MSBuild\*\Bin\amd64\MSBuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:windir}\Microsoft.NET\Framework64\*\MSBuild.exe" -ErrorAction SilentlyContinue)
}
default {
throw ($msgs.error_unknown_pointersize -f $ptrSize)
}
}
$latestMSBuildPath = $null
$latestVersion = $null
foreach ($msbuildFile in $msbuildPathes)
{
$msbuildPath = $msbuildFile.Path
$versionOutput = & $msbuildPath -version
$fileVersion = (New-Object System.Version($versionOutput[$versionOutput.Length - 1]))
if (!$latestVersion -or $latestVersion -lt $fileVersion)
{
$latestVersion = $fileVersion
$latestMSBuildPath = $msbuildPath
}
}
Write-Host "MSBuild version detected: $latestVersion" -Foreground Yellow
Write-Host "MSBuild path: $latestMSBuildPath" -Foreground Yellow
return $latestMSBuildPath;
}
Ensure module to be executed is installed or full path to command if it's not a node module
@Theo
The LINQ translator is smart enough to execute:
.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")
I've test this in LinqPad ==> YES, Linq translator is smart enough :))
The findandbind
npm addresses this for express/restify/connect: https://github.com/gyllstromk/node-find-and-bind
send a variable that flags the decode when you already getting data from an url.
?path=folder/new%20file.txt&decode=1
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).
apt-get install -d -o=dir::cache=/tmp whateveryouwant
Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).
This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.
I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot
is capable of plotting multiple lines with one command. If x
and y
are arrays, then plot
draws one line for every column.
In your case, you can do the following:
x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5, 1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')
Have a long list of x's and y's, and want to connect adjacent pairs?
xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])
Want a specified (different) color for the dots and the lines?
plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')
Don't ask what this has to do with that , but by right clicking the genymotion application file and changing to compatibility to Vista solved the problem!
That will almost work.
When pushing to a non-default branch, you need to specify the source ref and the target ref:
git push origin branch1:branch2
Or
git push <remote> <branch with new changes>:<branch you are pushing to>
Throwing an exception is the best way of dealing with constructor failure. You should particularly avoid half-constructing an object and then relying on users of your class to detect construction failure by testing flag variables of some sort.
On a related point, the fact that you have several different exception types for dealing with mutex errors worries me slightly. Inheritance is a great tool, but it can be over-used. In this case I would probably prefer a single MutexError exception, possibly containing an informative error message.
.nvmrc
If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc
file:
echo v10.15.1 > .nvmrc
This does not take effect automatically on cd
, which is sane: the user must then do a:
nvm use
and now that version of node will be used for the current shell.
You can list the versions of node that you have with:
nvm list
.nvmrc
is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc
How to automatically select that node version on cd
was asked at: Automatically switch to correct version of Node based on project
Tested with NVM 0.33.11.
Neither of the above answers worked for me, however this did
UPDATE:
As @doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on
. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.
$('iframe').on('load', function() {
// do stuff
});
If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.
Please note this doesn't solve the cookie sharing process, as in general this is bad practice.
You need to be using JSONP as your type:
From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
$.ajax(
{
type: "POST",
url: "http://example.com/api/getlist.json",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
},
success: function(){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
}
);
When a script is loaded, any parameters that are passed are automatically loaded into a special variables $args
. You can reference that in your script without first declaring it.
As an example, create a file called test.ps1
and simply have the variable $args
on a line by itself. Invoking the script like this, generates the following output:
PowerShell.exe -File test.ps1 a b c "Easy as one, two, three"
a
b
c
Easy as one, two, three
As a general recommendation, when invoking a script by calling PowerShell directly I would suggest using the -File
option rather than implicitly invoking it with the &
- it can make the command line a bit cleaner, particularly if you need to deal with nested quotes.
You can try command to clear the untracked files from the local
Git 2.11 and newer versions:
git clean -d -f .
Older versions of Git:
git clean -d -f ""
Where -d
can be replaced with the following:
-x
ignored files are also removed as well as files unknown to Git.
-d
remove untracked directories in addition to untracked files.
-f
is required to force it to run.
Here is the link that can be helpful as well.
No criticism regarding those great answers I just want to present the simple solution I use for our admin content creators:
^(\+|00)[1-9][0-9 \-\(\)\.]{7,}$
Force start with a plus or two zeros and use at least a little bit of numbers, white space, braces, minus and point is optional and no other characters. You can safely remove all non-numbers and use this in a tel: input. Numbers will have a common form of representation and I do not have to worry about being to restrictive.
..extending Mikaels' answers
SELECT
CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
...
e0
fixes some ISNUMERIC issues (such as +
-
.
and empty string being accepted)@Josh Lindsey already answered perfectly fine. But I want to add some information since I often use ssh.
Therefore just change:
git remote add origin [email protected]:/path/to/my_project.git
to:
git remote add origin ssh://[email protected]/path/to/my_project
Note that the colon between domain and path isn't there anymore.
in your projects build.gradle file... write as below.. i have solved that error by change the appcompat version from v7.23.0.0 to v7.22.2.1..
dependencies
{
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
}
For me the problem was a configuration file that was missing an Element.
using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
cmd.ExecuteNonQuery();
}
It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.
WARNING: this is unsanitized. You should use parameters to avoid injection attacks.
EDIT: Since Jon insists.
It must be overridden. You could use:
<!-- Add a class name to override -->
<select name="funTimes" class="funTimes" size="5">
#elementId select.funTimes {
/* Override styles here */
}
Make sure you use !important
flag in css style e.g. margin-top: 0px !important
What does !important mean in CSS?
You could use an attribute selector, but since that isn't supported by legacy browsers (read IE6 etc), it's better to add a class name
I think one thing that is worth mentioning and isn't intuitive enough from the documentation is that, when you use a factory function to create an array and you specify it's size, the array is initialized with values that are equal to their index values. For example, in an array such as this:
val array = Array(5, { i -> i })
, the initial values assigned are [0,1,2,3,4]
and not say, [0,0,0,0,0]
. That is why from the documentation, val asc = Array(5, { i -> (i * i).toString() })
produces an answer of ["0", "1", "4", "9", "16"]
@poulter7: I cannot comment on the other answers, so I post it as new answer: be careful with
np.log(df.price).diff()
as this will fail for indices which can become negative as well as risk factors e.g. negative interest rates. In these cases
np.log(df.price/df.price.shift(1)).dropna()
is preferred and based on my experience generally the safer approach. It also evaluates the logarithm only once.
Whether you use +1 or -1 depends on the ordering of your time series. Use -1 for descending and +1 for ascending dates - in both cases the shift provides the preceding date's value.
If you just want to indent random, arbitrary <option />
elements, you can use
, which has the greatest cross-browser compatibility of the solutions posted here...
.optionGroup {
font-weight: bold;
font-style: italic;
}
_x000D_
<select>
<option class="optionGroup" selected disabled>Choose one</option>
<option value="sydney" class="optionChild"> Sydney</option>
<option value="melbourne" class="optionChild"> Melbourne</option>
<option value="cromwell" class="optionChild"> Cromwell</option>
<option value="queenstown" class="optionChild"> Queenstown</option>
</select>
_x000D_
But if you have some sorted, ordered structure to your data, then it is recommended that you use the <optgroup/>
syntax....
The HTML element creates a grouping of options within a element. (Source: MDN Web Docs:
<optgroup>
)
<select>
<optgroup label="Australia" default selected>
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
</optgroup>
<optgroup label="United Kingdom">
<option value="london">London</option>
<option value="glasgow">Glasgow</option>
</optgroup>
</select>
_x000D_
Unfortunately, only one <optgroup />
level is allowed and currently supported by browsers today. (Source: w3.org.) Personally, I would consider that part of the spec broken, but you can always extend to third, fourth, etc., levels of indentation with using the
trick up above.
There is
between the two.
Semantical Difference:
FirstOrDefault
returns a first item of potentially multiple (or default if none exists).SingleOrDefault
assumes that there is a single item and returns it (or default if none exists). Multiple items are a violation of contract, an exception is thrown.Performance Difference
FirstOrDefault
is usually faster, it iterates until it finds the element and only has to iterate the whole enumerable when it doesn't find it. In many cases, there is a high probability to find an item.
SingleOrDefault
needs to check if there is only one element and therefore always iterates the whole enumerable. To be precise, it iterates until it finds a second element and throws an exception. But in most cases, there is no second element.
Conclusion
Use FirstOrDefault
if you don't care how many items there are or when you can't afford checking uniqueness (e.g. in a very large collection). When you check uniqueness on adding the items to the collection, it might be too expensive to check it again when searching for those items.
Use SingleOrDefault
if you don't have to care about performance too much and want to make sure that the assumption of a single item is clear to the reader and checked at runtime.
In practice, you use First
/ FirstOrDefault
often even in cases when you assume a single item, to improve performance. You should still remember that Single
/ SingleOrDefault
can improve readability (because it states the assumption of a single item) and stability (because it checks it) and use it appropriately.
Problem
The upstream server is timing out and I don't what is happening.
Where to Look first before increasing read or write timeout if your server is connecting to a database
Server is connecting to a database and that connection is working just fine and within sane response time, and its not the one causing this delay in server response time.
make sure that connection state is not causing a cascading failure on your upstream
Then you can move to look at the read and write timeout configurations of the server and proxy.
Try CTR + M it will work like before.
If you make change default value to CURRENT_TIMESTAMP
it is more effiency,
ALTER TABLE servers MODIFY COLUMN network_shares datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
If anyone can't seem to get there .bash_profile
file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.
That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.
Wrap code in
window.onload = function(){
// your code
};
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.
The other option is that if you have a filter that you always want applied, to add a custom manager on the model in question which always applies the filter to the results returned.
A good example of this is a Event
model, where for 90% of the queries you do on the model you are going to want something like Event.objects.filter(date__gte=now)
, i.e. you're normally interested in Events
that are upcoming. This would look like:
class EventManager(models.Manager):
def get_query_set(self):
now = datetime.now()
return super(EventManager,self).get_query_set().filter(date__gte=now)
And in the model:
class Event(models.Model):
...
objects = EventManager()
But again, this applies the same filter against all default queries done on the Event
model and so isn't as flexible some of the techniques described above.
This goes also for statements like this (auto-formatted by PyCharm):
return combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Which will give the same style-warning. In order to get rid of it I had to rewrite it to:
return \
combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Here's three ways to do it.
public enum Months {
JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), AUG(8), SEP(9), OCT(10), NOV(11), DEC(12);
int monthOrdinal = 0;
Months(int ord) {
this.monthOrdinal = ord;
}
public static Months byOrdinal2ndWay(int ord) {
return Months.values()[ord-1]; // less safe
}
public static Months byOrdinal(int ord) {
for (Months m : Months.values()) {
if (m.monthOrdinal == ord) {
return m;
}
}
return null;
}
public static Months[] MONTHS_INDEXED = new Months[] { null, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
}
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
public class MonthsTest {
@Test
public void test_indexed_access() {
assertEquals(Months.MONTHS_INDEXED[1], Months.JAN);
assertEquals(Months.MONTHS_INDEXED[2], Months.FEB);
assertEquals(Months.byOrdinal(1), Months.JAN);
assertEquals(Months.byOrdinal(2), Months.FEB);
assertEquals(Months.byOrdinal2ndWay(1), Months.JAN);
assertEquals(Months.byOrdinal2ndWay(2), Months.FEB);
}
}
I had the same error : The type 'MyCustomDerivedFactory' exists in both and My ServiceHost and ServiceHostFactory derived classes where in the App_Code folder of my WCF service project. Adding
<configuration>
<system.web>
<compilation batch="false" />
</system.web>
<configuration>
didn't solve the error but moving my ServiceHost and ServiceHostFactory derived classes in a separate Class library project did it.
Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.
See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
If you do not want to use numpy,
sorted(range(len(seq)), key=seq.__getitem__)
is fastest, as demonstrated here.
If you need something quick and dirty, you can just use PayPal's "Buy" buttons and drop them on your pages. These will take people off-site to PayPal where they can pay with a PayPal account or a credit card. This is free and super easy to implement.
If you want something a bit nicer where people pay on-site with their credit card, then you would want to look into one of those 3rd part payment providers. None of them (that I'm aware of) are completely free. All will have a per-transaction fee, and most will have a monthly fee as well.
Personally I've worked with Authorize.NET and PayPal Website Payments Pro. Both have great APIs and sample code that you can hook into via PHP easily enough.
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
In bash, the $LINES
and $COLUMNS
environmental variables should be able to do the trick. The will be set automatically upon any change in the terminal size. (i.e. the SIGWINCH signal)
In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.
component.html
<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
<label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio1" value="option1" type="radio"> TRUE
</label>
<label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio2" value="option2" type="radio"> FALSE
</label>
</div>
component.ts file
@Component({
selector: '',
templateUrl: './.component.html',
styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
checked = true;
}
Revisiting this question a few years later, UglifyJS, seems to be the best option as of now.
As stated below, it runs on the NodeJS platform, but can be easily modified to run on any JavaScript engine.
--- Old answer below---
Google released Closure Compiler which seems to be generating the smallest files so far as seen here and here
Previous to that the various options were as follow
Basically Packer does a better job at initial compression , but if you are going to gzip the files before sending on the wire (which you should be doing) YUI Compressor gets the smallest final size.
The tests were done on jQuery code btw.
@daniel james mentions in the comment compressorrater which shows Packer leading the chart in best compression, so I guess ymmv
Here is the code in Python to print all possible permutations of a list:
def next_perm(arr):
# Find non-increasing suffix
i = len(arr) - 1
while i > 0 and arr[i - 1] >= arr[i]:
i -= 1
if i <= 0:
return False
# Find successor to pivot
j = len(arr) - 1
while arr[j] <= arr[i - 1]:
j -= 1
arr[i - 1], arr[j] = arr[j], arr[i - 1]
# Reverse suffix
arr[i : ] = arr[len(arr) - 1 : i - 1 : -1]
print arr
return True
def all_perm(arr):
a = next_perm(arr)
while a:
a = next_perm(arr)
arr = raw_input()
arr.split(' ')
arr = map(int, arr)
arr.sort()
print arr
all_perm(arr)
I have used a lexicographic order algorithm to get all possible permutations, but a recursive algorithm is more efficient. You can find the code for recursive algorithm here: Python recursion permutations
If your method is void and you want to check for an exception, you could use expected
:
https://weblogs.java.net/blog/johnsmart/archive/2009/09/27/testing-exceptions-junit-47
You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.
A little math can give you a one-line function:
function zeroFill( number, width ) {
return Array(width - parseInt(Math.log(number)/Math.LN10) ).join('0') + number;
}
That's assuming that number
is an integer no wider than width
. If the calling routine can't make that guarantee, the function will need to make some checks:
function zeroFill( number, width ) {
var n = width - parseInt(Math.log(number)/Math.LN10);
return (n < 0) ? '' + number : Array(n).join('0') + number;
}
I ended up with this:
if($.browser.msie || $.browser.webkit){
// doesn't work with opera and FF
$(this).after($(this).clone(true)).remove();
}else{
this.setAttribute('type', 'text');
this.setAttribute('type', 'file');
}
may not be the most elegant solution, but it work as far as I can tell.
I second that.
Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.
However, JDGUI generates .java files which have ,more often than not, errors.
It has got something to do with code obfuscation I guess.
You need to pass your components as children, like this:
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
<App>
<SampleComponent name="SomeName"/>
<App>,
document.body
);
And then append them in the component's body:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
{
this.props.children
}
</div>
);
}
});
You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:
var App = React.createClass({
getInitialState: function(){
return [
{id:1,name:"Some Name"}
]
},
addChild: function() {
// State change will cause component re-render
this.setState(this.state.concat([
{id:2,name:"Another Name"}
]))
}
render: function() {
return (
<div>
<h1>App main component! </h1>
<button onClick={this.addChild}>Add component</button>
{
this.state.map((item) => (
<SampleComponent key={item.id} name={item.name}/>
))
}
</div>
);
}
});
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
The accepted answer didn't work for me on Azure SQL, here's one that did, it's super fast and did exactly what I wanted:
select t.name, s.row_count
from sys.tables t
join sys.dm_db_partition_stats s
ON t.object_id = s.object_id
and t.type_desc = 'USER_TABLE'
and t.name not like '%dss%'
and s.index_id = 1
order by s.row_count desc
If you like to have the timestamp without the timezone but local timezone do
git log -1 --format=%cd --date=local
Which gives this depending on your location
Mon Sep 28 12:07:37 2015
As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:
// 3. Pass the connection to a command object
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn); // ", conn)" added
cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
//
// 4. Use the connection
//
By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).
You don't have any example code but I assume you want to do something like this?
@View({
directives: [NgClass],
styles: [`
.${TodoModel.COMPLETED} {
text-decoration: line-through;
}
.${TodoModel.STARTED} {
color: green;
}
`],
template: `<div>
<span [ng-class]="todo.status" >{{todo.title}}</span>
<button (click)="todo.toggle()" >Toggle status</button>
</div>`
})
You assign ng-class
to a variable which is dynamic (a property of a model called TodoModel
as you can guess).
todo.toggle()
is changing the value of todo.status
and there for the class of the input is changing.
This is an example for class name but actually you could do the same think for css properties.
I hope this is what you meant.
This example is taken for the great egghead tutorial here.
@hydroo: Without the extra file:
#define SOME_ENUM(DO) \
DO(Foo) \
DO(Bar) \
DO(Baz)
#define MAKE_ENUM(VAR) VAR,
enum MetaSyntacticVariable{
SOME_ENUM(MAKE_ENUM)
};
#define MAKE_STRINGS(VAR) #VAR,
const char* const MetaSyntacticVariableNames[] = {
SOME_ENUM(MAKE_STRINGS)
};
well the only thing that will work is
python -m pip install pip==
you can and should run it under IDE terminal (mine was pycharm)
you can use following code.
file_obj = open('big_file')
open() returns a file object
then use os.stat for getting size
file_size = os.stat('big_file').st_size
for i in range( file_size/1024):
print file_obj.read(1024)
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
Make the table rock solid BEFORE the css. Figure your width of the table, then use a 'controlling' row whereby each td has an explicit width, all of which add up to the width in the table tag.
Having to do hundreds html emails to work everywhere, using the correct HTML first, then styling w/css will work around many issues in all IE's, webkit's and mozillas.
so:
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="50"></td>
<td width="100"></td>
<td width="150"></td>
</tr>
<tr>
<td>your stuff</td>
<td>your stuff</td>
<td>your stuff</td>
</tr>
</table>
Will keep a table at 300px wide. Watch images that are larger than the width by extremes
The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:
let UserSchema = new Schema({
username: {
type: String
},
events: {
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}
})
Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.
All of these answers could not work if you use Maven. The solution for me was to add
<genDirectory>${project.basedir}/gen</genDirectory>
to the configuration section of android-maven-plugin.
I did the same search time ago, it seems that he exact solution depends on the backend.
I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.
Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.
def maximize(backend=None,fullscreen=False):
"""Maximize window independently on backend.
Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
if backend is None:
backend=matplotlib.get_backend()
mng = plt.get_current_fig_manager()
if fullscreen:
mng.full_screen_toggle()
else:
if backend == 'wxAgg':
mng.frame.Maximize(True)
elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
mng.window.showMaximized()
elif backend == 'TkAgg':
mng.window.state('zoomed') #works fine on Windows!
else:
print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
plt.show()
plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)
None of the above changes worked for me. Please see my worked configuration below:
Dependencies:
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.4.0</version>
</dependency>
web.xml:
<servlet>
<servlet-name>cfxServlet</servlet-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.MyApplication</param-value>
</init-param>
<init-param>
<param-name>jaxrs.providers</param-name>
<param-value>org.codehaus.jackson.jaxrs.JacksonJsonProvider</param-value>
</init-param>
<init-param>
<param-name>jaxrs.extensions</param-name>
<param-value>
json=application/json
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cfxServlet</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
Enjoy coding .. :)
A newbie mistake was generating the same error message in my case.
The app-root
tag wasn't present in index.html
I can't comment on the above answer, but be careful with @Pavel Chuchuva's answer. That formula will not return a result if both coordinates are the same. In that case, distance is null, and so that row won't be returned with that formula as is.
I'm not a MySQL expert, but this seems to be working for me:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
FROM markers HAVING distance < 25 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;
Here's the fix that worked for me. Firefox has a file origin policy that causes this. To fix do the following steps:
Details: http://stuffandnonsense.co.uk/blog/about/firefoxs_file_uri_origin_policy_and_web_fonts
You will only see this issue when accessing a file using file:/// protocol
Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:
$ ps -ef|grep httpd
0 681 1 0 10:38pm ?? 0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501 690 681 0 10:38pm ?? 0:00.02 /Applications/MAMP/Library/bin/httpd -k start
...
Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)
$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.
Wait for crash... then:
(gdb) backtrace
Or
(gdb) backtrace full
Should give you some clue what's going on. If you file a bug report you should include the backtrace.
If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:
StartServers 1
MinSpareServers 1
MaxSpareServers 1
I would just do
int pnSize = primeNumber.size();
for (int i = 0; i < pnSize; i++)
cout << primeNumber[i] << ' ';
I use the timestamp
i.e
new File( simpleDateFormat.format( new Date() ) );
And have the simpleDateFormat initialized to something like as:
new SimpleDateFormat("File-ddMMyy-hhmmss.SSS.txt");
EDIT
What about
new File(String.format("%s.%s", sdf.format( new Date() ),
random.nextInt(9)));
Unless the number of files created in the same second is too high.
If that's the case and the name doesn't matters
new File( "file."+count++ );
:P
You May use set
keyword for set the path
set path=%path%;c:/wamp/bin/php/php5.3.0
if all the path are set in path variables
If you want to see all path list. you can use
set %path%
you need to append your php path behind this path.
This is how you can set environment variable.
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
Public Sub Extract_Outlook_Email_Attachments()
Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String
saveFolder = "Y:\Wingman" ' THIS IS WHERE YOU WANT TO SAVE THE ATTACHMENT TO
If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"
subjectFilter = ("Daily Operations Custom All Req Statuses Report") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND
OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set outApp = New Outlook.Application
OutlookOpened = True
End If
On Error GoTo 0
If outApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)
If Not outFolder Is Nothing Then
For Each outItem In outFolder.Items
If outItem.Class = Outlook.OlObjectClass.olMail Then
Set outMailItem = outItem
If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
For Each outAttachment In outMailItem.Attachments
outAttachment.SaveAsFile saveFolder & outAttachment.filename
Set outAttachment = Nothing
Next
End If
End If
Next
End If
If OutlookOpened Then outApp.Quit
Set outApp = Nothing
End Sub
Given the following tables..
Domain Table
dom_id | dom_url
Review Table
rev_id | rev_dom_from | rev_dom_for
Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.
Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for
If you are still stuck, please be more specific with exactly it is that you don't understand.
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
If you trust the host, either add the valid certificate, specify --no-check-certificate
or add:
check_certificate = off
into your ~/.wgetrc
.
In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.
The problem is easy to resolve; it's because the last line MUST be empty.
Say, if your content is
line 1,
line2
change it to
line 1,
line2
(empty line here)
Today I met this kind problem, when I was trying to use R to read a JSON file, by using command below:
json_data<-fromJSON(paste(readLines("json01.json"), collapse=""))
; and I resolve it by my above method.
I had a simple issue, but I was baffled by responses to this question.
I had to use a variable (myVar1) defined in one JavaScript file (myvariables.js) in another JavaScript file (main.js).
For this I did as below:
Loaded the JavaScript code in the HTML file, in the correct order, myvariables.js first, then main.js:
<html>
<body onload="bodyReady();" >
<script src="myvariables.js" > </script>
<script src="main.js" > </script>
<!-- Some other code -->
</body>
</html>
File: myvariables.js
var myVar1 = "I am variable from myvariables.js";
File: main.js
// ...
function bodyReady() {
// ...
alert (myVar1); // This shows "I am variable from myvariables.js", which I needed
// ...
}
// ...
As you saw, I had use a variable in one JavaScript file in another JavaScript file, but I didn't need to include one in another. I just needed to ensure that the first JavaScript file loaded before the second JavaScript file, and, the first JavaScript file's variables are accessible in the second JavaScript file, automatically.
This saved my day. I hope this helps.
I typically prefer if/else constructs over switch statements, especially in languages that allows fall-through cases. What I've found, often, is as the projects age, and multiple developers gets involved, you'll start having trouble with the construction of a switch statement.
If they (the statements) become anything more than simple, many programmers become lazy and instead of reading the entire statement to understand it, they'll simply pop in a case to cover whatever case they're adding into the statement.
I've seen many cases where code repeats in a switch statement because a person's test was already covered, a simple fall-though case would have sufficed, but laziness forced them to add the redundant code at the end instead of trying to understand the switch. I've also seen some nightmarish switch statements with many cases that were poorly constructed, and simply trying to follow all the logic, with many fall-through cases dispersed throughout, and many cases which weren't, becomes difficult ... which kind of leads to the first/redundancy problem I talked about.
Theoretically, the same problem could exist with if/else constructs, but in practice this just doesn't seem to happen as often. Maybe (just a guess) programmers are forced to read a bit more carefully because you need to understand the, often, more complex conditions being tested within the if/else construct? If you're writing something simple that you know others are likely to never touch, and you can construct it well, then I guess it's a toss-up. In that case, whatever is more readable and feels best to you is probably the right answer because you're likely to be sustaining that code.
Switch statements often perform faster than if-else constructs (but not always). Since the possible values of a switch statement are laid out beforehand, compilers are able to optimize performance by constructing jump tables. Each condition doesn't have to be tested as in an if/else construct (well, until you find the right one, anyway).
However this isn't always the case, though. If you have a simple switch, say, with possible values of 1 to 10, this will be the case. The more values you add requires the jump tables to be larger and the switch becomes less efficient (not than an if/else, but less efficient than the comparatively simple switch statement). Also, if the values are highly variant ( i.e. instead of 1 to 10, you have 10 possible values of, say, 1, 1000, 10000, 100000, and so on to 100000000000), the switch is less efficient than in the simpler case.
Hope this helps.
Couldnt get the TEXT() formula to work
Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back
Or you can do the same with a formula like this
=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)
Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.
As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.
For example, like this:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
With jQuery 1.6 version you can use the .promise()
method.
$(selector).fadeOut('slow');
$(selector).promise().done(function(){
// will be called when all the animations on the queue finish
});
It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.
While you should probably use one of the many SQLite wrappers, if you wanted to know how to call the SQLite library yourself, you would:
Configure your Swift project to handle SQLite C calls. If using Xcode 9 or later, you can simply do:
import SQLite3
Create/open database.
let fileURL = try! FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("test.sqlite")
// open database
var db: OpaquePointer?
guard sqlite3_open(fileURL.path, &db) == SQLITE_OK else {
print("error opening database")
sqlite3_close(db)
db = nil
return
}
Note, I know it seems weird to close the database upon failure to open, but the sqlite3_open
documentation makes it explicit that we must do so to avoid leaking memory:
Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to
sqlite3_close()
when it is no longer required.
Use sqlite3_exec
to perform SQL (e.g. create table).
if sqlite3_exec(db, "create table if not exists test (id integer primary key autoincrement, name text)", nil, nil, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error creating table: \(errmsg)")
}
Use sqlite3_prepare_v2
to prepare SQL with ?
placeholder to which we'll bind value.
var statement: OpaquePointer?
if sqlite3_prepare_v2(db, "insert into test (name) values (?)", -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing insert: \(errmsg)")
}
if sqlite3_bind_text(statement, 1, "foo", -1, SQLITE_TRANSIENT) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding foo: \(errmsg)")
}
if sqlite3_step(statement) != SQLITE_DONE {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure inserting foo: \(errmsg)")
}
Note, that uses the SQLITE_TRANSIENT
constant which can be implemented as follows:
internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
Reset SQL to insert another value. In this example, I'll insert a NULL
value:
if sqlite3_reset(statement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error resetting prepared statement: \(errmsg)")
}
if sqlite3_bind_null(statement, 1) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding null: \(errmsg)")
}
if sqlite3_step(statement) != SQLITE_DONE {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure inserting null: \(errmsg)")
}
Finalize prepared statement to recover memory associated with that prepared statement:
if sqlite3_finalize(statement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error finalizing prepared statement: \(errmsg)")
}
statement = nil
Prepare new statement for selecting values from table and loop through retrieving the values:
if sqlite3_prepare_v2(db, "select id, name from test", -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
while sqlite3_step(statement) == SQLITE_ROW {
let id = sqlite3_column_int64(statement, 0)
print("id = \(id); ", terminator: "")
if let cString = sqlite3_column_text(statement, 1) {
let name = String(cString: cString)
print("name = \(name)")
} else {
print("name not found")
}
}
if sqlite3_finalize(statement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error finalizing prepared statement: \(errmsg)")
}
statement = nil
Close database:
if sqlite3_close(db) != SQLITE_OK {
print("error closing database")
}
db = nil
For Swift 2 and older versions of Xcode, see previous revisions of this answer.
In angular 2 we don't have pre-defined filter and order by as it was with AngularJs, we need to create it for our requirements. It is time killing but we need to do it, (see No FilterPipe or OrderByPipe). In this article we are going to see how we can create filter called pipe in angular 2 and sorting feature called Order By. Let's use a simple dummy json data array for it. Here is the json we will use for our example
First we will see how to use the pipe (filter) by using the search feature:
Create a component with name category.component.ts
import { Component, OnInit } from '@angular/core';_x000D_
@Component({_x000D_
selector: 'app-category',_x000D_
templateUrl: './category.component.html'_x000D_
})_x000D_
export class CategoryComponent implements OnInit {_x000D_
_x000D_
records: Array<any>;_x000D_
isDesc: boolean = false;_x000D_
column: string = 'CategoryName';_x000D_
constructor() { }_x000D_
_x000D_
ngOnInit() {_x000D_
this.records= [_x000D_
{ CategoryID: 1, CategoryName: "Beverages", Description: "Coffees, teas" },_x000D_
{ CategoryID: 2, CategoryName: "Condiments", Description: "Sweet and savory sauces" },_x000D_
{ CategoryID: 3, CategoryName: "Confections", Description: "Desserts and candies" },_x000D_
{ CategoryID: 4, CategoryName: "Cheeses", Description: "Smetana, Quark and Cheddar Cheese" },_x000D_
{ CategoryID: 5, CategoryName: "Grains/Cereals", Description: "Breads, crackers, pasta, and cereal" },_x000D_
{ CategoryID: 6, CategoryName: "Beverages", Description: "Beers, and ales" },_x000D_
{ CategoryID: 7, CategoryName: "Condiments", Description: "Selishes, spreads, and seasonings" },_x000D_
{ CategoryID: 8, CategoryName: "Confections", Description: "Sweet breads" },_x000D_
{ CategoryID: 9, CategoryName: "Cheeses", Description: "Cheese Burger" },_x000D_
{ CategoryID: 10, CategoryName: "Grains/Cereals", Description: "Breads, crackers, pasta, and cereal" }_x000D_
];_x000D_
// this.sort(this.column);_x000D_
}_x000D_
}
_x000D_
<div class="col-md-12">_x000D_
<table class="table table-responsive table-hover">_x000D_
<tr>_x000D_
<th >Category ID</th>_x000D_
<th>Category</th>_x000D_
<th>Description</th>_x000D_
</tr>_x000D_
<tr *ngFor="let item of records">_x000D_
<td>{{item.CategoryID}}</td>_x000D_
<td>{{item.CategoryName}}</td>_x000D_
<td>{{item.Description}}</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
2.Nothing special in this code just initialize our records variable with a list of categories, two other variables isDesc and column are declared which we will use for sorting latter. At the end added this.sort(this.column); latter we will use, once we will have this method.
Note templateUrl: './category.component.html', which we will create next to show the records in tabluar format.
For this create a HTML page called category.component.html, whith following code:
3.Here we use ngFor to repeat the records and show row by row, try to run it and we can see all records in a table.
Search - Filter Records
Say we want to search the table by category name, for this let's add one text box to type and search
<div class="form-group">_x000D_
<div class="col-md-6" >_x000D_
<input type="text" [(ngModel)]="searchText" _x000D_
class="form-control" placeholder="Search By Category" />_x000D_
</div>_x000D_
</div>
_x000D_
5.Now we need to create a pipe to search the result by category because filter is not available as it was in angularjs any more.
Create a file category.pipe.ts and add following code in it.
import { Pipe, PipeTransform } from '@angular/core';_x000D_
@Pipe({ name: 'category' })_x000D_
export class CategoryPipe implements PipeTransform {_x000D_
transform(categories: any, searchText: any): any {_x000D_
if(searchText == null) return categories;_x000D_
_x000D_
return categories.filter(function(category){_x000D_
return category.CategoryName.toLowerCase().indexOf(searchText.toLowerCase()) > -1;_x000D_
})_x000D_
}_x000D_
}
_x000D_
6.Here in transform method we are accepting the list of categories and search text to search/filter record on the list. Import this file into our category.component.ts file, we want to use it here, as follows:
import { CategoryPipe } from './category.pipe';_x000D_
@Component({ _x000D_
selector: 'app-category',_x000D_
templateUrl: './category.component.html',_x000D_
pipes: [CategoryPipe] // This Line _x000D_
})
_x000D_
7.Our ngFor loop now need to have our Pipe to filter the records so change it to this.You can see the output in image below
I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).
If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:
// Any Tr element will be green if its (row.age > 20)
<ReactTable
getTrProps={(state, rowInfo, column) => {
return {
style: {
background: rowInfo.row.selected ? 'green' : 'red'
}
}
}}
/>
You are close, but the parameter you pass to SecureStringToBSTR
must be a SecureString
. You appear to be passing the result of ConvertFrom-SecureString
, which is an encrypted standard string. So call ConvertTo-SecureString
on this before passing to SecureStringToBSTR
.
$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
My solution:_x000D_
_x000D_
ul {_x000D_
line-height: 1.3 !important;_x000D_
li {_x000D_
font-size: x-large;_x000D_
position: relative;_x000D_
&:before {_x000D_
content: '';_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 5px;_x000D_
left: -25px;_x000D_
height: 23px;_x000D_
width: 23px;_x000D_
background-image: url(../img/list-char.png) !important;_x000D_
background-size: 23px;_x000D_
background-repeat: no-repeat;_x000D_
}_x000D_
}_x000D_
}
_x000D_
You can do this as well, hopeit helps
<span style="color:black"><i class="glyphicon glyphicon-music"></i></span>
Here's an elaboration of Kevin's answer. It's important to know that the expression to be returned is evaluated before finally
, even if it is returned after.
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int printX() {
System.out.println("X");
return 0;
}
public static int test() {
try {
return printX();
}
finally {
System.out.println("finally trumps return... sort of");
}
}
Output:
X
finally trumps return... sort of
0
select ID from A where ID not in (select ID from B);
or
select ID from A except select ID from B;
Your second question:
delete from A where ID not in (select ID from B);
The Change event gets called even if you click on cancel..
x = math.ceil(x * 100.0) / 100.0
To force git stash pop
run this command
git stash show -p | git apply && git stash drop
Swift 4
let dicc = NSDictionary()
//MARK: - This is empty dictionary
let dic = ["":""]
//MARK:- This is variable dic means if you want to put variable
let dic2 = ["":"", "":"", "":""]
//MARK:- Variable example
let dic3 = ["name":"Shakeel Ahmed", "imageurl":"https://abc?abc.abc/etc", "address":"Rawalpindi Pakistan"]
//MARK: - This is 2nd Variable Example dictionary
let dic4 = ["name": variablename, "city": variablecity, "zip": variablezip]
//MARK:- Dictionary String with Any Object
var dic5a = [String: String]()
//MARK:- Put values in dic
var dic5a = ["key1": "value", "key2":"value2", "key3":"value3"]
var dic5b = [String:AnyObject]()
dic5b = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]
or
//MARK:- Dictionary String with Any Object
let dic5 = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]
//MARK:- More Easy Way
let dic6a = NSDictionary()
let dic6b = NSMutalbeDictionary()
Express v4.17.0
app.use(express.urlencoded( {extended: true} ))
app.post('/userlogin', (req, res) => {
console.log(req.body) // object
var email = req.body.email;
}
/^.*?\bcat\b.*?\bmat\b.*?$/m
Using the m
modifier (which ensures the beginning/end metacharacters match on line breaks rather than at the very beginning and end of the string):
^
matches the line beginning.*?
matches anything on the line before...\b
matches a word boundary the first occurrence of a word boundary (as @codaddict discussed)cat
and another word boundary; note that underscores are treated as "word" characters, so _cat_
would not match*;.*?
: any characters before...mat
, boundary.*?
: any remaining characters before...$
: the end of the line.It's important to use \b
to ensure the specified words aren't part of longer words, and it's important to use non-greedy wildcards (.*?
) versus greedy (.*
) because the latter would fail on strings like "There is a cat on top of the mat which is under the cat." (It would match the last occurrence of "cat" rather than the first.)
* If you want to be able to match _cat_
, you can use:
/^.*?(?:\b|_)cat(?:\b|_).*?(?:\b|_)mat(?:\b|_).*?$/m
which matches either underscores or word boundaries around the specified words. (?:)
indicates a non-capturing group, which can help with performance or avoid conflicted captures.
Edit: A question was raised in the comments about whether the solution would work for phrases rather than just words. The answer is, absolutely yes. The following would match "A line which includes both the first phrase and the second phrase":
/^.*?(?:\b|_)first phrase here(?:\b|_).*?(?:\b|_)second phrase here(?:\b|_).*?$/m
Edit 2: If order doesn't matter you can use:
/^.*?(?:\b|_)(first(?:\b|_).*?(?:\b|_)second|second(?:\b|_).*?(?:\b|_)first)(?:\b|_).*?$/m
And if performance is really an issue here, it's possible lookaround (if your regex engine supports it) might (but probably won't) perform better than the above, but I'll leave both the arguably more complex lookaround version and performance testing as an exercise to the questioner/reader.
Edited per @Alan Moore's comment. I didn't have a chance to test it, but I'll take your word for it.
One more thing is the activity of the community. Compare the mailing list traffic for axis and cxf (2013).
So if this is any indicator of usage then axis is by far less used than cxf.
Compare CXF and Axis statistics at ohloh. CXF has very high activity while Axis has low activity overall.
This is the chart for the number of commits over time for CXF (red) and Axis1 (green) Axis2 (blue).
Its due to mismatch between column name defined in entity and the column name of table (in SQL db )
java.sql.SQLException: ORA-00904: "table_name"."column_name": invalid identifier e.g.java.sql.SQLException: ORA-00904: "STUDENT"."NAME": invalid identifier
issue can be like
in Student.java(entity file)
You have mentioned column name as "NAME" only.
But in STUDENT table ,column name is lets say "NMAE"
I had the same problem, maven was complaining about a missing artifact, even though it existed in .m2/repository/[...]. In my case the problem was that I forgot to specify the correct repository in the pom.xml from which the package was downloaded originally (download by another project).
Adding the package repository to the pom.xml solved the problem.
<repositories>
<repository>
<id>SomeName</id>
<name>SomeName</name>
<url>http://url.to.repo</url>
</repository>
</repositories>
Thanks Maximilianus for the hint to those "*.repositories" files in the package directory.
The same as @neobot's answer but a little more modern and succinct.
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'
Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
Here,
this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field
oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
Solution: Use unix command find
The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.
The Traditional Formula would be :
find <path> -flag <valueOfFlag>
Easy Examples
1.Find by Name - Find all package.json
from my current location subtree hierarchy.
find . -name "package.json"
2.Find by Name and Type - find all node_modules
directories from ALL file system (starting from root hierarchy )
sudo find / -name "node_modules" -type d
Complex Examples:
More Useful examples which can demonstrate the power of flag options and operators:
3.Regex and File Type - Find all javascript controllers variation names (using regex) javascript Files only in my app location.
find /user/dev/app -name "*contoller-*\.js" -type f
-type
f means file -name
related to regular expression to any variation of controller string and dash with .js
at the end
4.Depth - Find all routes patterns directories in app directory no more than 3 dimensions ( app/../../.. only and no more deeper)
find app -name "*route*" -type d -maxdepth 3
-type
d means directory -name
related to regular expression to any variation of route string -maxdepth
making the finder focusing on 3 subtree depth and no more <yourSearchlocation>/depth1/depth2/depth3
)
5.File Size , Ownership and OR Operator - Find all files with names 'sample' or 'test' under ownership of root user that greater than 1 Mega and less than 5 Mega.
find . \( -name "test" -or -name "sample" \) -user root -size +1M -size -5M
-size
threshold representing the range between more than (+) and less than (-) -user
representing the file owner -or
operator filters query for both regex matches
6.Empty Files - find all empty directories in file system
find / -type d -empty
7.Time Access, Modification and creation of files - find all files that were created/modified/access in directory in 10 days
# creation (c)
find /test -name "*.groovy" -ctime -10d
# modification (m)
find /test -name "*.java" -mtime -10d
# access (a)
find /test -name "*.js" -atime -10d
8.Modification Size Filter - find all files that were modified exactly between a week ago to 3 weeks ago and less than 500kb and present their sizes as a list
find /test -name "*.java" -mtime -3w -mtime +1w -size -500k | xargs du -h
index.html
<!DOCTYPE html>
<html>
<body>
<form action="submit.php" method="POST">
First name: <input type="text" name="firstname" /><br /><br />
Last name: <input type="text" name="lastname" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
After that one more file which page you want to display after pressing the submit button
submit.php
<html>
<body>
Your First Name is - <?php echo $_POST["firstname"]; ?><br>
Your Last Name is - <?php echo $_POST["lastname"]; ?>
</body>
</html>
When you are using any of the code provided by other users and if you want to display the message on your window and not on the alert
or console.log
, Then make sure you use javascript and not jquery.
Not everyone want to use alert
or console.log
alert('jquery is working');
console.log('jquery is working');
The code below will fail to display the message
Because we are using jquery inside the else
(how the hell the message displays on your screen if you do not have jquery)
if ('undefined' == typeof window.jQuery) {
$('#selector').appendTo('jquery is NOT working');
} else {
$('#selector').appendTo('jquery is working');
}
Use JavaScript instead
if ('undefined' == typeof window.jQuery) {
document.getElementById('selector').innerHTML = "jquery is NOT working";
} else {
document.getElementById('selector').innerHTML = "jquery is working";
}
As @Pascal said, it is likely that you encounter problem with the firewall or/and proxy issue. As a first step, go through FAQ on the CRAN web page. After that, try to flag R with --internet2.
Sometimes it could be useful to check global options in R studio and uncheck "Use Internet Explorer library/proxy for HTTP". Tools -> Global Options -> Packages and unchecking the "Use Internet Explorer library/proxy for HTTP" option.
Hope this helps.
Do it in two steps.
rm -r bar/
cp -r foo/ bar/
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
I thought I'd share a situation where my team decided to include .c files. Our archicture largely consists of modules that are decoupled through a message system. These message handlers are public, and call many local static worker functions to do their work. The problem came about when trying to get coverage for our unit test cases, as the only way to exercise this private implementation code was indirectly through the public message interface. With some worker functions knee-deep in the stack, this turned out to be a nightmare to achieve proper coverage.
Including the .c files gave us a way to reach the cog in the machine we were interesting in testing.
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
When writing queries with our server LIKE or INSTR (or CHARINDEX in T-SQL) takes too long, so we use LEFT like in the following structure:
select *
from little
left join big
on left( big.key, len(little.key) ) = little.key
I understand that might only work with varying endings to the query, unlike other suggestions with '%' + b + '%', but is enough and much faster if you only need b+'%'.
Another way to optimize it for speed (but not memory) is to create a column in "little" that is "len(little.key)" as "lenkey" and user that instead in the query above.
It is indeed possible with the following code
<div href="#" id='a'>
Hover me
</div>
<div id='b'>
Show me
</div>
and css
#a {
display: block;
}
#a:hover + #b {
display:block;
}
#b {
display:none;
}
Now by hovering on element #a shows element #b.