If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
Change the node to and create a file, packages.xsd, in the same folder (and include it in the project) with the following contents:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="urn:packages" xmlns="urn:packages">
<xs:element name="packages">
<xs:complexType>
<xs:sequence>
<xs:element name="package" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" use="required" />
<xs:attribute name="targetFramework" type="xs:string" use="optional" />
<xs:attribute name="allowedVersions" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
It is possible using ConfigTransform
build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/
All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.
The same applies to "app.*.config" transform files in non-web projects.
and then adding the following target to your *.csproj
.
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.
Using sn.exe utility:
sn -T YourAssembly.dll
or loading the assembly in Reflector.
If you want to add the string value to a button for example, simple use
android:text="@string/NameOfTheString"
The defined text in strings.xml looks like this:
<string name="NameOfTheString">Test string</string>
The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.
If you want to avoid this problem then use a more appropriate data type. decimal
will do what you want:
Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)
Result: 0.58
The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).
Edit to add:
Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875
You can see from this why rounding give 0.57.
If you just want to get the first decimal value, the solution is really simple.
Here's an explanatory example:
int leftSideOfDecimalPoint = (int) initialFloatValue; // The cast from float to int keeps only the integer part
int temp = (int) initialFloatValue * 10;
int rightSideOfDecimalPoint = temp % 10;
Say for example we have an initial float value of 27.8 .
This technique can then be used to get the following decimal characters by using for example 100 instead of 10, and so on.
Just take note that if you use this technique on real-time systems, for example to display it on a 7-segment display, it may not work properly because we are multiplying with a float value, where multiplication takes a lot of overhead time.
If you for example want the icon of glyphicon-chevron-left
Try adding class="glyphicon glyphicon-chevron-left"
Ok so if I understand well you're trying to get a random string password which contains 5 letters and 3 numbers randomly positioned and so which has a length of 8 characters and you accept maj and min letters, you can do that with the following function:
function randPass(lettersLength,numbersLength) {
var j, x, i;
var result = '';
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var numbers = '0123456789';
for (i = 0; i < lettersLength; i++ ) {
result += letters.charAt(Math.floor(Math.random() * letters.length));
}
for (i = 0; i < numbersLength; i++ ) {
result += numbers.charAt(Math.floor(Math.random() * numbers.length));
}
result = result.split("");
for (i = result.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = result[i];
result[i] = result[j];
result[j] = x;
}
result = result.join("");
return result
}
function randPass(lettersLength,numbersLength) {_x000D_
var j, x, i;_x000D_
var result = '';_x000D_
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';_x000D_
var numbers = '0123456789';_x000D_
for (i = 0; i < lettersLength; i++ ) {_x000D_
result += letters.charAt(Math.floor(Math.random() * letters.length));_x000D_
}_x000D_
for (i = 0; i < numbersLength; i++ ) {_x000D_
result += numbers.charAt(Math.floor(Math.random() * numbers.length));_x000D_
}_x000D_
result = result.split("");_x000D_
for (i = result.length - 1; i > 0; i--) {_x000D_
j = Math.floor(Math.random() * (i + 1));_x000D_
x = result[i];_x000D_
result[i] = result[j];_x000D_
result[j] = x;_x000D_
}_x000D_
result = result.join("");_x000D_
return result_x000D_
}_x000D_
console.log(randPass(5,3))
_x000D_
I use if (ptr)
, but this is completely not worth arguing about.
I like my way because it's concise, though others say == NULL
makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.
I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)
Note in C++0x, we can do if (ptr == nullptr)
, which to me does read nicer. (Again, I hate the macro. But nullptr
is nice.) I still do if (ptr)
, though, just because it's what I'm used to.
My solution in code behind was:
System.Web.UI.WebControls.FileUpload fileUpload;
I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.
You can also get this error by prematurely taking PyCharm's advice to annotate a method @staticmethod. Remove the annotation.
svn merge -r 1944:1943 .
should revert the changes of r1944 in your working copy. You can then review the changes in your working copy (with diff), but you'd need to commit in order to apply the revert into the repository.
If you are not using Math.round() function the solution suggested by Dr.Molle will not work in some cases when a browser window has a zoom.
For example $(this).scrollTop() + $(this).innerHeight() = 600
$(this)[0].scrollHeight yields = 599.99998
600 >= 599.99998 fails.
Here is the correct code:
jQuery(function($) {
$('#flux').on('scroll', function() {
if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
alert('end reached');
}
})
});
You may also add some extra margin pixels if you do not need a strict condition
var margin = 4
jQuery(function($) {
$('#flux').on('scroll', function() {
if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
alert('end reached');
}
})
});
public static boolean deleteDirectory(File path) {
// TODO Auto-generated method stub
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return(path.delete());
}
This Code will Help you.. And In Android Manifest You have to get Permission to make modification..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Consider such a solution without a need to define the third variable:
function swap(arr, from, to) {_x000D_
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);_x000D_
}_x000D_
_x000D_
var letters = ["a", "b", "c", "d", "e", "f"];_x000D_
_x000D_
swap(letters, 1, 4);_x000D_
_x000D_
console.log(letters); // ["a", "e", "c", "d", "b", "f"]
_x000D_
Note: You may want to add additional checks for example for array length. This solution is mutable so swap
function does not need to return a new array, it just does mutation over array passed into.
Why not just extend the Android CheckBox to have better padding instead. That way instead of having to fix it in code every time you use the CheckBox you can just use the fixed CheckBox instead.
First Extend CheckBox:
package com.whatever;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;
/**
* This extends the Android CheckBox to add some more padding so the text is not on top of the
* CheckBox.
*/
public class CheckBoxWithPaddingFix extends CheckBox {
public CheckBoxWithPaddingFix(Context context) {
super(context);
}
public CheckBoxWithPaddingFix(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CheckBoxWithPaddingFix(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public int getCompoundPaddingLeft() {
final float scale = this.getResources().getDisplayMetrics().density;
return (super.getCompoundPaddingLeft() + (int) (10.0f * scale + 0.5f));
}
}
Second in your xml instead of creating a normal CheckBox create your extended one
<com.whatever.CheckBoxWithPaddingFix
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello there" />
Variables can contain single quotes.
myvar=\'....$variable\'
repo forall -c $myvar
I was having the same problem, and solved it by replacing Manifest.permission.READ_PHONE_STATE with android.Manifest.permission.READ_PHONE_STATE.
We can also do this using randint.
from random import randint
l= ['a','b','c']
def get_rand_element(l):
if l:
return l[randint(0,len(l)-1)]
else:
return None
get_rand_element(l)
Something like this should work:
sh -c 'cd /tmp && exec pwd'
Value of %TEMP%
environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM
, LOCALSYSTEM
or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP%
variable explicitly, Windows may use c:\temp
or even c:\windows\temp
folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!
Same problem with Chrome : I had in my html page the following code :
<body>
...
<script src="http://myserver/lib/load.js"></script>
...
</body>
But the load.js
was always in status pending
when looking in the Network pannel.
I found a workaround using asynchronous load of load.js
:
<body>
...
<script>
setTimeout(function(){
var head, script;
head = document.getElementsByTagName("head")[0];
script = document.createElement("script");
script.src = "http://myserver/lib/load.js";
head.appendChild(script);
}, 1);
</script>
...
</body>
Now its working fine.
The simplest solution what works for me is to store the data as json_encode.
later when you retrieve just make sure you json_decode it.
Here you don't have to change the collation or the character set of the database and the table.
You can delete the browser cache by setting these headers:
<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
Try to execute below command in your terminal :
mysql -h localhost -P 3306 -u root -p
If you successfully connect to your database, then same thing has to happen with Mysql Workbench
.
If you are unable to connect then I think 3306
port is acquired by another process.
Find which process running on 3306
port. If required, give admin privileges using sudo
.
netstat -lnp | grep 3306
Kill/stop that process and restart your MySQL server. You are good to go.
Execute below command to find my.cnf
file in macbook.
mysql --help | grep cnf
You can change MySQL
port to any available port in your system. But after that, make sure you restart MySQL
server.
This was my scenario:
for i in generate_numbers():
do_something(i)
# Use the last i.
I can’t easily determine the length of the iterable, and that means that i
may or may not exist depending on whether the iterable produces an empty sequence.
If I want to use the last i
of the iterable (an i
that doesn’t exist for an empty sequence) I can do one of two things:
i = None # Declare the variable.
for i in generate_numbers():
do_something(i)
use_last(i)
or
for i in generate_numbers():
do_something(i)
try:
use_last(i)
except UnboundLocalError:
pass # i didn’t exist because sequence was empty.
The first solution may be problematic because I can’t tell (depending on the sequence values) whether i
was the last element. The second solution is more accurate in that respect.
You can choose:
if [[ $? -ne 0 ]]; then # -ne: not equal
if ! [[ $? -eq 0 ]]; then # -eq: equal
if [[ ! $? -eq 0 ]]; then
!
inverts the return of the following expression, respectively.
Here is how you can do it :
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 3;
int y = 2;
Float fX = new Float(x);
float res = fX.floatValue()/y;
System.out.println("res = "+res);
}
See you !
Just use z-index
CSS property as described in the highest liked answer and the nav bar will stick to the top.
Example:
<div class="navigation">
<nav>
<ul>
<li>Home</li>
<li>Contact</li>
</ul>
</nav>
.navigation {
/* fixed keyword is fine too */
position: sticky;
top: 0;
z-index: 100;
/* z-index works pretty much like a layer:
the higher the z-index value, the greater
it will allow the navigation tag to stay on top
of other tags */
}
I think that the fastest way to do this is to just clone the node, which will remove all event listeners:
var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.
math.e
or from math import e
(= 2.718281…)
The two expressions math.exp(x)
and e**x
are equivalent
however:
Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x
or pow(math.e, x)
. docs.python
for power use **
(3**2
= 9), not " ^ "
" ^ " is a bitwise XOR operator (& and, | or), it works logicaly with bits.
So for example 10^4
=14 (maybe unexpectedly) ? consider the bitwise depiction:
(0000 1010 ^ 0000 0100 = 0000 1110) programiz
The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:
/*jshint -W106 */
save_state(id);
/*jshint +W106 */
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Above two answers are correct but didn't work for me.
docker container ls
docker container ls -a
and after that it showed all the process previously exited and running.docker stop <container id>
or docker container stop <container id>
didn't work docker rm -f <container id>
and it worked.docker container ls -a
and this process wasn't present.I added 40px-height .vspace
element holding the anchor before each of my h1
elements.
<div class="vspace" id="gherkin"></div>
<div class="page-header">
<h1>Gherkin</h1>
</div>
In the CSS:
.vspace { height: 40px;}
It's working great and the space is not chocking.
Use this
openssl ciphers -v | awk '{print $2}' | sort | uniq
Here are clarified instruction combining Dawn Song's answer and Marmor's answer.
Drag a long Press Gesture Recognizer and drop it into your Table Cell. It will jump to the bottom of the list on the left.
Then connect the gesture recognizer the same way you would connect a button.
Add the code from Marmor in the the action handler
- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {
CGPoint p = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell.isHighlighted) {
NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
}
}
}
}
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
If using Angular >= 1.4, here's the cleanest solution I've found that doesn't rely on anything custom or external:
angular.module('yourModule')
.config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});
And then you can do this anywhere in your app:
$http({
method: 'POST',
url: '/requesturl',
data: {
param1: 'value1',
param2: 'value2'
}
});
And it will correctly serialize the data as param1=value1¶m2=value2
and send it to /requesturl
with the application/x-www-form-urlencoded; charset=utf-8
Content-Type header as it's normally expected with POST requests on endpoints.
Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:
$rootScope.$digest()
-- i.e., check the full component tree$rootScope.$apply(callback)
-- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.$scope.$digest()
-- i.e., check only this component and its childrenYou will need to import and then inject ApplicationRef
, NgZone
, or ChangeDetectorRef
into your component.
For your particular scenario, I would recommend the last option if only a single component has changed.
*Please try the below codes
"250000".replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
Ans: 250,000
A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2]
, the code right now would scale that to have intensities of [0, 128, 255]
. You want these to remain small after converting to np.uint8
.
Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo
and provide it the type (dtype
) of the image and you will obtain a structure of information for that type. You would then access the max
field from this structure to determine the maximum value.
So with the above, do the following modifications to your code:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
Note that I've additionally converted the image into np.float64
in case the incoming data type is not so and to maintain floating-point precision when doing the division.
Or you can simply use OleDbDataAdapter to get data from Excel
You can see all of your activities (recently uploaded builds here). It will also provide current status of your build.
You can include a .js file which has the script to set the
window.location.href = url;
Where url would be the url you wish to load.
You can change the tint, quite easily in code via:
imageView.setColorFilter(Color.argb(255, 255, 255, 255));
// White Tint
If you want color tint then
imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);
For Vector Drawable
imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);
UPDATE:
@ADev has newer solution in his answer here, but his solution requires newer support library - 25.4.0 or above.
I'd like to clarify a few things:
pandas.Series.tolist()
. I'm not sure why the top voted answer
leads off with using pandas.Series.values.tolist()
since as far as I can tell, it adds syntax/confusion with no added benefit.tst[lookupValue][['SomeCol']]
is a dataframe (as stated in the
question), not a series (as stated in a comment to the question). This is because tst[lookupValue]
is a dataframe, and slicing it with [['SomeCol']]
asks for
a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you
remove the extra set of brackets, as in
tst[lookupValue]['SomeCol']
, then you are asking for just that one
column rather than a list of columns, and thus you get a series back.pandas.Series.tolist()
, so you should
definitely skip the second set of brackets in this case. FYI, if you
ever end up with a one-column dataframe that isn't easily avoidable
like this, you can use pandas.DataFrame.squeeze()
to convert it to
a series.tst[lookupValue]['SomeCol']
is getting a subset of a particular column via
chained slicing. It slices once to get a dataframe with only certain rows
left, and then it slices again to get a certain column. You can get
away with it here since you are just reading, not writing, but
the proper way to do it is tst.loc[lookupValue, 'SomeCol']
(which returns a series).ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
Demo Code:
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
Result:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
Although the question is: How do I get control early enough to issue an error message and exit?
The question that I answer is: How do I get control early enough to issue an error message before starting the app?
I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.
I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.
Here is the DOS script with version 2.7:
@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF
This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.
The FOR /F
line is the key.
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17
And my hack version:
[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.
let's play a bit ;) :
import cv2
import numpy as np
>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168, 58, 2, 1], # uninitialized memory counts as random, too ? fun ;)
[ 0, 100, 2, 0, 101],
[ 0, 0, 106, 2, 0],
[131, 2, 0, 90, 3],
[ 0, 100, 1, 0, 83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99)) # normal
array([[ 0, 76, 0, 129, 0],
[ 0, 0, 0, 188, 27],
[ 0, 152, 0, 0, 0],
[ 0, 0, 134, 79, 0],
[ 0, 181, 36, 128, 0]], dtype=uint8)
>>> cv2.randu(im,(0),(99)) # uniform
array([[19, 53, 2, 86, 82],
[86, 73, 40, 64, 78],
[34, 20, 62, 80, 7],
[24, 92, 37, 60, 72],
[40, 12, 27, 33, 18]], dtype=uint8)
to apply it to an existing image, just generate noise in the desired range, and add it:
img = ...
noise = ...
image = img + noise
These are properties. You would use them like so:
Tom.Title = "Accountant";
string desc = Tom.Description;
But considering they are declared protected
their visibility may be a concern.
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables
I got the answer.
Here is the code:
SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Basically any file that is automatically regenerated.
A good test is to clone your repo and see if Android Studio is able to interpret and run your project immediately (generating what is missing).
If not, find what is missing, and make sure it isn't ignored, but added to the repo.
That being said, you can take example on existing .gitignore
files, like the Android one.
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
# Eclipse project files
.classpath
.project
# Proguard folder generated by Eclipse
proguard/
# Intellij project files
*.iml
*.ipr
*.iws
.idea/
Use re.sub
, like so:
>>> import re
>>> re.sub('\D', '', 'aas30dsa20')
'3020'
\D
matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.
Or you can use filter
, like so (in Python 2):
>>> filter(str.isdigit, 'aas30dsa20')
'3020'
Since in Python 3, filter
returns an iterator instead of a list
, you can use the following instead:
>>> ''.join(filter(str.isdigit, 'aas30dsa20'))
'3020'
As everyone mentioned, it might not be a good idea for layout purposes. I arrived to this question because I was wondering the same and I only wanted to know if it would be valid code.
Since it's valid, you can use it for other purposes. For example, what I'm going to use it for is to put some fancy "CSSed" divs inside table rows and then use a quick jQuery function to allow the user to sort the information by price, name, etc. This way, the only layout table will give me is the "vertical order", but I'll control width, height, background, etc of the divs by CSS.
The perfect solution which works undoubtedly is to just add these packages to your app:
https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.2
http://archive.apache.org/dist/logging/log4j/1.2.16/
after adding so you may encounter following WARNING which you can simply ignore!
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
body.bg {
background-size: cover;
background-repeat: no-repeat;
min-height: 100vh;
background: white url(../images/bg-404.jpg) center center no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
Try This
_x000D_
_x000D_
body.bg {_x000D_
background-size: cover;_x000D_
background-repeat: no-repeat;_x000D_
min-height: 100vh;_x000D_
background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
}
_x000D_
<body class="bg">_x000D_
_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_
Try this query
DECLARE @PrintVarchar nvarchar(max) = (Select Sum(Amount) From Expense)
PRINT 'Varchar format =' + @PrintVarchar
DECLARE @PrintInt int = (Select Sum(Amount) From Expense)
PRINT @PrintInt
You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:
double click the button and add write // this.close();
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
If you're using Rails 3.2 or Rails 4 you should use request.original_url
to get the current URL.
Documentation for the method is at http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url but if you're curious the implementation is:
def original_url
base_url + original_fullpath
end
type C:\temp\test.bat>C:\temp\test.log
you must clear the target file such as in jar and others In C: drive your folder at .m2 see the location where it install and delete the .jar file,Snaphot file and delete target files then clean the application you found it will be run
import java.util.*;
class ArrayLst
{
public static void main(String args[])
{
ArrayList<String> ar = new ArrayList<String>();
ar.add("pulak");
ar.add("sangeeta");
ar.add("sumit");
System.out.println("Enter the name:");
Scanner scan=new Scanner(System.in);
String st=scan.nextLine();
for(String lst: ar)
{
if(st.contains(lst))
{
System.out.println(st+"is here!");
break;
}
else
{
System.out.println("OOps search can't find!");
break;
}
}
}
}
update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which
/event.keyCode
and start using event.key
:
if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")
Like the accepted answer well explained by lhunath, you can use
command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
Beware than if you use bash you could have some issue.
Let me take the matthew-wilcoxson exemple.
And for those who "seeing is believing", a quick test:
(echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
Personally, when I try, I have this result :
user@computer:~$ (echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
user@computer:~$ Test Out
Test Err
Both message does not appear at the same level. Why Test Out
seem to be put like if it is my previous command ?
Prompt is on a blank line, let me think the process is not finished, and when I press Enter
this fix it.
When I check the content of the files, it is ok, redirection works.
Let take another test.
function outerr() {
echo "out" # stdout
echo >&2 "err" # stderr
}
user@computer:~$ outerr
out
err
user@computer:~$ outerr >/dev/null
err
user@computer:~$ outerr 2>/dev/null
out
Trying again the redirection, but with this function.
function test_redirect() {
fout="stdout.log"
ferr="stderr.log"
echo "$ outerr"
(outerr) > >(tee "$fout") 2> >(tee "$ferr" >&2)
echo "# $fout content :"
cat "$fout"
echo "# $ferr content :"
cat "$ferr"
}
Personally, I have this result :
user@computer:~$ test_redirect
$ outerr
# stdout.log content :
out
out
err
# stderr.log content :
err
user@computer:~$
No prompt on a blank line, but I don't see normal output, stdout.log content seem to be wrong, only stderr.log seem to be ok. If I relaunch it, output can be different...
So, why ?
Because, like explained here :
Beware that in bash, this command returns as soon as [first command] finishes, even if the tee commands are still executed (ksh and zsh do wait for the subprocesses)
So, if you use bash, prefer use the better exemple given in this other answer :
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
It will fix the previous issues.
Now, the question is, how to retrieve exit status code ?
$?
does not works.
I have no found better solution than switch on pipefail with set -o pipefail
(set +o pipefail
to switch off) and use ${PIPESTATUS[0]}
like this
function outerr() {
echo "out"
echo >&2 "err"
return 11
}
function test_outerr() {
local - # To preserve set option
! [[ -o pipefail ]] && set -o pipefail; # Or use second part directly
local fout="stdout.log"
local ferr="stderr.log"
echo "$ outerr"
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
# First save the status or it will be lost
local status="${PIPESTATUS[0]}" # Save first, the second is 0, perhaps tee status code.
echo "==="
echo "# $fout content :"
echo "<==="
cat "$fout"
echo "===>"
echo "# $ferr content :"
echo "<==="
cat "$ferr"
echo "===>"
if (( status > 0 )); then
echo "Fail $status > 0"
return "$status" # or whatever
fi
}
user@computer:~$ test_outerr
$ outerr
err
out
===
# stdout.log content :
<===
out
===>
# stderr.log content :
<===
err
===>
Fail 11 > 0
The answer from @gunn is correct, target="_blank
makes the link open in a new tab.
But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer"
.
<a style={{display: "table-cell"}} href = "someLink" target = "_blank"
rel = "noopener noreferrer">text</a>
Reason of comments:
HTML Comments
<!-- Everything is invisible -->
Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness).
However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything displayed in a normal web browser.
Some things to note:
You must have the Python version of Selenium RC installed for this to work, and you must have set up Selenium properly. Also this is just a template crawler. You could get much crazier and more advanced with things but I just wanted to show the basic idea. As the code stands now you will be doing two requests for any given url. One request is made by Scrapy and the other is made by Selenium. I am sure there are ways around this so that you could possibly just make Selenium do the one and only request but I did not bother to implement that and by doing two requests you get to crawl the page with Scrapy too.
This is quite powerful because now you have the entire rendered DOM available for you to crawl and you can still use all the nice crawling features in Scrapy. This will make for slower crawling of course but depending on how much you need the rendered DOM it might be worth the wait.
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from selenium import selenium
class SeleniumSpider(CrawlSpider):
name = "SeleniumSpider"
start_urls = ["http://www.domain.com"]
rules = (
Rule(SgmlLinkExtractor(allow=('\.html', )), callback='parse_page',follow=True),
)
def __init__(self):
CrawlSpider.__init__(self)
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*chrome", "http://www.domain.com")
self.selenium.start()
def __del__(self):
self.selenium.stop()
print self.verificationErrors
CrawlSpider.__del__(self)
def parse_page(self, response):
item = Item()
hxs = HtmlXPathSelector(response)
#Do some XPath selection with Scrapy
hxs.select('//div').extract()
sel = self.selenium
sel.open(response.url)
#Wait for javscript to load in Selenium
time.sleep(2.5)
#Do some crawling of javascript created content with Selenium
sel.get_text("//div")
yield item
# Snippet imported from snippets.scrapy.org (which no longer works)
# author: wynbennett
# date : Jun 21, 2011
Reference: http://snipplr.com/view/66998/
ListenForClients
is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main
. When two instances of the TcpListener
try to listen on the same port, you get that error.
You could use Directory.GetCurrentDirectory
:
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");
Which will look for the file fileName.txt
in the current directory of the application.
Try to add export PATH=$PATH:/home/me/play
in ~/.bashrc file.
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
The code below will produce this plot:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]
# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]
# A dataframe
df = pd.DataFrame(data)
def CorrMtx(df, dropDuplicates = True):
# Your dataset is already a correlation matrix.
# If you have a dateset where you need to include the calculation
# of a correlation matrix, just uncomment the line below:
# df = df.corr()
# Exclude duplicate correlations by masking uper right values
if dropDuplicates:
mask = np.zeros_like(df, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set background color / chart style
sns.set_style(style = 'white')
# Set up matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Add diverging colormap from red to blue
cmap = sns.diverging_palette(250, 10, as_cmap=True)
# Draw correlation plot with or without duplicates
if dropDuplicates:
sns.heatmap(df, mask=mask, cmap=cmap,
square=True,
linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
else:
sns.heatmap(df, cmap=cmap,
square=True,
linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
CorrMtx(df, dropDuplicates = False)
I put this together after it was announced that the outstanding seaborn corrplot
was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap
. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of
0.95173379, try changing to -0.95173379 and you'll get this:
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Thin.otf);
font-weight: 200;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Light.otf);
font-weight: 300;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Regular.otf);
font-weight: normal;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Bold.otf);
font-weight: bold;
}
h3, h4, h5, h6 {
font-size:2em;
margin:0;
padding:0;
font-family:Kaffeesatz;
font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }
Is this what you had in mind?
$("document").ready( function() {
// do your stuff
}
you can try this
CSS:
#table-wrapper {
height:150px;
overflow:auto;
margin-top:20px;
}
#table-wrapper table {
width:100%;
color:#000;
}
#table-wrapper table thead th .text {
position:fixed;
top:0px;
height:20px;
width:35%;
border:1px solid red;
}
HTML:
<div id="table-wrapper">
<table>
<thead>
<tr>
<th><span class="text">album</span></th>
<th><span class="text">song</span></th>
<th><span class="text">genre</span></th>
</tr>
</thead>
<tbody>
<tr> <td> album 0</td> <td> song0</td> <td> genre0</td> </tr>
<tr> <td>album 1</td> <td>song 1</td> <td> genre1</td> </tr>
<tr> <td> album2</td> <td>song 2</td> <td> genre2</td> </tr>
<tr> <td> album3</td> <td>song 3</td> <td> genre3</td> </tr>
<tr> <td> album4</td> <td>song 4</td> <td>genre 4</td> </tr>
<tr> <td> album5</td> <td>song 5</td> <td>genre 5</td> </tr>
<tr> <td>album 6</td> <td> song6</td> <td> genre6</td> </tr>
<tr> <td>album 7</td> <td> song7</td> <td> genre7</td> </tr>
<tr> <td> album8</td> <td> song8</td> <td>genre 8</td> </tr>
<tr> <td> album9</td> <td> song9</td> <td> genre9</td> </tr>
<tr> <td> album10</td> <td>song 10</td> <td> genre10</td> </tr>
<tr> <td> album11</td> <td>song 11</td> <td> genre11</td> </tr>
<tr> <td> album12</td> <td> song12</td> <td> genre12</td> </tr>
<tr> <td>album 13</td> <td> song13</td> <td> genre13</td> </tr>
<tr> <td> album14</td> <td> song14</td> <td> genre14</td> </tr>
<tr> <td> album15</td> <td> song15</td> <td> genre15</td> </tr>
<tr> <td>album 16</td> <td> song16</td> <td> genre16</td> </tr>
<tr> <td>album 17</td> <td> song17</td> <td> genre17</td> </tr>
<tr> <td> album18</td> <td> song18</td> <td> genre18</td> </tr>
<tr> <td> album19</td> <td> song19</td> <td> genre19</td> </tr>
<tr> <td> album20</td> <td> song20</td> <td> genre20</td> </tr>
</tbody>
</table>
</div>
Check this fiddle : http://jsfiddle.net/Kritika/GLKxB/1/
this will keep the table
head fixed
,and scroll
only the table content
.
SQL Server recognizes 'TRUE'
and 'FALSE'
as bit
values. So, use a bit
data type!
declare @var bit
set @var = 'true'
print @var
That returns 1
.
Regular expressions are simple enough, if you know them.
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
Inline tag is used to add another src of document to the current html element.
In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link
so add ?html=5 to the end of the link.. :)
... You can then use copy()
to duplicate a PHP file, although this sounds incredibly inefficient.
The CP1 means 'Code Page 1' - technically this translates to code page 1252
The following code sample, will match the pattern even in case of space characters in between. i.e. :
<td><a href='/path/to/file'>Name of File</a></td>
as well as:
<td> <a href='/path/to/file' >Name of File</a> </td>
Method returns true or false, depending on whether the input htmlTd string matches the pattern or no. If it matches, the out params contain the link and name respectively.
/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
link = null;
name = null;
string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";
if (Regex.IsMatch(htmlTd, pattern))
{
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
link = r.Match(htmlTd).Result("${link}");
name = r.Match(htmlTd).Result("${name}");
return true;
}
else
return false;
}
I have tested this and it works correctly.
Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:
template<typename T>
struct TypeParseTraits;
#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
{ static const char* name; } ; const char* TypeParseTraits<X>::name = #X
REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...
And then use it like
throw ParseError(TypeParseTraits<T>::name);
EDIT:
You could also combine the two, change name
to be a function that by default calls typeid(T).name()
and then only specialize for those cases where that's not acceptable.
static
variables exist for the "lifetime" of the translation unit that it's defined in, and:
constexpr
. Anything else, and you end up with a separate variable in each translation unit, which is crazy confusing)static
, but can be addressed from the class as well as an instance (like std::string::npos
). [Note: you can declare static members in a class, but they should usually still be defined in a translation unit (cpp file), and as such, there's only one per class]locations as code:
static std::string namespaceScope = "Hello";
void foo() {
static std::string functionScope= "World";
}
struct A {
static std::string classScope = "!";
};
Before any function in a translation unit is executed (possibly after main
began execution), the variables with static storage duration (namespace scope) in that translation unit will be "constant initialized" (to constexpr
where possible, or zero otherwise), and then non-locals are "dynamically initialized" properly in the order they are defined in the translation unit (for things like std::string="HI";
that aren't constexpr
). Finally, function-local statics will be initialized the first time execution "reaches" the line where they are declared. All static
variables all destroyed in the reverse order of initialization.
The easiest way to get all this right is to make all static variables that are not constexpr
initialized into function static locals, which makes sure all of your statics/globals are initialized properly when you try to use them no matter what, thus preventing the static initialization order fiasco.
T& get_global() {
static T global = initial_value();
return global;
}
Be careful, because when the spec says namespace-scope variables have "static storage duration" by default, they mean the "lifetime of the translation unit" bit, but that does not mean it can't be accessed outside of the file.
Significantly more straightforward, static
is often used as a class member function, and only very rarely used for a free-standing function.
A static member function differs from a regular member function in that it can be called without an instance of a class, and since it has no instance, it cannot access non-static members of the class. Static variables are useful when you want to have a function for a class that definitely absolutely does not refer to any instance members, or for managing static
member variables.
struct A {
A() {++A_count;}
A(const A&) {++A_count;}
A(A&&) {++A_count;}
~A() {--A_count;}
static int get_count() {return A_count;}
private:
static int A_count;
}
int main() {
A var;
int c0 = var.get_count(); //some compilers give a warning, but it's ok.
int c1 = A::get_count(); //normal way
}
A static
free-function means that the function will not be referred to by any other translation unit, and thus the linker can ignore it entirely. This has a small number of purposes:
static void log(const char*) {}
in each cpp file, and they could each all log in a different way.I am late to the game but, just in case anybody needs it, this a function I use to make adjustments on my code so it runs on Windows, Linux and MacOs:
import sys
def get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}):
'''
get OS to allow code specifics
'''
opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]
try:
return opsys[0]
except:
return 'unknown_OS'
Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.
I feel the simplest way would be
from matplotlib import pyplot;
from pylab import genfromtxt;
mat0 = genfromtxt("data0.txt");
mat1 = genfromtxt("data1.txt");
pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
pyplot.legend();
pyplot.show();
Try this:
Declare @DayOfMonth TinyInt Set @DayOfMonth = 13
Declare @Month TinyInt Set @Month = 6
Declare @Year Integer Set @Year = 2006
-- ------------------------------------
Select DateAdd(day, @DayOfMonth - 1,
DateAdd(month, @Month - 1,
DateAdd(Year, @Year-1900, 0)))
It works as well, has added benefit of not doing any string conversions, so it's pure arithmetic processing (very fast) and it's not dependent on any date format This capitalizes on the fact that SQL Server's internal representation for datetime and smalldatetime values is a two part value the first part of which is an integer representing the number of days since 1 Jan 1900, and the second part is a decimal fraction representing the fractional portion of one day (for the time) --- So the integer value 0 (zero) always translates directly into Midnight morning of 1 Jan 1900...
or, thanks to suggestion from @brinary,
Select DateAdd(yy, @Year-1900,
DateAdd(m, @Month - 1, @DayOfMonth - 1))
Edited October 2014. As Noted by @cade Roux, SQL 2012 now has a built-in function:
DATEFROMPARTS(year, month, day)
that does the same thing.
Edited 3 Oct 2016, (Thanks to @bambams for noticing this, and @brinary for fixing it), The last solution, proposed by @brinary. does not appear to work for leap years unless years addition is performed first
select dateadd(month, @Month - 1,
dateadd(year, @Year-1900, @DayOfMonth - 1));
Use where
with a !=
operator in combination with whereNull
Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get()
just for modifying certain property from object collection you could directly use forEach with a collection as follows
collection.forEach(c -> c.setXyz(c.getXyz + "a"))
Generally a cosine similarity between two documents is used as a similarity measure of documents. In Java, you can use Lucene (if your collection is pretty large) or LingPipe to do this. The basic concept would be to count the terms in every document and calculate the dot product of the term vectors. The libraries do provide several improvements over this general approach, e.g. using inverse document frequencies and calculating tf-idf vectors. If you are looking to do something copmlex, LingPipe also provides methods to calculate LSA similarity between documents which gives better results than cosine similarity. For Python, you can use NLTK.
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
This doesn't seem to be relevant in this case, but in case others face this problem --- make sure that if you installed 32 bit version of Eclipse, you also installed 32 bit version of JRE. Similarly, if you installed 64 bit version of Eclipse, you need 64 bit version of JRE in your Windows. Otherwise you will see the above error message as well.
In jstl we can access the current URL path using pageContext.request.contextPath
. If you want to do an Ajax call, use the following URL.
url = "${pageContext.request.contextPath}" + "/controller/path"
Example: For the page http://stackoverflow.com/posts/36577223
this will give http://stackoverflow.com/controller/path
.
Try this:
new String(bytebuffer.array(), "ASCII");
NB. you can't correctly convert a byte array to a String without knowing its encoding.
I hope this helps
Have not tested it yet, but the looks are better than the one Alex mentions.
The description at winginx.com/en/htaccess says:
About the htaccess to nginx converter
The service is to convert an Apache's .htaccess to nginx configuration instructions.
First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.
Note server instructions (e.g. php_value, etc.) are ignored.
The converter does not check syntax, including regular expressions and logic errors.
Please, check the result manually before use.
1· Do I need these DLL's?
It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.
- Where can I get them?
most dlls can be found at https://www.dll-files.com
I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll
For me leshims.dll
can be placed at C:\Windows\System32\
. Context: windows 7 64bit.
Just two more things I found helpful to know, even if they are not part of the question, really.
You can use the relayEvents
method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load
event. It is quite handy when writing custom components that encapsulate several sub-components.
The other way around, i.e. passing on events received by an encapsulating component mycmp
to one of its sub-components subcmp
, can be done like this
mycmp.on('show' function (mycmp, eOpts)
{
mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});
Drop the hash - that's for identifying the id attribute.
Besides the methods described in other answers (sp_depends system stored procedure, SQL Server dynamic management functions) you can also view dependencies between SQL Server objects - from SSMS.
You can use the View Dependencies option from SSMS. From the Object Explorer pane, right click on the object and from the context menu, select the View Dependencies option
I myself prefer a 3rd party dependency viewer called ApexSQL Search. It is a free add-in, which integrates into SSMS and Visual Studio for SQL object and data text search, extended property management, safe object rename, and relationship visualization.
To strip any whitespace, you can use a regular expression
$str=preg_replace('/\s+/', '', $str);
See also this answer for something which can handle whitespace in UTF-8 strings.
Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).
With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.
We'll take an example, a company table with a user table containing people from theses company
CREATE TABLE COMPANY (
company_id INT NOT NULL,
company_name VARCHAR(50),
PRIMARY KEY (company_id)
) ENGINE=INNODB;
CREATE TABLE USER (
user_id INT,
user_name VARCHAR(50),
company_id INT,
INDEX company_id_idx (company_id),
FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;
Let's look at the ON UPDATE clause:
And now on the ON DELETE side:
usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE
for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL
when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.
Edit
It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.
MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server
==> See below the last edit, things are moving on this domain
Triggers are not activated by foreign key actions.
And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.
But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.
as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).
Have you checked this http://support.microsoft.com/kb/209805? In particular, whether you have Msrd3x40.dll.
You may also like to check that you have the latest version of Jet: http://support.microsoft.com/kb/239114
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
Here are my two cents:
function stringFormat(str) {
if (str !== undefined && str !== null) {
str = String(str);
if (str.trim() !== "") {
var args = arguments;
return str.replace(/(\{[^}]+\})/g, function(match) {
var n = +match.slice(1, -1);
if (n >= 0 && n < args.length - 1) {
var a = args[n + 1];
return (a !== undefined && a !== null) ? String(a) : "";
}
return match;
});
}
}
return "";
}
alert(stringFormat("{1}, {0}. You're looking {2} today.",
"Dave", "Hello", Math.random() > 0.5 ? "well" : "good"));
C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.
C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.
And I almost missed it - you need to declare a variable name, not just the array dimensions.
First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:
var data : {
name: string;
file: File;
} = {
name: "Name",
file: inputValue.files[0]
};
Then you send it to the Server with JSON.stringify(data)
let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);
There are other database systems, such as document stores, key value stores, columnar stores, object oriented databases. These are databases too but they are not based on relations (relational theory) ie they are not relational database systems.
So there are lot of differences. Database management system is the name for all databases.
PYTHONPATH
is an environment variable/usr/lib/python2.7
on UbuntuPYTHONPATH
explicitlyIf you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.
I know that it is a very old post but for the sake of the users who are landed here and looking for a solution, if you are using Cloudflare as your DNS then you can activate IP geolocation and get the value from the request header,
here is the code snippet in C# after you enable IP geolocation in Cloudflare through the network tab
var countryCode = HttpContext.Request.Headers.Get("cf-ipcountry"); // in older asp.net versions like webform use HttpContext.Current.Request. ...
var countryName = new RegionInfo(CountryCode)?.EnglishName;
you can simply map it to other programming languages, please take a look at the Cloudflare's documentation here
but if you are really insisting on using a 3rd party solution to have more precise information about the visitors using their IP here is a complete, ready to use implementation using C#:
the 3rd party I have used is https://ipstack.com, you can simply register for a free plan and get an access token to use for 10K API requests each month, I am using the JSON model to retrieve and like to convert all the info the API gives me, here we go:
The DTO:
using System;
using Newtonsoft.Json;
public partial class GeoLocationModel
{
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("hostname")]
public string Hostname { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("continent_code")]
public string ContinentCode { get; set; }
[JsonProperty("continent_name")]
public string ContinentName { get; set; }
[JsonProperty("country_code")]
public string CountryCode { get; set; }
[JsonProperty("country_name")]
public string CountryName { get; set; }
[JsonProperty("region_code")]
public string RegionCode { get; set; }
[JsonProperty("region_name")]
public string RegionName { get; set; }
[JsonProperty("city")]
public string City { get; set; }
[JsonProperty("zip")]
public long Zip { get; set; }
[JsonProperty("latitude")]
public double Latitude { get; set; }
[JsonProperty("longitude")]
public double Longitude { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
[JsonProperty("time_zone")]
public TimeZone TimeZone { get; set; }
[JsonProperty("currency")]
public Currency Currency { get; set; }
[JsonProperty("connection")]
public Connection Connection { get; set; }
[JsonProperty("security")]
public Security Security { get; set; }
}
public partial class Connection
{
[JsonProperty("asn")]
public long Asn { get; set; }
[JsonProperty("isp")]
public string Isp { get; set; }
}
public partial class Currency
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("plural")]
public string Plural { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("symbol_native")]
public string SymbolNative { get; set; }
}
public partial class Location
{
[JsonProperty("geoname_id")]
public long GeonameId { get; set; }
[JsonProperty("capital")]
public string Capital { get; set; }
[JsonProperty("languages")]
public Language[] Languages { get; set; }
[JsonProperty("country_flag")]
public Uri CountryFlag { get; set; }
[JsonProperty("country_flag_emoji")]
public string CountryFlagEmoji { get; set; }
[JsonProperty("country_flag_emoji_unicode")]
public string CountryFlagEmojiUnicode { get; set; }
[JsonProperty("calling_code")]
public long CallingCode { get; set; }
[JsonProperty("is_eu")]
public bool IsEu { get; set; }
}
public partial class Language
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("native")]
public string Native { get; set; }
}
public partial class Security
{
[JsonProperty("is_proxy")]
public bool IsProxy { get; set; }
[JsonProperty("proxy_type")]
public object ProxyType { get; set; }
[JsonProperty("is_crawler")]
public bool IsCrawler { get; set; }
[JsonProperty("crawler_name")]
public object CrawlerName { get; set; }
[JsonProperty("crawler_type")]
public object CrawlerType { get; set; }
[JsonProperty("is_tor")]
public bool IsTor { get; set; }
[JsonProperty("threat_level")]
public string ThreatLevel { get; set; }
[JsonProperty("threat_types")]
public object ThreatTypes { get; set; }
}
public partial class TimeZone
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("current_time")]
public DateTimeOffset CurrentTime { get; set; }
[JsonProperty("gmt_offset")]
public long GmtOffset { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("is_daylight_saving")]
public bool IsDaylightSaving { get; set; }
}
The Helper:
using System.Configuration;
using System.IO;
using System.Net;
using System.Threading.Tasks;
public class GeoLocationHelper
{
public static async Task<GeoLocationModel> GetGeoLocationByIp(string ipAddress)
{
var request = WebRequest.Create(string.Format("http://api.ipstack.com/{0}?access_key={1}", ipAddress, ConfigurationManager.AppSettings["ipStackAccessKey"]));
var response = await request.GetResponseAsync();
using (var stream = new StreamReader(response.GetResponseStream()))
{
var jsonGeoData = await stream.ReadToEndAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<GeoLocationModel>(jsonGeoData);
}
}
}
As others have noted, in Notepad++ 6.0 and later, it is possible to use the "Replace" feature to delete all lines that begin with ";" or "#".
Tao provides a regular expression that serves as a starting point, but it does not account for white-space that may exist before the ";" or "#" character on a given line. For example, lines that begin with ";" or "#" but are "tabbed-in" will not be deleted when using Tao's regular expression, ^(#|;).*\r\n
.
Tao's regular expression does not account for the caveat mentioned in BoltClock's answer, either: variances in newline characters across systems.
An improvement is to use ^(\s)*(#|;).*(\r\n|\r|\n)?
, which accounts for leading white-space and the newline character variances. Also, the trailing ?
handles cases in which the last line of the file begins with #
or ;
, but does not end with a newline.
For the curious, it is possible to discern which type of newline character is used in a given document (and more than one type may be used): View -> Show Symbol -> Show End of Line.
Using Widget.AppCompat.RatingBar
, you have 2 styles to use; Indicator
and Small
for large and small sizes respectively. See example below.
<RatingBar
android:id="@+id/rating_star_value"
style="@style/Widget.AppCompat.RatingBar.Small"
... />
Use This Code anywhere in class or libraries
$current_url =& get_instance(); // get a reference to CodeIgniter
$current_url->router->fetch_class(); // for Class name or controller
$current_url->router->fetch_method(); // for method name
There are two ways you can count the number of rows.
$query = "SELECT count(*) as total from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_ASSOC);
echo $row['total']; // This will return you a number of rows.
Or second way is
$query = "SELECT field1, field2 from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_NUM);
echo $rows[0]; // This will return you a number of rows as well.
Robot robot = new Robot();
robot.mouseMove(coordinates.x,coordinates.y+80);
Rotbot is good solution. It works for me.
First you split the values of two input box by using split function. then concat the same in reverse order. after concat nation parse it to integer. then compare two values in in if statement. eg.1>20-11-2018 2>21-11-2018
after split and concat new values for comparison 20181120 and 20181121 the after that compare the same.
var date1 = $('#datevalue1').val();
var date2 = $('#datevalue2').val();
var d1 = date1.split("-");
var d2 = date2.split("-");
d1 = d1[2].concat(d1[1], d1[0]);
d2 = d2[2].concat(d2[1], d2[0]);
if (parseInt(d1) > parseInt(d2)) {
$('#fromdatepicker').val('');
} else {
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Yeah, when ASP.NET web.config gets updated, the whole application gets restarted which means the web.config gets reloaded.
<select id="myselect">
<option value="0">sometext</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
</select>
$('#myselect').change(function() {
if($('#myselect option:selected').val() == 0) {
...
}
else {
...
}
});
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.
However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon
, data-url
, data-target
, etc.
In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:
ele.setAttribute(attributeName, value);
to change the given attribute attributeName
to value
for the DOM element ele
.
For example:
document.getElementById("someElement").setAttribute("data-id", 2);
Note that you can also use .dataset
to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute
method instead.
Check out http://codepad.org. It probably won't solve the poster's problem; but, I think it will be of use to others who read this article.
If you take a look at bootstrap source codes, you will notice that position can be modified using margin.
So, first you should change popover template to add own css class to not get in conflict with other popovers:
$(".trigger").popover({
html: true,
placement: 'bottom',
trigger: 'click',
template: '<div class="popover popover--topright" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
});
Then using css you can easily shift popover position:
.popover.popover--topright {
/* margin-top: 0px; // Use to change vertical position */
margin-right: 40px; /* Use to change horizontal position */
}
.popover.popover--topright .arrow {
left: 88% !important; /* fix arrow position */
}
This solution would not influence other popovers you have. Same solution can be used on tooltips as well because popover class inherit from tooltip class.
There are many tutorials and answers here how to add your script to be included in the page. But what I couldn't find is how to structure that code so it will work properly. This is due the $ being not used in this form of JQuery.
So here is my code and you can use that as a template.
jQuery(document).ready(function( $ ){
$("#btnCalculate").click(function () {
var val1 = $(".visits").val();
var val2 = $(".collection").val();
var val3 = $(".percent").val();
var val4 = $(".expired").val();
var val5 = $(".payer").val();
var val6 = $(".deductible").val();
var result = val1 * (val3 / 100) * 10 * 0.25;
var result2 = val1 * val2 * (val4 / 100) * 0.2;
var result3 = val1 * val2 * (val5 / 100) * 0.2;
var result4 = val1 * val2 * (val6 / 100) * 0.1;
var val7 = $(".pverify").val();
var result5 = result + result2 + result3 + result4 - val7;
var result6 = result5 * 12;
$("#result").val("$" + result);
$("#result2").val("$" + result2);
$("#result3").val("$" + result3);
$("#result4").val("$" + result4);
$("#result5").val("$" + result5);
$("#result6").val("$" + result6);
});
});
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method compareTo
in order to know how (attributes) we want to compare instances.
Dog
class:package test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("brutus");
Dog d2 = new Dog("medor");
Dog d3 = new Dog("ara");
Dog[] dogs = new Dog[3];
dogs[0] = d1;
dogs[1] = d2;
dogs[2] = d3;
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* brutus
* medor
* ara
*/
Arrays.sort(dogs, Dog.NameComparator);
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* ara
* medor
* brutus
*/
}
}
Main
class:package test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("brutus");
Dog d2 = new Dog("medor");
Dog d3 = new Dog("ara");
Dog[] dogs = new Dog[3];
dogs[0] = d1;
dogs[1] = d2;
dogs[2] = d3;
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* brutus
* medor
* ara
*/
Arrays.sort(dogs, Dog.NameComparator);
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* ara
* medor
* brutus
*/
}
}
Here is a good example how to use comparable in Java:
http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2
The only way is to highlight the lines to comment and press
ctrl + k, ctrl + c
or after highlighted press the toolbar option to comment out the selected lines.
The icons look like this
I never had any luck with that approach. I always do this (hope this helps):
var obj = {};
obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();
Then in your ajax:
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(obj),
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
First, you know that "blank" and "null" are two COMPLETELY DIFFERENT THINGS? Correct?
Second: in most programming languages, "" means an "empty string". A zero-length string. No characters in it.
SQL doesn't necessarily work like that. If I define a column "name char(5)", then a "blank" name will be " "
(5 spaces).
It sounds like you might want something like this:
select count(*) from my_table where Length(trim(my_column)) = 0;
"Trim()" is one of many Oracle functions you can use in PL/SQL. It's documented here:
http://www.techonthenet.com/oracle/functions/trim.php
'Hope that helps!
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());
You can try with the code that is below.
It will make the default date become the date you are looking for.
$('#birthdate').datepicker("setDate", new Date(1985,01,01) );
use the pow
function (it takes float
s/double
s though).
man pow
:
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
EDIT: For the special case of positive integer powers of 2
, you can use bit shifting: (1 << x)
will equal 2
to the power x
. There are some potential gotchas with this, but generally, it would be correct.
The second function should have:
var value = document.getElementById(id).value;
Then they are basically the same function.
Uninstall tensorflow and install only tensorflow-gpu; this should be sufficient. By default, this should run on the GPU and not the CPU. However, further you can do the following to specify which GPU you want it to run on.
If you have an nvidia GPU, find out your GPU id using the command nvidia-smi
on the terminal. After that, add these lines in your script:
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = #GPU_ID from earlier
config = tf.ConfigProto()
sess = tf.Session(config=config)
For the functions where you wish to use GPUs, write something like the following:
with tf.device(tf.DeviceSpec(device_type="GPU", device_index=gpu_id)):
Try to use it, and trap for the error. The allowed set may change across file systems, or across different versions of Windows. In other words, if you want know if Windows likes the name, hand it the name and let it tell you.
Here's yet another solution, just for kicks. It's probably not very efficient, but it does cope with both height and width of the text, and with marked-up text.
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec)
{
if ((MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED)
&& (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.UNSPECIFIED)) {
final float desiredWidth = MeasureSpec.getSize(widthMeasureSpec);
final float desiredHeight = MeasureSpec.getSize(heightMeasureSpec);
float textSize = getTextSize();
float lastScale = Float.NEGATIVE_INFINITY;
while (textSize > MINIMUM_AUTO_TEXT_SIZE_PX) {
// Measure how big the textview would like to be with the current text size.
super.onMeasure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
// Calculate how much we'd need to scale it to fit the desired size, and
// apply that scaling to the text size as an estimate of what we need.
final float widthScale = desiredWidth / getMeasuredWidth();
final float heightScale = desiredHeight / getMeasuredHeight();
final float scale = Math.min(widthScale, heightScale);
// If we don't need to shrink the text, or we don't seem to be converging, we're done.
if ((scale >= 1f) || (scale <= lastScale)) {
break;
}
// Shrink the text size and keep trying.
textSize = Math.max((float) Math.floor(scale * textSize), MINIMUM_AUTO_TEXT_SIZE_PX);
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
lastScale = scale;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
If you have access to apache bin directory you can use,
httpd -M
to check loaded modules first.
info_module (shared) isapi_module (shared) log_config_module (shared) cache_disk_module (shared) mime_module (shared) negotiation_module (shared) proxy_module (shared) proxy_ajp_module (shared) rewrite_module (shared) setenvif_module (shared) socache_shmcb_module (shared) ssl_module (shared) status_module (shared) version_module (shared) php5_module (shared)
After that simple directives like Options -Indexes
or deny from all
will solidify that .htaccess are working correctly.
If you already have a list and want to add values from a delimited string, you can use AddRange
or InsertRange
. For example:
existingList.AddRange(names.Split(','));
or you can simply do
$('select[name=a[b]] option:selected').val()
You can use animate insted of show/hide
Something like this:
function switch_tabs(obj)
{
$('.tab-content').animate({opacity:0},3000);
$('.tabs a').removeClass("selected");
var id = obj.attr("rel");
$('#'+id).animate({opacity:1},3000);
obj.addClass("selected");
}
This is somewhat a go around solution but it worked for me I hope it works for this problem for others as well:
You can run the select SQL query on the table that you want to export and save the result as .xls in you drive.
Now create the table you want to add data with all the columns and indexes. This can be easily done with the right click on the actual table and selecting Create To script option.
Now you can right click on the DB where you want to add you table and select the Tasks>Import .
Import Export wizard opens and select next.Select the Microsoft Excel as input Data source and then browse and select the .xls file you have saved earlier.
Now select the destination server and also the destination table we have created already.
Note:If there is any identity based field, in the destination table you might want to remove the identity property as this data will also be inserted . So if you had this one as Identity property only then it would error out the import process.
Now hit next and hit finish and it will show you how many records are being imported and return success if no errors occur.
Happy hashing!
You can also use the tag, this works in divs and everything else:
<center><form></form></center>
This link will help you with the tag:
The terms "interpreted language" or "compiled language" don't make sense, because any programming language can be interpreted and/or compiled.
As for the existing implementations of Java, most involve a compilation step to bytecode, so they involve compilation. The runtime also can load bytecode dynamically, so some form of a bytecode interpreter is always needed. That interpreter may or may not in turn use compilation to native code internally.
These days partial just-in-time compilation is used for many languages which were once considered "interpreted", for example JavaScript.
The simplest approach is to use ExecutorService.invokeAll()
which does what you want in a one-liner. In your parlance, you'll need to modify or wrap ComputeDTask
to implement Callable<>
, which can give you quite a bit more flexibility. Probably in your app there is a meaningful implementation of Callable.call()
, but here's a way to wrap it if not using Executors.callable()
.
ExecutorService es = Executors.newFixedThreadPool(2);
List<Callable<Object>> todo = new ArrayList<Callable<Object>>(singleTable.size());
for (DataTable singleTable: uniquePhrases) {
todo.add(Executors.callable(new ComputeDTask(singleTable)));
}
List<Future<Object>> answers = es.invokeAll(todo);
As others have pointed out, you could use the timeout version of invokeAll()
if appropriate. In this example, answers
is going to contain a bunch of Future
s which will return nulls (see definition of Executors.callable()
. Probably what you want to do is a slight refactoring so you can get a useful answer back, or a reference to the underlying ComputeDTask
, but I can't tell from your example.
If it isn't clear, note that invokeAll()
will not return until all the tasks are completed. (i.e., all the Future
s in your answers
collection will report .isDone()
if asked.) This avoids all the manual shutdown, awaitTermination, etc... and allows you to reuse this ExecutorService
neatly for multiple cycles, if desired.
There are a few related questions on SO:
None of these are strictly on-point for your question, but they do provide a bit of color about how folks think Executor
/ExecutorService
ought to be used.
Simplest:
Form form = new Form();
form.add("id", "1");
form.add("name", "supercobra");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
you should try with jquery validate plugin :
$('form').validate({
rules:{
email:{
required:true,
email:true
}
},
messages:{
email:{
required:"Email is required",
email:"Please type a valid email"
}
}
})
Its fine to just do char **strings;
, char **strings = NULL
, or char **strings = {NULL}
but to initialize it you'd have to use malloc:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
// allocate space for 5 pointers to strings
char **strings = (char**)malloc(5*sizeof(char*));
int i = 0;
//allocate space for each string
// here allocate 50 bytes, which is more than enough for the strings
for(i = 0; i < 5; i++){
printf("%d\n", i);
strings[i] = (char*)malloc(50*sizeof(char));
}
//assign them all something
sprintf(strings[0], "bird goes tweet");
sprintf(strings[1], "mouse goes squeak");
sprintf(strings[2], "cow goes moo");
sprintf(strings[3], "frog goes croak");
sprintf(strings[4], "what does the fox say?");
// Print it out
for(i = 0; i < 5; i++){
printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
}
//Free each string
for(i = 0; i < 5; i++){
free(strings[i]);
}
//finally release the first string
free(strings);
return 0;
}
TL;DR If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0, on the other hand, lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll your own system.
As stated in another answer, JWT (Learn JSON Web Tokens) is just a token format, it defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.
Being self-contained (the actual token contains information about a given subject) they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route and the only thing a party must present to be granted access to a protected resource is the token itself, the token in question can be called a bearer token.
In practice, what you're doing can already be classified as based on bearer tokens. However, do consider that you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply, relying on the Authorization
HTTP header and using the Bearer
authentication scheme.
Regarding the use of the JWT to prevent CSRF without knowing exact details it's difficult to ascertain the validity of that practice, but to be honest it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.
One final piece of advice, even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization
header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header.
Authorization headers are recognized and specially treated by HTTP proxies and servers. Thus, the usage of such headers for sending access tokens to resource servers reduces the likelihood of leakage or unintended storage of authenticated requests in general, and especially Authorization headers.
(source: RFC 6819, section 5.4.1)
Regarding the question,
” can someone explain why the
compare()
function exists if a comparison can be made using simple operands?
Relative to <
and ==
, the compare
function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.
As an example of simplicity, for small integer values you can write a compare function like this:
auto compare( int a, int b ) -> int { return a - b; }
which is highly efficient.
Now for a structure
struct Foo
{
int a;
int b;
int c;
};
auto compare( Foo const& x, Foo const& y )
-> int
{
if( int const r = compare( x.a, y.a ) ) { return r; }
if( int const r = compare( x.b, y.b ) ) { return r; }
return compare( x.c, y.c );
}
Trying to express this lexicographic compare directly in terms of <
you wind up with horrendous complexity and inefficiency, relatively speaking.
With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.
UPDATE `table_name` SET `test` = `number`
You can also do any mathematical changes in the process or use MySQL functions to modify the values.
There are various causes of segmentation faults, but fundamentally, you are accessing memory incorrectly. This could be caused by dereferencing a null pointer, or by trying to modify readonly memory, or by using a pointer to somewhere that is not mapped into the memory space of your process (that probably means you are trying to use a number as a pointer, or you incremented a pointer too far). On some machines, it is possible for a misaligned access via a pointer to cause the problem too - if you have an odd address and try to read an even number of bytes from it, for example (that can generate SIGBUS, instead).
add android:focusableInTouchMode="true" in root layout, when edit text will be clicked at that time cursor will be shown.
Works, just figured this out a week ago, and just now got to testing it.
double theta = Math.atan2(cir.getX()-sqr.getX()*1.0,
cir.getY()-sqr.getY()*1.0); //radians of the angle
double dBox; //distance from box to edge of box in direction of the circle
if((theta > Math.PI/4 && theta < 3*Math.PI / 4) ||
(theta < -Math.PI/4 && theta > -3*Math.PI / 4)) {
dBox = sqr.getS() / (2*Math.sin(theta));
} else {
dBox = sqr.getS() / (2*Math.cos(theta));
}
boolean touching = (Math.abs(dBox) >=
Math.sqrt(Math.pow(sqr.getX()-cir.getX(), 2) +
Math.pow(sqr.getY()-cir.getY(), 2)));
Set your Textbox value in a string like:
string MySTring = textBox1.Text;
Then replace your string. For example, replace "Text" with "Hex":
MyString = MyString.Replace("Text", "Hex");
Or for your problem (replace "," with ;) :
MyString = MyString.Replace(@""",""", ",");
Note: If you have "" in your string you have to use @ in the back of "", like:
@"","";
I personally use
myVar === undefined
Warning: Please note that ===
is used over ==
and that myVar
has been previously declared (not defined).
I do not like typeof myVar === "undefined"
. I think it is long winded and unnecessary. (I can get the same done in less code.)
Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined
can be redefined!"
Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?
If you follow this rule, good for you: you aren't a hypocrite.
The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout
because someone can
window.setTimeout = function () {
alert("Got you now!");
};
Bottom line, the "it can be redefined" argument to not use a raw === undefined
is bogus.
(If you are still scared of undefined
being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)
Also, like the typeof
approach, this technique can "detect" undeclared variables:
if (window.someVar === undefined) {
doSomething();
}
But both these techniques leak in their abstraction. I urge you not to use this or even
if (typeof myVar !== "undefined") {
doSomething();
}
Consider:
var iAmUndefined;
To catch whether or not that variable is declared or not, you may need to resort to the in
operator. (In many cases, you can simply read the code O_o).
if ("myVar" in window) {
doSomething();
}
But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in
operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined
(and ****cough**** typeof
) works just fine. If you really care, you can read about this subject on its own.)
That is the simple way of converting string into util date and sql date
String startDate="12-31-2014";
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = sdf1.parse(startDate);
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).
Read my answer there for a fuller explaination, but in short:
They removed it deliberately, because compat mode is not actually really very good for testing compatibility.
If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.
The only way to get compat mode in IE11 is to set the X-UA-Compatible
header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.
The push
command has a -n
/--dry-run
option which will compute what needs to be pushed but not actually do it. Does that work for you?
On C++17 you can by this way :
#include <filesystem>
#include <iostream>
#include <vector>
namespace fs = std::filesystem;
int main()
{
std::ios_base::sync_with_stdio(false);
for (const auto &entry : fs::recursive_directory_iterator(".")) {
if (entry.path().extension() == ".png") {
std::cout << entry.path().string() << std::endl;
}
}
return 0;
}
To expand on what has been provided for automatically exporting data as csv to a network share via SQL Server Agent.
(1) Enable the xp_cmdshell procedure:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database. Done through user mapping
(3) Give log on as batch job: Navigate to Local Security Policy -> Local Policies -> User Rights Assignment. Add user to "Log on as a batch job"
(4) Give read/write permissions to network folder for domain\user
(5) Grant EXEC permission on the xp_cmdshell stored procedure:
GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]
(6) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'password_for_domain_user'
(7) If the sp_xp_cmdshell_proxy_account command doesn't work, manually create it
create credential ##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret = 'password'
(8) Enable SQL Server Agent. Open SQL Server Configuration Manager, navigate to SQL Server Services, enable SQL Server Agent.
(9) Create automated job. Open SSMS, select SQL Server Agent, then right-click jobs and click "New Job".
(10) Select "Owner" as your created user. Select "Steps", make "type" = T-SQL. Fill out command field similar to below. Set delimiter as ','
EXEC master..xp_cmdshell 'SQLCMD -q "select * from master" -o file.csv -s ","
(11) Fill out schedules accordingly.
The simple answer is yes - new() creates an object on the heap (with the unfortunate side effect that you have to manage its lifetime (by explicitly calling delete on it), whereas the second form creates an object in the stack in the current scope and that object will be destroyed when it goes out of scope.
Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever
error.
So my solution was importing like below
from . import filename # without .py
inside my first file I have defined function fun like below
# file name is firstFile.py
def fun():
print('this is fun')
inside the second file lets say I want to call the function fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
I encountered the same error. My linker command did have the rt library included -lrt
which is correct and it was working for a while. After re-installing Kubuntu it stopped working.
A separate forum thread suggested the -lrt
needed to come after the project object files.
Moving the -lrt
to the end of the command fixed this problem for me although I don't know the details of why.
Statements before could change the state of our Python program: create or update variables, define function, etc.
And expressions just return some value can't change the global state or local state in a function.
But now we got :=
, it's an alien!
Developed this method:
You NEED a table that has an unique value that can be ordered.
If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:
int start = 40000 - 10000;
int total = 25000 - 10000;
And then pass these by code to the query:
SELECT * FROM
(SELECT * FROM schema.mytable
ORDER BY userId DESC fetch first {start} rows only ) AS mini
ORDER BY mini.userId ASC fetch first {total} rows only
You are using a forward declaration for the type MainWindowClass
. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)
So, you either want:
// forward declaration, details unknown
class A;
class B {
A *a; // pointer to A, ok
};
Or, if you can't use a pointer or reference....
// declaration of A
#include "A.h"
class B {
A a; // ok, declaration of A is known
};
At some point, the compiler needs to know the details of A
.
If you are only storing a pointer to A
then it doesn't need those details when you declare B
. It needs them at some point (whenever you actually dereference the pointer to A
), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A
.
// B.h
// header file
// forward declaration, details unknown
class A;
class B {
public:
void foo();
private:
A *a; // pointer to A, ok
};
// B.cpp
// implementation file
#include "B.h"
#include "A.h" // declaration of A
B::foo() {
// here we need to know the declaration of A
a->whatever();
}
apt-get install php7.3-mbstring
solved the issue on ubuntu, php version is php-fpm 7.3
In commandline, there is a command dropuser
available to do drop user from postgres.
$ dropuser someuser
Java programming provides wrapper class for each primitive data types, to convert a primitive data types to correspond object of wrapper class.
You can do this instead too:
tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul
datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2)
will return True
.
datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2)
will return datetime.timedelta(-1)
.
datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2)
will return datetime.timedelta(1)
.
see the docs.
In the early days...like before the 90s...the processors weren't able to do multi tasks that efficiently...coz a single processor could handle just a single task...so when we used to say that my antivirus,microsoft word,vlc,etc. softwares are all running at the same time...that isn't actually true. When I said a processor could handle a single process at a time...I meant it. It actually would process a single task...then it used to pause that task...take another task...complete it if its a short one or again pause it and add it to the queue...then the next. But this 'pause' that I mentioned was so small (appx. 1ns) that you didn't understand that the task has been paused. Eg. On vlc while listening to music there are other apps running simultaneously but as I told you...one program at a time...so the vlc is actually pausing in between for ns so you dont underatand it but the music is actually stopping in between.
But this was about the old processors...
Now-a- days processors ie 3rd gen pcs have multi cored processors. Now the 'cores' can be compared to a 1st or 2nd gen processors itself...embedded onto a single chip, a single processor. So now we understood what are cores ie they are mini processors which combine to become a processor. And each core can handle a single process at a time or multi threads as designed for the OS. And they folloq the same steps as I mentioned above about the single processor.
Eg. A i7 6gen processor has 8 cores...ie 8 mini processors in 1 i7...ie its speed is 8x times the old processors. And this is how multi tasking can be done.
There could be hundreds of cores in a single processor Eg. Intel i128.
I hope I explaned this well.
It lets you define a @Section
of code in your template that you can then include in other files. For example, a sidebar defined in the template, could be referenced in another included view.
//This could be used to render a @Section defined as @Section SideBar { ...
@RenderSection("SideBar", required: false);
Hope this helps.
Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.
In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.
PHP < 5.3If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here
Blob is much slower than String.fromCharCode(null,array);
but that fails if the array buffer gets too big. The best solution I have found is to use String.fromCharCode(null,array);
and split it up into operations that won't blow the stack, but are faster than a single char at a time.
The best solution for large array buffer is:
function arrayBufferToString(buffer){
var bufView = new Uint16Array(buffer);
var length = bufView.length;
var result = '';
var addition = Math.pow(2,16)-1;
for(var i = 0;i<length;i+=addition){
if(i + addition > length){
addition = length - i;
}
result += String.fromCharCode.apply(null, bufView.subarray(i,i+addition));
}
return result;
}
I found this to be about 20 times faster than using blob. It also works for large strings of over 100mb.
Your current implementation is correct. The suggested is not possible but the pseudo code would be implemented with multiple equal()
calls and ||
.
You can have multiple identical hash keys; but only if you have a range key that varies. Think of it like file formats; you can have 2 files with the same name in the same folder as long as their format is different. If their format is the same, their name must be different. The same concept applies to DynamoDB's hash/range keys; just think of the hash as the name and the range as the format.
Also, I don't recall if they had these at the time of the OP (I don't believe they did), but they now offer Local Secondary Indexes.
My understanding of these is that it should now allow you to perform the desired queries without having to do a full scan. The downside is that these indexes have to be specified at table creation, and also (I believe) cannot be blank when creating an item. In addition, they require additional throughput (though typically not as much as a scan) and storage, so it's not a perfect solution, but a viable alternative, for some.
I do still recommend Mike Brant's answer as the preferred method of using DynamoDB, though; and use that method myself. In my case, I just have a central table with only a hash key as my ID, then secondary tables that have a hash and range that can be queried, then the item points the code to the central table's "item of interest", directly.
Additional data regarding the secondary indexes can be found in Amazon's DynamoDB documentation here for those interested.
Anyway, hopefully this will help anyone else that happens upon this thread.
For Web API 2, you can implement IHttpActionResult
. Here's mine:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
class FileResult : IHttpActionResult
{
private readonly string _filePath;
private readonly string _contentType;
public FileResult(string filePath, string contentType = null)
{
if (filePath == null) throw new ArgumentNullException("filePath");
_filePath = filePath;
_contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(_filePath))
};
var contentType = _contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(_filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return Task.FromResult(response);
}
}
Then something like this in your controller:
[Route("Images/{*imagePath}")]
public IHttpActionResult GetImage(string imagePath)
{
var serverPath = Path.Combine(_rootPath, imagePath);
var fileInfo = new FileInfo(serverPath);
return !fileInfo.Exists
? (IHttpActionResult) NotFound()
: new FileResult(fileInfo.FullName);
}
And here's one way you can tell IIS to ignore requests with an extension so that the request will make it to the controller:
<!-- web.config -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
Let's say we have a menu like this:
<div class="menu">
<a href="link1.html">Link 1</a>
<a href="link2.html">Link 2</a>
<a href="link3.html">Link 3</a>
<a href="link4.html">Link 4</a>
</div>
Let our current url be https://demosite.com/link1.html
With the following function we can add the active class to which menu's href is in our url.
let currentURL = window.location.href;
document.querySelectorAll(".menu a").forEach(p => {
if(currentURL.indexOf(p.getAttribute("href")) !== -1){
p.classList.add("active");
}
})
MSDN Documentation Here
To add a bit of context to M.Ali's Answer you can convert a string to a uniqueidentifier using the following code
SELECT CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E')
If that doesn't work check to make sure you have entered a valid GUID
main()
is a static method which has two fundamental restrictions:
this()
and super()
cannot be used in static context.
class A {
int a = 40; //non static
public static void main(String args[]) {
System.out.println(a);
}
}
Output: Compile Time Error
Here is the sample MYSQL Stored Procedure with delimiter and how to call..
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
IN loc_username VARCHAR(255),
IN loc_password VARCHAR(255)
)
BEGIN
SELECT user_id,
user_name,
user_emailid,
user_profileimage,
last_update
FROM tbl_user
WHERE user_name = loc_username
AND password = loc_password
AND status = 1;
END $$
DELIMITER ;
and call by, mysql_connection specification and
$loginCheck="call sp_user_login('".$username."','".$password."');";
it will return the result from the procedure.
Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.
<?xml version="1.0"?>
<definitions name="StockQuote"
targetNamespace="http://example.com/stockquote.wsdl"
xmlns:tns="http://example.com/stockquote.wsdl"
xmlns:xsd1="http://example.com/stockquote.xsd"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?
In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.
See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
Installig Eclispe ADT from market place solved this problem for me.
For anyone on a Mac who has Docker Desktop installed. I was able to just click the tray icon and say Restart Docker
. Once it restarted was able to delete the containers.
Lets take below object as example
let obj = { property1: 'value 1', property2: 'value 2'};
First fetch all the key in the obj
let keys = Object.keys(obj) //it will return array of keys
and then loop through it
keys.forEach(key => //your way)
just putting all together
Object.keys(obj).forEach(key=>{/*code here*/})
If the string can not be converted to an integer, then
int.Parse()
will throw an exceptionint.TryParse()
will return false (but not throw an exception)Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc
For example:
git clone https://github.com/zrax/pycdc
cd pycdc
make
./bin/pycdc Example.pyc > Example.py
mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:
mosquitto_sub -h test.mosquitto.org -t "#" -v
The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.
If your MQTT device publishes a topic of irisys/V4D-19230005/
to the test MQTT broker , then you could filter the messages:
mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v
Options:
Relative Paths
A relative path assumes that the file is on the current server. Using relative paths allows you to construct your site offline and fully test it before uploading it.
For example:
php/webct/itr/index.php
.
Absolute Paths
An absolute path refers to a file on the Internet using its full URL. Absolute paths tell the browser precisely where to go.
For example:
http://www.uvsc.edu/disted/php/webct/itr/index.php
Absolute paths are easier to use and understand. However, it is not good practice on your own website. For one thing, using relative paths allows you to construct your site offline and fully test it before uploading it. If you were to use absolute paths you would have to change your code before uploading it in order to get it to work. This would also be the case if you ever had to move your site or if you changed domain names.
Reference: http://openhighschoolcourses.org/mod/book/tool/print/index.php?id=12503
Here's some javascript. Just input x and y values.
var angle = (Math.atan2(x,y) * (180/Math.PI) + 360) % 360;
tl;dr: You want to use curve
(with add=TRUE
) or lines
.
I disagree with par(new=TRUE)
because that will double-print tick-marks and axis labels. Eg
The output of plot(sin); par(new=T); plot( function(x) x**2 )
.
Look how messed up the vertical axis labels are! Since the ranges are different you would need to set ylim=c(lowest point between the two functions, highest point between the two functions)
, which is less easy than what I'm about to show you---and way less easy if you want to add not just two curves, but many.
What always confused me about plotting is the difference between curve
and lines
. (If you can't remember that these are the names of the two important plotting commands, just sing it.)
curve
and lines
.curve
will plot a function, like curve(sin)
. lines
plots points with x and y values, like: lines( x=0:10, y=sin(0:10) )
.
And here's a minor difference: curve
needs to be called with add=TRUE
for what you're trying to do, while lines
already assumes you're adding to an existing plot.
Here's the result of calling plot(0:2); curve(sin)
.
Behind the scenes, check out methods(plot)
. And check body( plot.function )[[5]]
. When you call plot(sin)
R figures out that sin
is a function (not y values) and uses the plot.function
method, which ends up calling curve
. So curve
is the tool meant to handle functions.
Float the #list
and #similar
the right and add clear: right;
to #similar
Like so:
#map { float:left; width:700px; height:500px; }
#list { float:right; width:200px; background:#eee; list-style:none; padding:0; }
#similar { float:right; width:200px; background:#000; clear:right; }
<div id="map"></div>
<ul id="list"></ul>
<div id="similar">this text should be below, not next to ul.</div>
You might need a wrapper(div) around all of them though that's the same width of the left and right element.