There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.
This is not the perfect solution (or the one you asked for) but a decent work-a-round.
The other answers only show the changed files.
git log -p DIR
is very useful, if you need the full diff of all changed files in a specific subdirectory.
Example: Show all detailed changes in a specific version range
git log -p 8a5fb..HEAD -- A B
commit 62ad8c5d
Author: Scott Tiger
Date: Mon Nov 27 14:25:29 2017 +0100
My comment
...
@@ -216,6 +216,10 @@ public class MyClass {
+ Added
- Deleted
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
DISCLAMER: Following code creates different threads for each function.
This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.
To make any function non blocking, simply copy the decorator and decorate any function with a callback function as parameter. The callback function will receive the data returned from the function.
import asyncio
import requests
def run_async(callback):
def inner(func):
def wrapper(*args, **kwargs):
def __exec():
out = func(*args, **kwargs)
callback(out)
return out
return asyncio.get_event_loop().run_in_executor(None, __exec)
return wrapper
return inner
def _callback(*args):
print(args)
# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
return requests.get(url)
get("https://google.com")
print("Non blocking code ran !!")
I just wanted to share a combined snippet for hiding the scrollbar that I use when developing. It is a collection of several snippets found on the Internet that works for me:
.container {
overflow-x: scroll; /* For horiz. scroll, otherwise overflow-y: scroll; */
-ms-overflow-style: none;
overflow: -moz-scrollbars-none;
scrollbar-width: none;
}
.container::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
You need to do this on each word after you split
into an array
of words.
public String reverse(String word) {
char[] chs = word.toCharArray();
int i=0, j=chs.length-1;
while (i < j) {
// swap chs[i] and chs[j]
char t = chs[i];
chs[i] = chs[j];
chs[j] = t;
i++; j--;
}
return String.valueOf(chs);
}
I encountered the same problem. When the folder /worker
is mounted to the container - all of it's content will be syncronized (so the node_modules folder will disappear if you don't have it locally.)
Due to incompatible npm packages based on OS, I could not just install the modules locally - then launch the container, so..
My solution to this, was to wrap the source in a src
folder, then link node_modules
into that folder, using this index.js file. So, the index.js
file is now the starting point of my application.
When I run the container, I mounted the /app/src
folder to my local src
folder.
So the container folder looks something like this:
/app
/node_modules
/src
/node_modules -> ../node_modules
/app.js
/index.js
It is ugly, but it works..
The problem could be on this line:
var selectedText2 = $("#SelectedCountryId:selected").text();
It's looking for the item with id of SelectedCountryId
that is selected, where you really want the option that's selected under SelectedCountryId
, so try:
$('#SelectedCountryId option:selected').text()
If you are using just code like this below, you must put just a grave accent at the end of line `
.
docker run -d --name rabbitmq ` -p 5672:5672 ` -p 15672:15672 ` --restart=always ` --hostname rabbitmq-master ` -v c:\docker\rabbitmq\data:/var/lib/rabbitmq ` rabbitmq:latest
In my case i used directive, but hadn't imported it in my module.ts file. Import fixed it.
To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.
So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:
When I log in the user I save the access token:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$accessToken = $facebook->getAccessToken();
//save the access token for later
Now when I make requests to facebook I just do something like this:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.
Refer below URL
COUNTER=1
while [ Your != "done" ]
do
echo " $COUNTER "
COUNTER=$[$COUNTER +1]
done
TESTED BASH: Centos, SuSE, RH
Try this for WPF
StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
Go to: C:\Users\ [youruserdirectory] \bash_profile
In your bash_profile file type - alias desk='cd " [DIRECTORY LOCATION] "'
Refresh your User directory where the bash_profile file exists then reopen your CMD or Git Bash window
Type in desk to see if you get to the Desktop location or the location you want in the "DIRECTORY LOCATION" area above
Note: [ desk ] can be what ever name that you choose and should get you to the location you want to get to when typed in the CMD window.
Since dplyr 1.0.0
, the slice_max()
/slice_min()
functions were implemented:
mtcars %>%
group_by(cyl) %>%
slice_max(mpg, n = 2, with_ties = FALSE)
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
2 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
3 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
4 21 6 160 110 3.9 2.62 16.5 0 1 4 4
5 19.2 8 400 175 3.08 3.84 17.0 0 0 3 2
6 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
The documentation on with_ties
parameter:
Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.
Below window(w1) opens another window(w2). Any window can send/receive message to/from another window. So we should ideally verify that the message originated from the window(w2) we opened.
In w1
var w2 = window.open("abc.do");
window.addEventListener("message", function(event){
console.log(event.data);
});
In w2(abc.do)
window.opener.postMessage("Hi! I'm w2", "*");
If you are using wiindows OS (I am using windows 10 ) just type
where python
in command prompt ( cmd )
It will show you the directory where you have installed .
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
I started using the 'prefix-free' Script available at http://leaverou.github.io/prefixfree so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:
$('.user-text').css('transform', 'scale(' + ui.value + ')');
I had this problem and I solved the following:
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
Go to control panel ? services, look for MySQL and right click choose properties. If there, in “path to EXE file”, there is a parameter like
--defaults-file="X:\path\to\my.ini"
this is the file the server actually uses (independent of what mysql --help
prints).
The ZingChart library has an AngularJS directive that was built in-house. Features include:
Support from the development team
...
$scope.myJson = {
type : 'line',
series : [
{ values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
]
};
...
<zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
There is a full demo with code examples available.
in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver
instead of manage.py runserver
in my project directory.
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
for($i=0; $i < count($owned_urls); $i++)
{
if(strpos($string,$owned_urls[$i]) != false)
echo 'Found';
}
if there are multiple java processes and you wish to kill them with one command try the below command
kill -9 $(ps -ef | pgrep -f "java")
replace "java" with any process string identifier , to kill anything else.
For windows & pycharm setup:
If you are using pycharm and If you want to use pip3 install git+https://github.com/...
If you are using Primefaces, you should insert inside the the .xhtml file so it converts correctly to java integer. For example:
<p:selectCheckboxMenu
id="frameSelect"
widgetVar="frameSelectBox"
filter="true"
filterMatchMode="contains"
label="#{messages['frame']}"
value="#{platform.frameBean.selectedFramesTypesList}"
converter="javax.faces.Integer">
<f:selectItems
value="#{platform.frameBean.framesTypesList}"
var="area"
itemLabel="#{area}"
itemValue="#{area}" />
</p:selectCheckboxMenu>
In my case, I've just downloaded the missing file directly from here: https://gitlab.com/mailman/mailman-website/raw/a97d6b4c5b29594004e3855f1ab1222449d0c211/content/fonts/glyphicons-halflings-regular.woff2
Your form should look like this :
<form action="myprocessingscript.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
and the PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
I wrote to /tmp/mydata.txt
because this way I know exactly where it is. using data.txt
writes to that file in the current working directory which I know nothing of in your example.
file_put_contents
opens, writes and closes files for you. Don't mess with it.
Further reading: file_put_contents
Try adding the following to your JS on bootply
$('#myModal2').on('show.bs.modal', function () {
$('#myModal').css('z-index', 1030); })
$('#myModal2').on('hidden.bs.modal', function () {
$('#myModal').css('z-index', 1040); })
Explanation:
After playing around with the attributes(using Chrome's dev tool), I have realized that any z-index
value below 1031
will put things behind the backdrop.
So by using bootstrap's modal event handles I set the z-index
to 1030
. If #myModal2
is shown and set the z-index
back to 1040
if #myModal2
is hidden.
just the query phpmyadmin prints after granting super user. hope help someone with console:
ON $.$ TO-> $=* doesnt show when you put two with a dot between them.
REVOKE ALL PRIVILEGES ON . FROM 'usr'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'usr'@'localhost' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
and the reverse one, removing grant:
REVOKE ALL PRIVILEGES ON . FROM 'dos007'@'localhost'; REVOKE GRANT OPTION ON . FROM 'dos007'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'dos007'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
checked on vagrant should be working in any mysql
use MYSQL as Example: 1) use database connection pools: for Example: Apache Commons DBCP , also, you need basicDataSource jar package in your classpath
@Bean
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/gene");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
2)use JDBC-based Driver it is usually used if you don't consider connection pool:
@Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/gene");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
Try changing "Reports" to "ReportServer" in your url
Converting int64
:
n := int64(32)
str := strconv.FormatInt(n, 10)
fmt.Println(str)
// Prints "32"
You can not access the environment variable like this.
Inside the .env
file you write
IMAP_HOSTNAME_TEST=imap.gmail.com // I am okay with this
Next, inside the config
folder there is a file, mail.php. You may use this file to code. As you are working with mail functionality. You might use another file as well.
return [
//..... other declarations
'imap_hostname_test' => env('IMAP_HOSTNAME_TEST'),
// You are hiding the value inside the configuration as well
];
You can call the variable from a controller using 'config(
.
Whatever file you are using inside config folder. You need to use that file name (without extension) + '.' + 'variable name' + ')'
. In the current case you can call the variable as follows.
$hostname = config('mail.imap_hostname_test');
Since you declare the variable inside mail.php and the variable name is imap_hostname_test
, you need to call it like this. If you declare this variable inside app.php
then you should call
$hostname = config('app.imap_hostname_test');
button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))
I believe should fix this
Sure you can use Swift!
Add the video (lets call it video.m4v
) to your Xcode project
Open the Project Navigator
cmd + 1
Then select your project root
> your Target
> Build Phases
> Copy Bundle Resources
.
Your video MUST be here. If it's not, then you should add it using the plus button
Open your View Controller and write this code.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}
}
}
Goto chrome://flags/#enable-webfonts-intervention-v2 and set it to disabled
It’s due to a bug in Chrome with their latest API for ‘network speed’. Hope it will be fixed in the next version
1. You've got the right idea about how to design your resources, IMHO. I wouldn't change a thing.
2. Rather than trying to extend HTTP with more verbs, consider what your proposed verbs can be reduced to in terms of the basic HTTP methods and resources. For example, instead of an activate_login
verb, you could set up resources like: /api/users/1/login/active
which is a simple boolean. To activate a login, just PUT
a document there that says 'true' or 1 or whatever. To deactivate, PUT
a document there that is empty or says 0 or false.
Similarly, to change or set passwords, just do PUT
s to /api/users/1/password
.
Whenever you need to add something (like a credit) think in terms of POST
s. For example, you could do a POST
to a resource like /api/users/1/credits
with a body containing the number of credits to add. A PUT
on the same resource could be used to overwrite the value rather than add. A POST
with a negative number in the body would subtract, and so on.
3. I'd strongly advise against extending the basic HTTP status codes. If you can't find one that matches your situation exactly, pick the closest one and put the error details in the response body. Also, remember that HTTP headers are extensible; your application can define all the custom headers that you like. One application that I worked on, for example, could return a 404 Not Found
under multiple circumstances. Rather than making the client parse the response body for the reason, we just added a new header, X-Status-Extended
, which contained our proprietary status code extensions. So you might see a response like:
HTTP/1.1 404 Not Found
X-Status-Extended: 404.3 More Specific Error Here
That way a HTTP client like a web browser will still know what to do with the regular 404 code, and a more sophisticated HTTP client can choose to look at the X-Status-Extended
header for more specific information.
4. For authentication, I recommend using HTTP authentication if you can. But IMHO there's nothing wrong with using cookie-based authentication if that's easier for you.
var expressionWithoutQuotes = '';
for(var i =0; i<length;i++){
if(expressionDiv.charAt(i) != '"'){
expressionWithoutQuotes += expressionDiv.charAt(i);
}
}
This may work for you.
While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this
mkdir -p {main,test}/{resources,scala/com/company}
It will create following directory structure under the directory from where it is invoked
+-- main
¦ +-- resources
¦ +-- scala
¦ +-- com
¦ +-- company
+-- test
+-- resources
+-- scala
+-- com
+-- company
The example was taken from this link for creating SBT directory structure
Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.
In practise it's a bit quirky.
Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.
You have to release Ctrl before you can rotate again.
KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).
The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.
Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.
Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.
Using the join operator you can only perform equijoins. Other types of joins can be constructed using other operators. I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause. Documentation on the join clause can be found here. MSDN has an article on join operations with multiple links to examples of other joins, as well.
To answer your question:
.html()
will just call .innerHTML
after doing some checks for nodeTypes and stuff. It also uses a try/catch
block where it tries to use innerHTML
first and if that fails, it'll fallback gracefully to jQuery's .empty()
+ append()
Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.
Everyone wants to make this more complicated than it is. The crypt() function does most of the work.
function blowfishCrypt($password,$cost)
{
$chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
// $salt=sprintf('$2a$%02d$',$cost);
//Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
mt_srand();
for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
return crypt($password,$salt);
}
Example:
$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password
I know it should be obvious, but please don't use 'password' as your password.
Check if the Node
is a Dom Element
, cast, and call getElementsByTagName()
Node doc = docs.item(i);
if(doc instanceof Element) {
Element docElement = (Element)doc;
...
cell = doc.getElementsByTagName("aoo").item(0);
}
Short answer:
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
-- The way to go these days --
Use SipHash. For your own protection.
-- Old and Dangerous --
unsigned int RSHash(const std::string& str)
{
unsigned int b = 378551;
unsigned int a = 63689;
unsigned int hash = 0;
for(std::size_t i = 0; i < str.length(); i++)
{
hash = hash * a + str[i];
a = a * b;
}
return (hash & 0x7FFFFFFF);
}
unsigned int JSHash(const std::string& str)
{
unsigned int hash = 1315423911;
for(std::size_t i = 0; i < str.length(); i++)
{
hash ^= ((hash << 5) + str[i] + (hash >> 2));
}
return (hash & 0x7FFFFFFF);
}
Ask google for "general purpose hash function"
Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.
This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.
SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';
Hope This Might Help
As far as I can remember, an array is actually a group of pointers. For example
p[1]== *(&p+1)
is a true statement
Another method without having to update your Python code at all, would be to redirect via the console.
Basically, have your Python script print()
as usual, then call the script from the command line and use command line redirection. Like this:
$ python ./myscript.py > output.txt
Your output.txt
file will now contain all output from your Python script.
Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py
)
Alternate solution of the values check
//Duplicate Title Entry
$.each(ar , function (i, val) {
if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
});
Note and update:
Since Git1.7.4 (January 2011), you have git merge --abort
, synonymous to "git reset --merge
" when a merge is in progress.
But if you want to complete the merge, while somehow nothing remains to be added, then a crude rm -rf .git/MERGE*
can be enough for Git to forget about the current merge.
I just used less
on top of Cygwin to read a 3GB file, though I ended up using grep
to find what I needed in it.
(less
is more
, but better.)
See this answer for more details on less
: https://stackoverflow.com/a/1343576/1005039
For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.
IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.
There is another library with much cleaner API and type-safe data. https://github.com/kodart/Httpzoid
Here is a simple usage example
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.execute();
Or more complex with callbacks
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.handler(new ResponseHandler<Void>() {
@Override
public void success(Void ignore, HttpResponse response) {
}
@Override
public void error(String message, HttpResponse response) {
}
@Override
public void failure(NetworkError error) {
}
@Override
public void complete() {
}
}).execute();
It is fresh new, but looks very promising.
Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?
Only related with currency trading (Forex), but many Forex brokers are offering MetaTrader which let you code in MQL. The main problem with it (aside that it's limited to Forex) is that you've to code in MQL which might not be your preferred language.
Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.
Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT
or ROLLBACK
statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT
applies the changes (if any) made within the transaction. ROLLBACK
disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.
Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:
SET autocommit = 0
An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION
. It also requires an explicitly made COMMIT
or ROLLBACK
statement at the end of the transaction. Nested transactions is beyond the scope of this topic.
Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT
or ROLLBACK
statement to be supplied.
Explicit transactions are the most ideal solution - they require a statement, COMMIT
or ROLLBACK
, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT
statements should only be specified once results have been tested & thoroughly determined to be valid.
That means you should use:
SET autocommit = 0;
START TRANSACTION;
UPDATE ...;
...and only use COMMIT;
when the results are correct.
That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.
DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.
A practical example of a singleton can be found in Test::Builder, the class which backs just about every modern Perl testing module. The Test::Builder singleton stores and brokers the state and history of the test process (historical test results, counts the number of tests run) as well as things like where the test output is going. These are all necessary to coordinate multiple testing modules, written by different authors, to work together in a single test script.
The history of Test::Builder's singleton is educational. Calling new()
always gives you the same object. First, all the data was stored as class variables with nothing in the object itself. This worked until I wanted to test Test::Builder with itself. Then I needed two Test::Builder objects, one setup as a dummy, to capture and test its behavior and output, and one to be the real test object. At that point Test::Builder was refactored into a real object. The singleton object was stored as class data, and new()
would always return it. create()
was added to make a fresh object and enable testing.
Currently, users are wanting to change some behaviors of Test::Builder in their own module, but leave others alone, while the test history remains in common across all testing modules. What's happening now is the monolithic Test::Builder object is being broken down into smaller pieces (history, output, format...) with a Test::Builder instance collecting them together. Now Test::Builder no longer has to be a singleton. Its components, like history, can be. This pushes the inflexible necessity of a singleton down a level. It gives more flexibility to the user to mix-and-match pieces. The smaller singleton objects can now just store data, with their containing objects deciding how to use it. It even allows a non-Test::Builder class to play along by using the Test::Builder history and output singletons.
Seems to be there's a push and pull between coordination of data and flexibility of behavior which can be mitigated by putting the singleton around just shared data with the smallest amount of behavior as possible to ensure data integrity.
function convertToRoman(num) {_x000D_
var arr = [];_x000D_
for (var i = 0; i < num.toString().length; i++) {_x000D_
arr.push(Number(num.toString().substr(i, 1)));_x000D_
}_x000D_
var romanArr = [_x000D_
["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"],_x000D_
["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],_x000D_
["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"],_x000D_
["M"]_x000D_
];_x000D_
var roman = arr.reverse().map(function (val, i) {_x000D_
if (val === 0) {_x000D_
return "";_x000D_
}_x000D_
if (i === 3) {_x000D_
var r = "";_x000D_
for (var j = 0; j < val; j++) {_x000D_
r += romanArr[i][0];_x000D_
}_x000D_
return r;_x000D_
} else {_x000D_
return romanArr[i][val - 1];_x000D_
}_x000D_
});_x000D_
console.log(roman.reverse().join(""));_x000D_
return roman.join("");_x000D_
}_x000D_
_x000D_
_x000D_
convertToRoman(10);
_x000D_
This currently only works with lower case but its super easy to make it work with both.
cout << "\nEnter a hexadecimal number: ";
cin >> hexNumber;
orighex = hexNumber;
strlength = hexNumber.length();
for (i=0;i<strlength;i++)
{
hexa = hexNumber.substr(i,1);
if ((hexa>="0") && (hexa<="9"))
{
//cout << "This is a numerical value.\n";
}
else
{
//cout << "This is a alpabetical value.\n";
if (hexa=="a"){hexa="10";}
else if (hexa=="b"){hexa="11";}
else if (hexa=="c"){hexa="12";}
else if (hexa=="d"){hexa="13";}
else if (hexa=="e"){hexa="14";}
else if (hexa=="f"){hexa="15";}
else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";}
}
//convert from string to integer
hx = atoi(hexa.c_str());
finalhex = finalhex + (hx*pow(16.0,strlength-i-1));
}
cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n";
Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...
http://www.jetbrains.com/idea/features/editions_comparison_matrix.html
it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.
I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.
Anyway this tells that story too... http://www.jetbrains.com/products.html
Nevermind.
I had to look at the Lucene documentation. Seems I can use wildcards! :-)
curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*
does the trick!
Please install http://asepsis.binaryage.com/ and then reboot your mac.
ASEPSIS redirect all .DS_Store on your mac to /usr/local/.dscage
After that, You could delete recursively all .DS_Store from your mac.
find ~ -name ".DS_Store" -delete
or
find <your path> -name ".DS_Store" -delete
You should repeat procedure after each Mac major update.
If all you want to do is change a single line, use \r
. \r
means carriage return. It's effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly, \b
can be used to go one character backward. (some terminals may not support all those features)
import sys
def process(data):
size_str = os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
sys.stdout.write('%s\r' % size_str)
sys.stdout.flush()
file.write(data)
Everybody struggles initially while installing opencv. Opencv requires lot of dependencies in back-end. The best way to start with opencv is, install it in virtual environment. I suggest you to first install python anaconda distribution and create virtual environment using it. Then inside virtual environment using conda install command you can easily install opencv. I feel this is the most safe and easy approach to install opencv. The following command work for me, you can try the same.
conda install -c menpo opencv3
You could try to reinstall the ca-certificates
package, or explicitly allow the certificate in question as described here.
i solved this problem by removing space between quotes and command value inside of array ,this is happened because container exited after started and no executable command present which to be run inside of container.
['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:
SELECT
SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table
You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:
RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
rm -f treeio.zip && cd treeio && pip install -r requirements.pip
Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.
In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.
If you use CSS to select a monospace font, the problem of varying character length is easily solved.
I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.
The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.
I believe that a memory mapped file will be the fastest solution. I tried four functions: the function posted by the OP (opcount
); a simple iteration over the lines in the file (simplecount
); readline with a memory-mapped filed (mmap) (mapcount
); and the buffer read solution offered by Mykola Kharechko (bufcount
).
I ran each function five times, and calculated the average run-time for a 1.2 million-line text file.
Windows XP, Python 2.5, 2GB RAM, 2 GHz AMD processor
Here are my results:
mapcount : 0.465599966049
simplecount : 0.756399965286
bufcount : 0.546800041199
opcount : 0.718600034714
Edit: numbers for Python 2.6:
mapcount : 0.471799945831
simplecount : 0.634400033951
bufcount : 0.468800067902
opcount : 0.602999973297
So the buffer read strategy seems to be the fastest for Windows/Python 2.6
Here is the code:
from __future__ import with_statement
import time
import mmap
import random
from collections import defaultdict
def mapcount(filename):
f = open(filename, "r+")
buf = mmap.mmap(f.fileno(), 0)
lines = 0
readline = buf.readline
while readline():
lines += 1
return lines
def simplecount(filename):
lines = 0
for line in open(filename):
lines += 1
return lines
def bufcount(filename):
f = open(filename)
lines = 0
buf_size = 1024 * 1024
read_f = f.read # loop optimization
buf = read_f(buf_size)
while buf:
lines += buf.count('\n')
buf = read_f(buf_size)
return lines
def opcount(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
counts = defaultdict(list)
for i in range(5):
for func in [mapcount, simplecount, bufcount, opcount]:
start_time = time.time()
assert func("big_file.txt") == 1209138
counts[func].append(time.time() - start_time)
for key, vals in counts.items():
print key.__name__, ":", sum(vals) / float(len(vals))
Here you have an example
$("#profiles-thread").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: URL,
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.completeName,
slug: item.slug,
id: item.id
}
})
};
}
}
});
It's quite easy
Since I wrote my prior answer, I have formulated a new definition of the declarative property which is quoted below. I have also defined imperative programming as the dual property.
This definition is superior to the one I provided in my prior answer, because it is succinct and it is more general. But it may be more difficult to grok, because the implication of the incompleteness theorems applicable to programming and life in general are difficult for humans to wrap their mind around.
The quoted explanation of the definition discusses the role pure functional programming plays in declarative programming.
Declarative vs. Imperative
The declarative property is weird, obtuse, and difficult to capture in a technically precise definition that remains general and not ambiguous, because it is a naive notion that we can declare the meaning (a.k.a semantics) of the program without incurring unintended side effects. There is an inherent tension between expression of meaning and avoidance of unintended effects, and this tension actually derives from the incompleteness theorems of programming and our universe.
It is oversimplification, technically imprecise, and often ambiguous to define declarative as “what to do” and imperative as “how to do”. An ambiguous case is the “what” is the “how” in a program that outputs a program— a compiler.
Evidently the unbounded recursion that makes a language Turing complete, is also analogously in the semantics— not only in the syntactical structure of evaluation (a.k.a. operational semantics). This is logically an example analogous to Gödel's theorem— “any complete system of axioms is also inconsistent”. Ponder the contradictory weirdness of that quote! It is also an example that demonstrates how the expression of semantics does not have a provable bound, thus we can't prove2 that a program (and analogously its semantics) halt a.k.a. the Halting theorem.
The incompleteness theorems derive from the fundamental nature of our universe, which as stated in the Second Law of Thermodynamics is “the entropy (a.k.a. the # of independent possibilities) is trending to maximum forever”. The coding and design of a program is never finished— it's alive!— because it attempts to address a real world need, and the semantics of the real world are always changing and trending to more possibilities. Humans never stop discovering new things (including errors in programs ;-).
To precisely and technically capture this aforementioned desired notion within this weird universe that has no edge (ponder that! there is no “outside” of our universe), requires a terse but deceptively-not-simple definition which will sound incorrect until it is explained deeply.
Definition:
The declarative property is where there can exist only one possible set of statements that can express each specific modular semantic.
The imperative property3 is the dual, where semantics are inconsistent under composition and/or can be expressed with variations of sets of statements.
This definition of declarative is distinctively local in semantic scope, meaning that it requires that a modular semantic maintain its consistent meaning regardless where and how it's instantiated and employed in global scope. Thus each declarative modular semantic should be intrinsically orthogonal to all possible others— and not an impossible (due to incompleteness theorems) global algorithm or model for witnessing consistency, which is also the point of “More Is Not Always Better” by Robert Harper, Professor of Computer Science at Carnegie Mellon University, one of the designers of Standard ML.
Examples of these modular declarative semantics include category theory functors e.g. the
Applicative
, nominal typing, namespaces, named fields, and w.r.t. to operational level of semantics then pure functional programming.Thus well designed declarative languages can more clearly express meaning, albeit with some loss of generality in what can be expressed, yet a gain in what can be expressed with intrinsic consistency.
An example of the aforementioned definition is the set of formulas in the cells of a spreadsheet program— which are not expected to give the same meaning when moved to different column and row cells, i.e. cell identifiers changed. The cell identifiers are part of and not superfluous to the intended meaning. So each spreadsheet result is unique w.r.t. to the cell identifiers in a set of formulas. The consistent modular semantic in this case is use of cell identifiers as the input and output of pure functions for cells formulas (see below).
Hyper Text Markup Language a.k.a. HTML— the language for static web pages— is an example of a highly (but not perfectly3) declarative language that (at least before HTML 5) had no capability to express dynamic behavior. HTML is perhaps the easiest language to learn. For dynamic behavior, an imperative scripting language such as JavaScript was usually combined with HTML. HTML without JavaScript fits the declarative definition because each nominal type (i.e. the tags) maintains its consistent meaning under composition within the rules of the syntax.
A competing definition for declarative is the commutative and idempotent properties of the semantic statements, i.e. that statements can be reordered and duplicated without changing the meaning. For example, statements assigning values to named fields can be reordered and duplicated without changed the meaning of the program, if those names are modular w.r.t. to any implied order. Names sometimes imply an order, e.g. cell identifiers include their column and row position— moving a total on spreadsheet changes its meaning. Otherwise, these properties implicitly require global consistency of semantics. It is generally impossible to design the semantics of statements so they remain consistent if randomly ordered or duplicated, because order and duplication are intrinsic to semantics. For example, the statements “Foo exists” (or construction) and “Foo does not exist” (and destruction). If one considers random inconsistency endemical of the intended semantics, then one accepts this definition as general enough for the declarative property. In essence this definition is vacuous as a generalized definition because it attempts to make consistency orthogonal to semantics, i.e. to defy the fact that the universe of semantics is dynamically unbounded and can't be captured in a global coherence paradigm.
Requiring the commutative and idempotent properties for the (structural evaluation order of the) lower-level operational semantics converts operational semantics to a declarative localized modular semantic, e.g. pure functional programming (including recursion instead of imperative loops). Then the operational order of the implementation details do not impact (i.e. spread globally into) the consistency of the higher-level semantics. For example, the order of evaluation of (and theoretically also the duplication of) the spreadsheet formulas doesn't matter because the outputs are not copied to the inputs until after all outputs have been computed, i.e. analogous to pure functions.
C, Java, C++, C#, PHP, and JavaScript aren't particularly declarative. Copute's syntax and Python's syntax are more declaratively coupled to intended results, i.e. consistent syntactical semantics that eliminate the extraneous so one can readily comprehend code after they've forgotten it. Copute and Haskell enforce determinism of the operational semantics and encourage “don't repeat yourself” (DRY), because they only allow the pure functional paradigm.
2 Even where we can prove the semantics of a program, e.g. with the language Coq, this is limited to the semantics that are expressed in the typing, and typing can never capture all of the semantics of a program— not even for languages that are not Turing complete, e.g. with HTML+CSS it is possible to express inconsistent combinations which thus have undefined semantics.
3 Many explanations incorrectly claim that only imperative programming has syntactically ordered statements. I clarified this confusion between imperative and functional programming. For example, the order of HTML statements does not reduce the consistency of their meaning.
Edit: I posted the following comment to Robert Harper's blog:
in functional programming ... the range of variation of a variable is a type
Depending on how one distinguishes functional from imperative programming, your ‘assignable’ in an imperative program also may have a type placing a bound on its variability.
The only non-muddled definition I currently appreciate for functional programming is a) functions as first-class objects and types, b) preference for recursion over loops, and/or c) pure functions— i.e. those functions which do not impact the desired semantics of the program when memoized (thus perfectly pure functional programming doesn't exist in a general purpose denotational semantics due to impacts of operational semantics, e.g. memory allocation).
The idempotent property of a pure function means the function call on its variables can be substituted by its value, which is not generally the case for the arguments of an imperative procedure. Pure functions seem to be declarative w.r.t. to the uncomposed state transitions between the input and result types.
But the composition of pure functions does not maintain any such consistency, because it is possible to model a side-effect (global state) imperative process in a pure functional programming language, e.g. Haskell's IOMonad and moreover it is entirely impossible to prevent doing such in any Turing complete pure functional programming language.
As I wrote in 2012 which seems to the similar consensus of comments in your recent blog, that declarative programming is an attempt to capture the notion that the intended semantics are never opaque. Examples of opaque semantics are dependence on order, dependence on erasure of higher-level semantics at the operational semantics layer (e.g. casts are not conversions and reified generics limit higher-level semantics), and dependence on variable values which can not be checked (proved correct) by the programming language.
Thus I have concluded that only non-Turing complete languages can be declarative.
Thus one unambiguous and distinct attribute of a declarative language could be that its output can be proven to obey some enumerable set of generative rules. For example, for any specific HTML program (ignoring differences in the ways interpreters diverge) that is not scripted (i.e. is not Turing complete) then its output variability can be enumerable. Or more succinctly an HTML program is a pure function of its variability. Ditto a spreadsheet program is a pure function of its input variables.
So it seems to me that declarative languages are the antithesis of unbounded recursion, i.e. per Gödel's second incompleteness theorem self-referential theorems can't be proven.
Lesie Lamport wrote a fairytale about how Euclid might have worked around Gödel's incompleteness theorems applied to math proofs in the programming language context by to congruence between types and logic (Curry-Howard correspondence, etc).
Most of the answers seem to be for svn+ssh, or don't seem to work for us.
For http access, the easiest way to log out an SVN user from the command line is:
rm ~/.subversion/auth/svn.simple/*
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
Try this https://github.com/devashish234073/Java-Socket-Http-Server/blob/master/README.md
This API has creates an HTTP server using sockets.
For example the here's how the constructor in the Response.java
class converts a raw response into an http response:
public Response(String resp){
Date date = new Date();
String start = "HTTP/1.1 200 OK\r\n";
String header = "Date: "+date.toString()+"\r\n";
header+= "Content-Type: text/html\r\n";
header+= "Content-length: "+resp.length()+"\r\n";
header+="\r\n";
this.resp=start+header+resp;
}
you can try to use cv2 like this
import cv2
image= cv2.imread('image page')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Well i don't have an appropriate reason regarding why this behavior occurs but then i just found a small work around
Inside the VirtualEnvironment
pip install -Iv package_name==version_number
now this will install the version in your virtual environment
Additionally you can check inside the virtual environment with this
pip install yolk
yolk -l
This shall give you the details of all the installed packages in both the locations(system and virtualenv)
While some might say its not appropriate to use --system-site-packages (it may be true), but what if you have already done a lot of stuffs inside your virtualenv? Now you dont want to redo everything from the scratch.
You may use this as a hack and be careful from the next time :)
To get the column names from pandas dataframe in python3- Here I am creating a data frame from a fileName.csv file
>>> import pandas as pd
>>> df = pd.read_csv('fileName.csv')
>>> columnNames = list(df.head(0))
>>> print(columnNames)
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
create procedure dbo.PrintMax @text nvarchar(max) as begin declare @i int, @newline nchar(2), @print varchar(max); set @newline = nchar(13) + nchar(10); select @i = charindex(@newline, @text); while (@i > 0) begin select @print = substring(@text,0,@i); while (len(@print) > 8000) begin print substring(@print,0,8000); select @print = substring(@print,8000,len(@print)); end print @print; select @text = substring(@text,@i+2,len(@text)); select @i = charindex(@newline, @text); end print @text; end
Using only standard python libs:
from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()
Works on Windows (if you are on drive C), Mac or Linux
Alternatively, you could remove one line with an immediate invocation:
from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
You have to bind your methods with 'this' (default object). So whatever your function may be just bind that in the constructor.
constructor(props) {
super(props);
this.state = { checked:false };
this.handleChecked = this.handleChecked.bind(this);
}
handleChecked(){
this.setState({
checked: !(this.state.checked)
})
}
render(){
var msg;
if(this.state.checked){
msg = 'checked'
}
else{
msg = 'not checked'
}
return (
<div>
<input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
<h3>This is {msg}</h3>
</div>
);
a = np.subtract(a, 0., dtype=np.float32)
This change worked for me:
// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width;
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);
Select
DISTINCT t1.col,t2col
From table1 t1, table2 t2
OR
Select
DISTINCT t1.col,t2col
From table1 t1
cross JOIN table2 t2
if its hug data , its take long time ..
Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object
If using ES6:
function yourFunction(args){
let defaults = {opt1: true, opt2: 'something'};
let params = {...defaults, ...args}; // right-most object overwrites
console.log(params.opt1);
}
Older Browsers using Object.assign(target, source):
function yourFunction(args){
var defaults = {opt1: true, opt2: 'something'};
var params = Object.assign(defaults, args) // args overwrites as it is source
console.log(params.opt1);
}
I think I found a workaround for you guys if you're still interested. This is my first week, but it worked for me...
<div class="contentScroller">
<div class="content">
</div>
</div>
.contentScroller {overflow-y: auto; visibility: hidden;}
.content {visibility: visible;}
To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:
./mysql --version
Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.
After adding the mysql bin dir to your $PATH, verify it's there by executing:
echo $PATH
Thereafter you can check your mysql version from anywhere by running (note no "./"):
mysql --version
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
[AllowCrossSiteJson]
public ActionResult YourMethod()
{
return Json("Works better?");
}
using System;
using System.Web.Http.Filters;
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
base.OnActionExecuted(actionExecutedContext);
}
}
[AllowCrossSiteJson]
public class ValuesController : ApiController
{
[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
...
}
IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).
Download it using nuget corsproxy
and follow the included instructions.
I think I know the reason for this exception. You might be running this code snippet in multiple threads.
One of the simple way of using NullSafe Comparator is to use Spring implementation of it, below is one of the simple example to refer :
public int compare(Object o1, Object o2) {
ValidationMessage m1 = (ValidationMessage) o1;
ValidationMessage m2 = (ValidationMessage) o2;
int c;
if (m1.getTimestamp() == m2.getTimestamp()) {
c = NullSafeComparator.NULLS_HIGH.compare(m1.getProperty(), m2.getProperty());
if (c == 0) {
c = m1.getSeverity().compareTo(m2.getSeverity());
if (c == 0) {
c = m1.getMessage().compareTo(m2.getMessage());
}
}
}
else {
c = (m1.getTimestamp() > m2.getTimestamp()) ? -1 : 1;
}
return c;
}
On my machine:
C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data
The problem you are having is the query command is taking too long. I believe that the default timeout for a query to execute is 15 seconds. You need to set the CommandTimeout (in seconds) so that it is long enough for the command to complete its execution. The "CommandTimeout" is different than the "Connection Timeout" in your connection string and must be set for each command.
In your sql Selecting Event, use the command:
e.Command.CommandTimeout = 60
for example:
Protected Sub SqlDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
e.Command.CommandTimeout = 60
End Sub
And just to give you yet another option, you can use NOT ISNULL(archived)
as your WHERE filter.
Laravel 5.7 introduced the following functionality:
Auth::routes(['register' => false]);
The currently possible options here are:
Auth::routes([
'register' => false, // Registration Routes...
'reset' => false, // Password Reset Routes...
'verify' => false, // Email Verification Routes...
]);
For older Laravel versions just override showRegistrationForm()
and register()
methods in
AuthController
for Laravel 5.0 - 5.4Auth/RegisterController.php
for Laravel 5.5public function showRegistrationForm()
{
return redirect('login');
}
public function register()
{
}
You need to use html helper, and you don't need to provide date format in model class. e.x :
@Html.TextBoxFor(m => m.ResgistrationhaseDate, "{0:dd/MM/yyyy}")
In > Swift 2.2, I've combined few answers here.
Make an outlet from storyboard to link to your staticCell.
@IBOutlet weak var updateStaticCell: UITableViewCell!
override func viewDidLoad() {
...
updateStaticCell.hidden = true
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 0
} else {
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
I want to hide my first cell so I set the height to 0 as described above.
Reading it columnwise is harder?
Anyway this reads the line and stores the values in a list:
for line in open("csvfile.csv"):
csv_row = line.split() #returns a list ["1","50","60"]
Modern solution:
# pip install pandas
import pandas as pd
df = pd.read_table("csvfile.csv", sep=" ")
If you wish to open the batch file in another window, use start
. This way, you can basically run two scripts at the same time. In other words, you don't have to wait for the script you just called to finish.
All examples below work:
start batch.bat
start call batch.bat
start cmd /c batch.bat
If you want to wait for the script to finish, try start /w call batch.bat
, but the batch.bat has to end with exit
.
As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.
Another variation is to split the pipe, and then re-direct the output as you like.
@echo off
for /f "tokens=1,* delims=:" %%P in ('findstr /n "^"') do (
echo(%%Q
echo(%%Q>&3
)
@exit/b %errorlevel%
Save the above to a .bat file. It splits text output on filestream 1 to filestream 3 also, which you can redirect as needed. In my examples below, I called the above script splitPipe.bat ...
dir | splitPipe.bat 1>con 2>&1 3>my_stdout.log
splitPipe.bat 2>nul < somefile.txt
You must use require_once() function.
here's an updated version, not using deprecated methods, based upon @danh32's answer:
protected int getScale(Double contentWidth) {
if(this.getActivity() != null) {
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
Double val = displaymetrics.widthPixels / contentWidth * 100d;
return val.intValue();
} else {
return 100;
}
}
to be used alike:
int initialScale = this.getScale(420d);
this.mWebView.setInitialScale(initialScale);
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
$('#mytextbox').keydown(function (e) {
if (e.keyCode == 13) {
if (e.altKey) {
alert("alt is pressed");
}
}
});
if you press alt + enter, you will see the alert.
Do not mix CSS/JQuery syntax (#
for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
In my case, I had to remove it with
rm -r /var/lib/docker/containers/<container-id>/
and it worked. Maybe that's how you solve it in docker version ~19. My docker version was 19.03.12
,
I have met with the exact same problem.
And it turns out that the configuration file generated by gradle asks for java1.7.
While my system has java1.8 installed.
After modifying the compiler compliance level to 1.8. All things are working as expected.
Do you mean Delegate.Invoke
/BeginInvoke
or Control.Invoke
/BeginInvoke
?
Delegate.Invoke
: Executes synchronously, on the same thread.Delegate.BeginInvoke
: Executes asynchronously, on a threadpool
thread.Control.Invoke
: Executes on the UI thread, but calling thread waits for completion before continuing.Control.BeginInvoke
: Executes on the UI thread, and calling thread doesn't wait for completion.Tim's answer mentions when you might want to use BeginInvoke
- although it was mostly geared towards Delegate.BeginInvoke
, I suspect.
For Windows Forms apps, I would suggest that you should usually use BeginInvoke
. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person
with FirstName
and LastName
properties, and you did:
person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";
Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)
Unless you have this sort of issue, however, Control.BeginInvoke
is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke
in a "fire and forget" manner - i.e. without ever calling EndInvoke
. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.
This is a common issue when attempting to 'bubble' up data from a chain of stored procedures. A restriction in SQL Server is you can only have one INSERT-EXEC active at a time. I recommend looking at How to Share Data Between Stored Procedures which is a very thorough article on patterns to work around this type of problem.
For example a work around could be to turn Sp3 into a Table-valued function.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Maybe you don't have a language file:
Language files are here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n
A new localization should be created in a separate JavaScript file named ui.datepicker-.js. Within a document.ready event it should add a new entry into the $.datepicker.regional array, indexed by the language code, with the following attributes:
I use stress for this kind of thing, you can tell it how many cores to max out.. it allows for stressing memory and disk as well.
Example to stress 2 cores for 60 seconds
stress --cpu 2 --timeout 60
Variables are comprised of fields and non-fields.
Fields can be either:
Non-fields can be either:
In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.
Basic Example (excuse me for my syntax, I am just a beginner)
Class {
//fields
method1 {
//non-fields
}
}
There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do
conda create -n python2 python=2.7 anaconda
This will create an environment named python2
that contains the Python 2.7 version of Anaconda. You can activate this environment with
source activate python2
This will put that environment (typically ~/anaconda/envs/python2
) in front in your PATH
, so that when you type python
at the terminal it will load the Python from that environment.
If you don't want all of Anaconda, you can replace anaconda
in the command above with whatever packages you want. You can use conda
to install packages in that environment later, either by using the -n python2
flag to conda
, or by activating the environment.
Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type
sudo dnf install maven
Now test the installation, just run maven in a random directory
mvn
And it will fail, because you did not specify a goal, e.g. mvn package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.102 s
[INFO] Finished at: 2017-11-14T13:45:00+01:00
[INFO] Final Memory: 8M/176M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build
[...]
I had this issue for 2 days, let me show you how I fixed it.
This was how the code looked when I was getting the error:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.response);
console.log(data)
}
This is what I changed to get the result I wanted:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.responseText);
console.log(data)
}
So all I really did was change
this.response
to this.responseText
.
Create a method similar to String.format()
of Java
StringJoin=(s, r=[])=>{
r.map((v,i)=>{
s = s.replace('%'+(i+1),v)
})
return s
}
use
console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
I too was getting this error. (for which I googled and I was directed to this page)
Problem: I was calling a static method defined in the class of a project A from a class defined in another project B. I was getting the following error:
error: cannot find symbol
Solution: I resolved this by first building the project where the method is defined then the project where the method was being called from.
Edit /etc/sudoers
file either manually or using the visudo application.
Remember: System reads /etc/sudoers
file from top to the bottom, so you could overwrite a particular setting by putting the next one below.
So to be on the safe side - define your access setting at the bottom.
You can select the form like this:
$("#submit").click(function(){
var form = $(this).parents('form:first');
...
});
However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});
To select fields inside the form, use the form context. For example:
$("input[name='somename']",form).val();
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
<div class="container-fluid login-container">
<div class="row">
<form (ngSubmit)="login('da')">
<div class="col-md-4">
<div class="login-text">
Login
</div>
<div class="form-signin">
<input type="text" class="form-control" placeholder="Email" required>
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="col-md-4">
<div class="login-go-div">
<input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
</div>
</div>
</form>
</div>
</div>
This is the working code for it.
If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.
jpanel1.setVisible(false);
The way to do it is with ternary operator:
name = city.getName() == null ? city.getName() : "N/A"
However, I believe you have a typo in your code above, and you mean to say:
if (city.getName() != null) ...
do you mean something like pgAdmin for administration?
Creating a table and copying the data in a single command:
create table T_NEW as
select * from T;
* This will not copy PKs, FKs, Triggers, etc.
By default, the datetime
object is naive
in Python, so you need to make both of them either naive or aware datetime
objects. This can be done using:
import datetime
import pytz
utc=pytz.UTC
challenge.datetime_start = utc.localize(challenge.datetime_start)
challenge.datetime_end = utc.localize(challenge.datetime_end)
# now both the datetime objects are aware, and you can compare them
Note: This would raise a ValueError
if tzinfo
is already set. If you are not sure about that, just use
start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)
BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following
d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
year=d.year,
month=d.month,
day=d.day,
hour=d.hour,
minute=d.minute,
second=d.second,
tzinfo=pytz.UTC)
In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.
In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).
A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.
Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).
Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.
Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse
and JSON.stringify
). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.
If you want to split by values in one of the columns, you can use lapply
. For instance, to split ChickWeight
into a separate dataset for each chick:
data(ChickWeight)
lapply(unique(ChickWeight$Chick), function(x) ChickWeight[ChickWeight$Chick == x,])
This will give you a list.
List<Card> cardsList = Arrays.asList(hand);
If you want an arraylist, you can do
ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
If your regex includes a variable, make sure to escape it.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
This can be used like this
new RegExp(escapeRegExp(searchString), 'i')
Or in a mongoDb query like this
{ '$regex': escapeRegExp(searchString) }
Posted same comment here
window_handles
should give you the references to all open windows.
this is what the docu has to say about switching windows.
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
If you throw a new exception with the initial exception you will preserve the initial stack trace too..
try{
}
catch(Exception ex){
throw new MoreDescriptiveException("here is what was happening", ex);
}
cv2
uses numpy
for manipulating images, so the proper and best way to get the size of an image is using numpy.shape
. Assuming you are working with BGR images, here is an example:
>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
600 800 3
In case you were working with binary images, img
will have two dimensions, and therefore you must change the code to: height, width = img.shape
Powerful tool for "Bulletproof Email Background Images" (VML for Outlook 2007/2010/2013, and HTML/CSS for Outlook 2000/2003, Gmail, Hotmail...)
as an exemple :
<div style="background-color:#f6f6f6;">
<!--[if gte mso 9]>
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
<v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
</v:background>
<![endif]-->
<table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td valign="top" align="left" background="http://i.imgur.com/n8Q6f.png">
</td>
</tr>
</table>
</div>
in order to have the specified background image to Full email body.
This link help to use the Vector Markup Language (VML)
try{
int year = Integer.parseInt(new Date().toString().split("-")[0]);
}
catch(NumberFormatException e){
}
Much of Date is deprecated.
use this, it won't effect height:
<input type="text" style="border:1px solid #ff0000" />
Try this:
subset(studentdata, Drink=='water')
that should do it.
Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.
Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.
The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.
Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.
In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
You have to remove the IMEX=1 if you want to update. ;)
"IMEX=1; tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative." https://www.connectionstrings.com/excel/
Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor()
. Direct to the point check this out!
function digitCount ( num )
{
return Math.floor( num.toString()).length;
}
digitCount(2343) ;
// ES5+
const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;
console.log(digitCount2(3343))
Basically What's going on here. toString()
and String()
same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length
.
Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs()
in it;
Cheer You!
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
In Angular 8 you can simply use "selectionChange" like this:
<mat-select [(value)]="selectedData" (selectionChange)="onChange()" >
<mat-option *ngFor="let i of data" [value]="i.ItemID">
{{i.ItemName}}
</mat-option>
</mat-select>
When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport
tag:
<binding name="MyServiceBinding">
<security defaultAlgorithmSuite="Basic256Rsa15"
authenticationMode="MutualCertificate" requireDerivedKeys="true"
securityHeaderLayout="Lax" includeTimestamp="true"
messageProtectionOrder="SignBeforeEncrypt"
messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSignatureConfirmation="false">
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
<secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="4096"
maxNameTableCharCount="16384"/>
</textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
requireClientCertificate="false" />
</binding>
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
If you would like to get the same information given when an exception isn't handled you can do something like this. Do import traceback
and then:
try:
...
except Exception as e:
print(traceback.print_tb(e.__traceback__))
I'm using Python 3.7.
The best and easiest way to set a button dynamically is
Button index=new Button(this);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());
The above height and width are in pixels px. 45 being the height in dp and 42 being the width in dp.
index.setLayoutParams(new <Parent>.LayoutParams(width, height));
So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams
index.setLayoutParams(new TableRow.LayoutParams(width, height));
I would not unit test code I don't own. What are you testing here, that the MSFT compiler works?
That said, to make this code testable, you almost HAVE to make your data access layer separate from your business logic code. What I do is take all of my EF stuff and put it in a (or multiple) DAO or DAL class which also has a corresponding interface. Then I write my service which will have the DAO or DAL object injected in as a dependency (constructor injection preferably) referenced as the interface. Now the part that needs to be tested (your code) can easily be tested by mocking out the DAO interface and injecting that into your service instance inside your unit test.
//this is testable just inject a mock of IProductDAO during unit testing
public class ProductService : IProductService
{
private IProductDAO _productDAO;
public ProductService(IProductDAO productDAO)
{
_productDAO = productDAO;
}
public List<Product> GetAllProducts()
{
return _productDAO.GetAll();
}
...
}
I would consider live Data Access Layers to be part of integration testing, not unit testing. I have seen guys run verifications on how many trips to the database hibernate makes before, but they were on a project that involved billions of records in their datastore and those extra trips really mattered.
there is a list of commad that you can use but for vs code use this
git config --global core.editor "code --wait"
this is the link for all editor :https://git-scm.com/book/en/v2/Appendix-C%3A-Git-Commands-Setup-and-Config
Actually, upon further reading on the file_get_contents()
function:
// Create a stream
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
]
];
// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$file = file_get_contents('http://www.example.com/', false, $context);
You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)
For Windows Vista/7/8/10, you can create a symlink instead via mklink
.
Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");
Alternatively, call CreateSymbolicLink
via P/Invoke.
If you wish to get the innerhtml of the class without the zend you could use this:
$dom = new DomDocument();
$dom->load($filePath);
$classname = 'main-article';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$tmp_dom = new DOMDocument();
foreach ($nodes as $node)
{
$tmp_dom->appendChild($tmp_dom->importNode($node,true));
}
$innerHTML.=trim($tmp_dom->saveHTML());
echo $innerHTML;
A String
is an immutable object which means the value cannot be changed whereas StringBuffer
is mutable.
The StringBuffer
is Synchronized hence thread-safe whereas StringBuilder
is not and suitable for only single-threaded instances.
If you are using Anaconda's Python distribution,
you can install it through pip
pip install setuptools
and then execute it as a module
python -m easy_install
just seperate the class name with a comma.
.a,.b{
your styles
}
I would avoid rolling your own and use either:
System.Web.Script.JavascriptSerializer
or
Both will do an excellent job :)
Create in your Site.css (or in another place) a new class named for example .font-bold and set it to your element
.font-bold {
font-weight: bold;
}
You can use tic
and toc
from ttictoc
. Install it with
pip install ttictoc
And just import them in your script as follow
from ttictoc import tic,toc
tic()
# Some code
print(toc())
Here is a ridiculously brute force answer:
I modified the gradlew script. Here is my new exec command at the end of the file in the
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" **| grep -v "libpng warning:"**
I assume that what you want is a tooltip. The easiest way to do this is to append an svg:title
element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something like
vis.selectAll("circle")
.data(datafiltered).enter().append("svg:circle")
...
.append("svg:title")
.text(function(d) { return d.x; });
If you want fancier tooltips, you could use tipsy for example. See here for an example.
You can use the Sum
function, but you'll have to convert the strings to integers, like so:
int total = monValues.Sum(x => Convert.ToInt32(x));
If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.
DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);
var itemsFiltered = allItems.Where(x=>
(x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
(x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
(intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
(intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);
you can simply use :
error_log("your message");
By default, the message will be send to the php system logger.
You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']
. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.
Site 1
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';
Includes under site one would be at:
echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';
Site 2
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';
The actual code to access includes from site1 inside of site2 you would say:
include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');
It will only use the relative path of the file executing the query if you try to access it by excluding the document root
and the root
slash:
//(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');
Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.
Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:
<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>
You should use:
<a href='/contact/'>Contact</a>
For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt
file for ONLY site1:
User-agent: *
Disallow: /blog/
Look up your IP address and include this snippet of code:
function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';
if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}
if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}
Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.
If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:
if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}
In my case we are migration multimodule application to Spring Boot. Unfortunately maven didnt execute all tests anymore in the modules. The naming of the Test Classes didnt change, we are following the naming conventions.
At the end it helped, when I added the dependency surefire-junit47
to the plugin maven-surefire-plugin
. But I could not explain, why, it was trial and error:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>${maven-surefire-plugin.version}</version>
</dependency>
</dependencies>
the solution: for type entity use option "data" but value is a object. ie:
$em = $this->getDoctrine()->getEntityManager();
->add('sucursal', 'entity', array
(
'class' => 'TestGeneralBundle:Sucursal',
'property'=>'descripcion',
'label' => 'Sucursal',
'required' => false,
'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)
))
In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.
Try removing package-lock.json file first
If you are running same app into multiple ports where app uses single database (h2), then add AUTO_SERVER=TRUE
in the url as follows:
jdbc:h2:file:C:/simple-commerce/price;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;AUTO_SERVER=TRUE
I installed opencv following the steps on https://docs.opencv.org/trunk/d7/d9f/tutorial_linux_install.html
Except on Step 2, use: cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=YES -D CMAKE_INSTALL_PREFIX=/path/to/opencv/ ..
Then locate the opencv4.pc file, mine was in opencv/build/unix-install/
Now run: $ export PKG_CONFIG_PATH=/path/to/the/file
You can listen resize
event and fire where some dimension change
directive
(function() {
'use strict';
angular
.module('myApp.directives')
.directive('resize', ['$window', function ($window) {
return {
link: link,
restrict: 'A'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
function onResize(){
// uncomment for only fire when $window.innerWidth change
// if (scope.width !== $window.innerWidth)
{
scope.width = $window.innerWidth;
scope.$digest();
}
};
function cleanUp() {
angular.element($window).off('resize', onResize);
}
angular.element($window).on('resize', onResize);
scope.$on('$destroy', cleanUp);
}
}]);
})();
In html
<div class="row" resize> ,
<div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod">
<h4 ng-bind="::v.known_as"></h4>
</div>
</div>
Controller :
$scope.$watch('width', function(old, newv){
console.log(old, newv);
})
You can also use jQuery - is(selector) Method:
var lastOpenSite = $(this).siblings().is(':not(.closedTab)');
You can use
window.top
see the following.
<head>
<script>
function abc() {
alert("sss");
}
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="window.top.abc();" href="#">Click Me</a>
</iframe>
</body>
If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.
From MySQL 5.7 Reference Manual.
Syntax :
ALTER TABLE t1 CHANGE a b DATATYPE;
e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.
And we want to change customercity TO customer_city :
alter table customer change customercity customer_city VARCHAR(225);
Use the pow(x,y) function: See Here
Just include math.h and you're all set.
Of course, I was misunderstanding the problem. As AWS themselves put it:
For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling
context.done()
in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.
I was calling context.done
way before any callbacks for the request fired, causing the termination of my function ahead of time.
The working code is this:
var http = require('http');
exports.handler = function(event, context) {
console.log('start request to ' + event.url)
http.get(event.url, function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
console.log('end request to ' + event.url);
}
Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.
function(event, context, callback)
Although you will still find the succeed
, done
and fail
on the context parameter, AWS suggest to use the callback
function instead or null
is returned by default.
callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok
Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
Boolean("true") will do the work too
No, absolutely not - because if acct
is null, it won't even get to isEmpty
... it will immediately throw a NullPointerException
.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of &&
here, rather than your ||
in the previous code; also note how in your previous code, your conditions were wrong anyway - even with &&
you would only have entered the if
body if acct
was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME)
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
int id();
}
Based up the OP's original request to be able to called a stored proc like this...
using (Entities context = new Entities())
{
context.MyStoreadProcedure(Parameters);
}
Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....
using (testentities te = new testentities())
{
//-------------------------------------------------------------
// Simple stored proc
//-------------------------------------------------------------
var parms1 = new testone() { inparm = "abcd" };
var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
var r1 = results1.ToList<TestOneResultSet>();
}
... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...
[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
[TestMethod]
public void GetTenantForName_ReturnsOneRecord()
{
// ARRANGE
const int expectedCount = 1;
const string expectedName = "Me";
// Build the paraemeters object
var parameters = new GetTenantForTenantNameParameters
{
TenantName = expectedName
};
// get an instance of the stored procedure passing the parameters
var procedure = new GetTenantForTenantNameProcedure(parameters);
// Initialise the procedure name and schema from procedure attributes
procedure.InitializeFromAttributes();
// Add some tenants to context so we have something for the procedure to return!
AddTenentsToContext(Context);
// ACT
// Get the results by calling the stored procedure from the context extention method
var results = Context.ExecuteStoredProcedure(procedure);
// ASSERT
Assert.AreEqual(expectedCount, results.Count);
}
}
internal class GetTenantForTenantNameParameters
{
[Name("TenantName")]
[Size(100)]
[ParameterDbType(SqlDbType.VarChar)]
public string TenantName { get; set; }
}
[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
: StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
public GetTenantForTenantNameProcedure(
GetTenantForTenantNameParameters parameters)
: base(parameters)
{
}
}
If either of those two approaches are any good?
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
h is used for AM/PM times (1-12).
H is used for 24 hour times (1-24).
a is the AM/PM marker
m is minute in hour
Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.
Looks like basically everyone beat me to it already, but I digress
Netbeans hints:
You get code completion on $users[0]->
and for $this->
for an array of User classes.
/**
* @var User[]
*/
var $users = array();
You also can see the type of the array in a list of class members when you do completion of $this->...
If a caching system correctly implements no-store, then you wouldn't need no-cache. But not all do. Additionally, some browsers implement no-cache like it was no-store. Thus, while not strictly required, it's probably safest to include both.