You can try to add some time.sleep
calls to your code.
It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.
In order to avoid your code from crashing, try to catch this error with try .. except
around the urllib2 calls.
Response.Write
is used to display the text not for executing JavaScript, If you want to execute the JavaScript from your code than try as below:
try
{
con.Open();
string pass="abc";
cmd = new SqlCommand("insert into register values('" + txtName.Text + "','" + txtEmail.Text + "','" + txtPhoneNumber.Text + "','" + ddlUserType.SelectedText + "','" + pass + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Page.ClientScript.RegisterStartupScript(this.GetType(), "click","alert('Login Successful');");
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
What's the question here?
Modern DBMS SQL2008 have a variety of ways of dealing with BLOBs which aren't just sticking in them in a table. There are pros and cons, of course, and you might need to think about it a little deeper.
This is an interesting paper, by the late (?) Jim Gray
To BLOB or Not To BLOB: Large Object Storage in a Database or a Filesystem
For Android API level of 8.0.0, you should use
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
instead of
LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL
or SYSTEM_ALERT
.
Example of export in file with full path on Windows and in case your file has headers:
df.to_csv (r'C:\Users\John\Desktop\export_dataframe.csv', index = None, header=True)
For example, if you want to store the file in same directory where your script is, with utf-8 encoding and tab as separator:
df.to_csv(r'./export/dftocsv.csv', sep='\t', encoding='utf-8', header='true')
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
You can try this to simple date format valdation
public Date validateDateFormat(String dateToValdate) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HHmmss");
//To make strict date format validation
formatter.setLenient(false);
Date parsedDate = null;
try {
parsedDate = formatter.parse(dateToValdate);
System.out.println("++validated DATE TIME ++"+formatter.format(parsedDate));
} catch (ParseException e) {
//Handle exception
}
return parsedDate;
}
With the use of the bootstrap 4 utilities you could horizontally center an element itself by setting the horizontal margins to 'auto'.
To set the horizontal margins to auto you can use mx-auto
. The m
refers to margin and the x
will refer to the x-axis (left+right) and auto
will refer to the setting. So this will set the left margin and the right margin to the 'auto' setting. Browsers will calculate the margin equally and center the element. The setting will only work on block elements so the display:block needs to be added and with the bootstrap utilities this is done by d-block
.
<button type="submit" class="btn btn-primary mx-auto d-block">Submit</button>
You can consider all browsers to fully support auto margin settings according to this answer Browser support for margin: auto so it's safe to use.
The bootstrap 4 class text-center
is also a very good solution, however it needs a parent wrapper element. The benefit of using auto margin is that it can be done directly on the button element itself.
I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.
Strings in python are immutable, so you cannot treat them as a list and assign to indices.
Use .replace()
instead:
line = line.replace(';', ':')
If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:
line = line[:10].replace(';', ':') + line[10:]
That'll replace all semi-colons in the first 10 characters of the string.
You can call net start "service name"
on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.
To prevent a long line of commands in a text file, I keep my copy-pase snippets like this:
echo a;\
echo b;\
echo c
In newer versions of VS Code, you navigate to settings (Ctrl+,), and make sure to select Workspace Settings at the top right.
Then add a files.exclude
option to specify patterns to exclude.
You can also add search.exclude
if you only want to exclude a file from search results, and not from the folder explorer.
While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begin
s and end
s?
Wouldn't you want something, you know, simpler?
(Scroll down to main
for the punchline)
#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>
template<typename C,typename=void> struct can_reserve: std::false_type {};
template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
std::true_type
{};
template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;
template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;
template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing
template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
decltype( std::declval<C>().size() ),
decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};
namespace adl_aux {
using std::begin; using std::end;
template<typename C>
auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
template<typename C>
auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;
template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
return c.size();
}
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
using std::begin; using std::end;
return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
!std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
return 0;
};
template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
return i;
}
#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
using std::begin; using std::end;
try_reserve( c1, size_at_least(c1) + size_at_least(c2) );
using is_rvref = std::is_rvalue_reference<C2&&>;
c1.insert( end(c1),
try_make_move_iterator(begin(c2), is_rvref{}),
try_make_move_iterator(end(c2), is_rvref{}) );
return std::forward<C1>(c1);
}
struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
LHS lhs;
template<typename RHS>
LHS&& operator=( RHS&& rhs ) {
return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
}
};
template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}
template<typename C>
void print_container( C&& c ) {
for( auto&& x:c )
std::cout << x << ",";
std::cout << "\n";
};
int main() {
std::vector<int> a = {0,1,2};
std::vector<int> b = {3,4,5};
print_container(a);
print_container(b);
a +append= b;
const int arr[] = {6,7,8};
a +append= arr;
print_container(a);
print_container(b);
std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
print_container(d);
std::vector<double> c = std::move(d) +append+ a;
print_container(c);
print_container(d);
std::vector<double> e = c +append+ std::move(a);
print_container(e);
print_container(a);
}
hehe.
Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.
Note that the above does not compile in clang thanks to the EnableFunctionIf<>...
technique. In clang this workaround works.
equals
if hashCode
differs.hashCode
if (obj1 == obj2)
.hashCode
and/or equals
just to iterate - you're not comparing objectsHow about just this?
org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));
You can use a constant (i.e. a static, final variable) as the parameter for an annotation. As a quick example, I use something like this fairly often:
import org.junit.Test;
import static org.junit.Assert.*;
public class MyTestClass
{
private static final int TEST_TIMEOUT = 60000; // one minute per test
@Test(timeout=TEST_TIMEOUT)
public void testJDK()
{
assertTrue("Something is very wrong", Boolean.TRUE);
}
}
Note that it's possible to pass the TEST_TIMEOUT
constant straight into the annotation.
Offhand, I don't recall ever having tried this with an array, so you may be running into some issues with slight differences in how arrays are represented as annotation parameters compared to Java variables? But as for the other part of your question, you could definitely use a constant String without any problems.
EDIT: I've just tried this with a String array, and didn't run into the problem you mentioned - however the compiler did tell me that the "attribute value must be constant" despite the array being defined as public static final String[]
. Perhaps it doesn't like the fact that arrays are mutable? Hmm...
Try this:
schtasks /change /ENABLE /tn "Auto Restart" /s mycomutername /u mycomputername\username/p mypassowrd
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
The assertNotNull()
method means "a passed parameter must not be null
": if it is null then the test case fails.
The assertNull()
method means "a passed parameter must be null
": if it is not null then the test case fails.
String str1 = null;
String str2 = "hello";
// Success.
assertNotNull(str2);
// Fail.
assertNotNull(str1);
// Success.
assertNull(str1);
// Fail.
assertNull(str2);
Might be it will help someone, 4 level and 2 child's on each level
Library.Include(a => a.Library.Select(b => b.Library.Select(c => c.Library)))
.Include(d=>d.Book.)
.Include(g => g.Library.Select(h=>g.Book))
.Include(j => j.Library.Select(k => k.Library.Select(l=>l.Book)))
For Windows server 2012 -> Go to Server manager -> Remove Roles and Features -> Server Roles -> Web Server (IIS) -> Web Server -> Common HTTP Features -> Uncheck WebDAV Publishing and remove it -> Restart server.
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);
class Wrapper{
int number;
String title;
}
Seems to work fine. But there is an extra ,
Comma in your string.
[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
You can use logeek, It allows you to control your log messages visibility. Here is how you do that:
<script src="bower_components/dist/logeek.js"></script>
logeek.show('security');
logeek('some message').at('copy'); //this won't be logged
logeek('other message').at('secturity'); //this would be logged
You can also logeek.show('nothing')
to totally disable every log message.
Reflection; for an instance:
obj.GetType().GetProperties();
for a type:
typeof(Foo).GetProperties();
for example:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
Following feedback...
null
as the first argument to GetValue
GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
(which returns all public/private instance properties ).Iterator through keySet
will give you keys. You should use entrySet
if you want to iterate entries.
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
Iterator iter = (Iterator) hm.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey() + " - " + entry.getValue());
}
Subset sum problem can be solved in O(sum*n) using dynamic programming. Optimal substructure for subset sum is as follows:
SubsetSum(A, n, sum) = SubsetSum(A, n-1, sum) || SubsetSum(A, n-1, sum-set[n-1])
SubsetSum(A, n, sum) = 0, if sum > 0 and n == 0 SubsetSum(A, n, sum) = 1, if sum == 0
Here A is array of elements, n is the number of elements of array A and sum is the sum of elements in the subset.
Using this dp, you can solve for the number of subsets for the sum.
For getting subset elements, we can use following algorithm:
After filling dp[n][sum] by calling SubsetSum(A, n, sum), we recursively traverse it from dp[n][sum]. For cell being traversed, we store path before reaching it and consider two possibilities for the element.
1) Element is included in current path.
2) Element is not included in current path.
Whenever sum becomes 0, we stop the recursive calls and print current path.
void findAllSubsets(int dp[], int A[], int i, int sum, vector<int>& p) {
if (sum == 0) {
print(p);
return;
}
// If sum can be formed without including current element
if (dp[i-1][sum])
{
// Create a new vector to store new subset
vector<int> b = p;
findAllSubsets(dp, A, i-1, sum, b);
}
// If given sum can be formed after including
// current element.
if (sum >= A[i] && dp[i-1][sum-A[i]])
{
p.push_back(A[i]);
findAllSubsets(dp, A, i-1, sum-A[i], p);
}
}
Use this code it works perfectly for odd or even list sizes. Hope it help somebody .
int listSize = listOfArtist.size();
int mid = 0;
if (listSize % 2 == 0) {
mid = listSize / 2;
Log.e("Parting", "You entered an even number. mid " + mid
+ " size is " + listSize);
} else {
mid = (listSize + 1) / 2;
Log.e("Parting", "You entered an odd number. mid " + mid
+ " size is " + listSize);
}
//sublist returns List convert it into arraylist * very important
leftArray = new ArrayList<ArtistModel>(listOfArtist.subList(0, mid));
rightArray = new ArrayList<ArtistModel>(listOfArtist.subList(mid,
listSize));
From the documentation:
/is
Includes the same files./it
Includes "tweaked" files.
"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.
robocopy src dst sample.txt /is # copy if attributes are equal
robocopy src dst sample.txt /it # copy if attributes differ
robocopy src dst sample.txt /is /it # copy irrespective of attributes
This answer on Super User has a good explanation of what kind of files the selection parameters match.
With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy
generated in my tests I would consider this a bug.
PS C:\temp> New-Item src -Type Directory >$null PS C:\temp> New-Item dst -Type Directory >$null PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Modified 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Same 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\src\sample.txt test001 PS C:\temp> Get-Content .\dst\sample.txt test002
The file is listed as copied, and since it becomes a same file after the first robocopy
run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall
). The behavior also doesn't change if the data flag is set explicitly (/copy:d
).
I had to modify the last write time to get robocopy
to actually synchronize the data.
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date) PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ 100% Newer 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\dst\sample.txt test001
An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy
to copy the data:
& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
Where-Object { $_.Trim() } |
ForEach-Object {
$f = Get-Item $_
$f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
}
& robocopy src dst /copyall /mir
Switching to xcopy
is probably your best option:
& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y
Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select
, and need to prepend a select
also to the list. Finally, you need to provide aliases for the table and column in you subselect:
Create Table #IMEIS(
imei varchar(15)
)
INSERT INTO #IMEIS(imei)
SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;
But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.
Assuming a forward-compatible context in OpenGL 3 and up, you can either use glPolygonMode
as mentioned before, but note that lines with thickness more than 1px are now deprecated. So while you can draw triangles as wire-frame, they need to be very thin. In OpenGL ES, you can use GL_LINES
with the same limitation.
In OpenGL it is possible to use geometry shaders to take incoming triangles, disassemble them and send them for rasterization as quads (pairs of triangles really) emulating thick lines. Pretty simple, really, except that geometry shaders are notorious for poor performance scaling.
What you can do instead, and what will also work in OpenGL ES is to employ fragment shader. Think of applying a texture of wire-frame triangle to the triangle. Except that no texture is needed, it can be generated procedurally. But enough talk, let's code. Fragment shader:
in vec3 v_barycentric; // barycentric coordinate inside the triangle
uniform float f_thickness; // thickness of the rendered lines
void main()
{
float f_closest_edge = min(v_barycentric.x,
min(v_barycentric.y, v_barycentric.z)); // see to which edge this pixel is the closest
float f_width = fwidth(f_closest_edge); // calculate derivative (divide f_thickness by this to have the line width constant in screen-space)
float f_alpha = smoothstep(f_thickness, f_thickness + f_width, f_closest_edge); // calculate alpha
gl_FragColor = vec4(vec3(.0), f_alpha);
}
And vertex shader:
in vec4 v_pos; // position of the vertices
in vec3 v_bc; // barycentric coordinate inside the triangle
out vec3 v_barycentric; // barycentric coordinate inside the triangle
uniform mat4 t_mvp; // modeview-projection matrix
void main()
{
gl_Position = t_mvp * v_pos;
v_barycentric = v_bc; // just pass it on
}
Here, the barycentric coordinates are simply (1, 0, 0)
, (0, 1, 0)
and (0, 0, 1)
for the three triangle vertices (the order does not really matter, which makes packing into triangle strips potentially easier).
The obvious disadvantage of this approach is that it will eat some texture coordinates and you need to modify your vertex array. Could be solved with a very simple geometry shader but I'd still suspect it will be slower than just feeding the GPU with more data.
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
You can also use Postman App for Windows, Linux or OSX. It is a complete web app & service test environment that involve all the request methods. You can find the latest version here.
I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
/**
* It is the parameter is to show arguments in the method or the class.
*/
boolean showArguments() default false;
}
@Aspect
@Component
public class AnnotationLoggerAspect {
@Autowired
private Logger logger;
private static final String METHOD_NAME = "METHOD NAME: {} ";
private static final String ARGUMENTS = "ARGS: {} ";
@Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
public void logAdviceExecutionBefore(JoinPoint joinPoint){
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
if(annotationLogger!= null) {
StringBuilder annotationLoggerFormat = new StringBuilder();
List<Object> annotationLoggerArguments = new ArrayList<>();
annotationLoggerFormat.append(METHOD_NAME);
annotationLoggerArguments.add(codeSignature.getName());
if (annotationLogger.showArguments()) {
annotationLoggerFormat.append(ARGUMENTS);
List<?> argumentList = Arrays.asList(joinPoint.getArgs());
annotationLoggerArguments.add(argumentList.toString());
}
logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
}
}
private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
AnnotationLogger annotationLogger = null;
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = joinPoint.getTarget().getClass().
getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
if (method.isAnnotationPresent(AnnotationLogger.class)){
annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
}else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
}
return annotationLogger;
}catch(Exception e) {
return annotationLogger;
}
}
}
This isn't a function of bash
, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.
In Perl for example, this could be accomplished by setting:
$| = 1;
See perlvar for more information on this.
Just add throw
where needed, and try
block to the caller that handles the error. By convention you should only throw things that derive from std::exception
, so include <stdexcept>
first.
int compare(int a, int b) {
if (a < 0 || b < 0) {
throw std::invalid_argument("a or b negative");
}
}
void foo() {
try {
compare(-1, 0);
} catch (const std::invalid_argument& e) {
// ...
}
}
Also, look into Boost.Exception.
For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:
df.insert(0, 'New_ID', df.index + 880)
if you want New_ID
to be the first column. Otherwise this if you don't mind it being at the end:
df['New_ID'] = df.index + 880
You are missing a space between else
and if
It should be else if
instead of elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}
Happened to me with the directory utils
. I was trying to import this directory as:
from utils import somefile
utils
is already a package in python. Just change your directory name to something different and it should work just fine.
This picture will remove everyone's confusion hopefully which is collected from there.
Like Unix shells, PowerShell supports >
redirects with most of the variations known from Unix, including 2>&1
(though weirdly, order doesn't matter - 2>&1 > file
works just like the normal > file 2>&1
).
Like most modern Unix shells, PowerShell also has a shortcut for redirecting both standard error and standard output to the same device, though unlike other redirection shortcuts that follow pretty much the Unix convention, the capture all shortcut uses a new sigil and is written like so: *>
.
So your implementation might be:
& myjob.bat *>> $logfile
It behaves the way you want if called as a function:
>>> def test():
... a = iter(list(range(10)))
... for i in a:
... print(i)
... next(a)
...
>>> test()
0
2
4
6
8
This ones a little old but was high in the google ranking so I thought I would throw in the answer I found from Chrome, pdf display, Duplicate headers received from the server
Basically my problem also was that the filename contained commas. Do a replace on commas to remove them and you should be fine. My function to make a valid filename is below.
public static string MakeValidFileName(string name)
{
string invalidChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
string invalidReStr = string.Format(@"[{0}]+", invalidChars);
string replace = Regex.Replace(name, invalidReStr, "_").Replace(";", "").Replace(",", "");
return replace;
}
Depending on how you can organize your code, another option can be to put the environment variable within a function that's executed at runtime.
In this file, the environment variable is set at import time and requires dynamic require
s in order to test different environment variables (as described in this answer):
const env = process.env.MY_ENV_VAR;
const envMessage = () => `MY_ENV_VAR is set to ${env}!`;
export default myModule;
In this file, the environment variable is set at envMessage
execution time, and you should be able to mutate process.env directly in your tests:
const envMessage = () => {
const env = process.env.MY_VAR;
return `MY_ENV_VAR is set to ${env}!`;
}
export default myModule;
Jest test:
const vals = [
'ONE',
'TWO',
'THREE',
];
vals.forEach((val) => {
it(`Returns the correct string for each ${val} value`, () => {
process.env.MY_VAR = val;
expect(envMessage()).toEqual(...
isfar<-load("C:/Users/isfar.RData")
if(is.data.frame(isfar)){
names(isfar)
}
If isfar is a dataframe, this will print out the names of its columns.
Update for Laravel 6
Now that Laravel 6 is released you need to install laravel/ui
.
composer require laravel/ui --dev
php artisan ui vue --auth
You can change vue
with react
if you use React in your project (see Using React).
And then you need to perform the migrations and compile the frontend
php artisan migrate
npm install && npm run dev
Source : Laravel Documentation for authentication
Want to get started fast? Install the laravel/ui Composer package and run php artisan ui vue --auth in a fresh Laravel application. After migrating your database, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These commands will take care of scaffolding your entire authentication system!
Note: That's only if you want to use scaffolding, you can use the default User model and the Eloquent authentication driver.
You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage
You can use the with
template tag.
{% with name="World" %}
<html>
<div>Hello {{name}}!</div>
</html>
{% endwith %}
As others already noted, in one case you are attempting to return cString
(which is a char *
value in this context - a pointer) from a function that is declared to return a char
(which is an integer). In another case you do the reverse: you are assigning a char
return value to a char *
pointer. This is what triggers the warnings. You certainly need to declare your return values as char *
, not as char
.
Note BTW that these assignments are in fact constraint violations from the language point of view (i.e. they are "errors"), since it is illegal to mix pointers and integers in C like that (aside from integral constant zero). Your compiler is simply too forgiving in this regard and reports these violations as mere "warnings".
What I also wanted to note is that in several answers you might notice the relatively strange suggestion to return void
from your functions, since you are modifying the string in-place. While it will certainly work (since you indeed are modifying the string in-place), there's nothing really wrong with returning the same value from the function. In fact, it is a rather standard practice in C language where applicable (take a look at the standard functions like strcpy
and others), since it enables "chaining" of function calls if you choose to use it, and costs virtually nothing if you don't use "chaining".
That said, the assignments in your implementation of compareString
look complete superfluous to me (even though they won't break anything). I'd either get rid of them
int compareString(char cString1[], char cString2[]) {
// To lowercase
strToLower(cString1);
strToLower(cString2);
// Do regular strcmp
return strcmp(cString1, cString2);
}
or use "chaining" and do
int compareString(char cString1[], char cString2[]) {
return strcmp(strToLower(cString1), strToLower(cString2));
}
(this is when your char *
return would come handy). Just keep in mind that such "chained" function calls are sometimes difficult to debug with a step-by-step debugger.
As an additional, unrealted note, I'd say that implementing a string comparison function in such a destructive fashion (it modifies the input strings) might not be the best idea. A non-destructive function would be of a much greater value in my opinion. Instead of performing as explicit conversion of the input strings to a lower case, it is usually a better idea to implement a custom char-by-char case-insensitive string comparison function and use it instead of calling the standard strcmp
.
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
Shortcut for the Mac: (ctrl + opt + o)
try
$locationProvider.html5Mode(true)
More info at
$locationProvider
Using $location
HashMap has no concept of position so there is no way to get an object by position. Objects in Maps are set and get by keys.
like this?
DF <- data.frame("a" = as.character(0:5),
"b" = paste(0:5, ".1", sep = ""),
"c" = paste(10:15),
stringsAsFactors = FALSE)
DF <- apply(DF, 2, as.numeric)
If there are "real" characters in dataframe like 'a' 'b' 'c', i would recommend answer from davsjob.
I originally came in here to find how to make PyTest
print in VSCode's console while running/debugging the unit test from there. This can be done with the following launch.json
configuration. Given .venv
the virtual environment folder.
"version": "0.2.0",
"configurations": [
{
"name": "PyTest",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config:python.pythonPath}",
"module": "pytest",
"args": [
"-sv"
],
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.venv",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
]
}
The answer to your question depends on what your learning goals are. If you are trying to get matrices to "click" so you can use them later, I would suggest looking at a Numpy array
instead of a list of lists. This will let you slice out rows and columns and subsets easily. Just try to get a column from a list of lists and you will be frustrated.
Let's take your list of lists for example:
L = [list("ABCDE") for i in range(5)]
It is easy to get sub-elements for any row:
>>> L[1][0:3]
['A', 'B', 'C']
Or an entire row:
>>> L[1][:]
['A', 'B', 'C', 'D', 'E']
But try to flip that around to get the same elements in column format, and it won't work...
>>> L[0:3][1]
['A', 'B', 'C', 'D', 'E']
>>> L[:][1]
['A', 'B', 'C', 'D', 'E']
You would have to use something like list comprehension to get all the 1th elements....
>>> [x[1] for x in L]
['B', 'B', 'B', 'B', 'B']
If you use an array instead, you will get the slicing and indexing that you expect from MATLAB or R, (or most other languages, for that matter):
>>> import numpy as np
>>> Y = np.array(list("ABCDE"*5)).reshape(5,5)
>>> print Y
[['A' 'B' 'C' 'D' 'E']
['A' 'B' 'C' 'D' 'E']
['A' 'B' 'C' 'D' 'E']
['A' 'B' 'C' 'D' 'E']
['A' 'B' 'C' 'D' 'E']]
>>> print Y.transpose()
[['A' 'A' 'A' 'A' 'A']
['B' 'B' 'B' 'B' 'B']
['C' 'C' 'C' 'C' 'C']
['D' 'D' 'D' 'D' 'D']
['E' 'E' 'E' 'E' 'E']]
Grab row 1 (as with lists):
>>> Y[1,:]
array(['A', 'B', 'C', 'D', 'E'],
dtype='|S1')
Grab column 1 (new!):
>>> Y[:,1]
array(['B', 'B', 'B', 'B', 'B'],
dtype='|S1')
So now to generate your printed matrix:
for mycol in Y.transpose():
print " ".join(mycol)
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
Javascript programming language supports functional programming paradigm so you can do easily with these codes.
var data = [
{"Id": "1", "Status": "Valid"},
{"Id": "2", "Status": "Invalid"}
];
var isValid = function(data){
return data.Status === "Valid";
};
var valids = data.filter(isValid);
Just use .split(',')
:
var str = "How are you doing today?";
var n = str.split(" ");
Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5
jQuery.parseXML( data )
Returns: XMLDocument
On MAC
Step 1: Alt + Cmd + F . At the bottom, a window appears Step 2: Enable Regular Expression. Left side on the window, looks like .* Step 3: Enter text to you want to find in the Find input field Step 4: Enter replace text in the Replace input field Step 5: Click on Replace All - Right bottom.
Go to application/config/autoload.php
$autoload['helper'] = array('url');
add this on top anywhere
and at this in controller
function __construct()
{
parent::__construct();
$this->load->helper('url');
}
Whether a value in an int is signed or unsigned depends on how the bits are interpreted - Java interprets bits as a signed value (it doesn't have unsigned primitives).
If you have an int that you want to interpret as an unsigned value (e.g. you read an int from a DataInputStream
that you know should be interpreted as an unsigned value) then you can do the following trick.
int fourBytesIJustRead = someObject.getInt();
long unsignedValue = fourBytesIJustRead & 0xffffffffL;
Note, that it is important that the hex literal is a long literal, not an int literal - hence the 'L' at the end.
$('.class').length
This one does not work for me. I'd rather use this:
$('.class').children().length
I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.
i think better to do this
if ( $request->hasFile('file')){
if ($request->file('file')->isValid()){
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('images' , $name);
$inputs = $request->all();
$inputs['path'] = $name;
}
}
Post::create($inputs);
actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory
The date format for mysql insert query is YYYY-MM-DD
example:
INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');
What about something like this.
<div id="movie_item">
<div class="movie_item_poster">
<img src="..." style="max-width: 100%; max-height: 100%;">
</div>
<div id="movie_item_content">
<div class="movie_item_content_year">year</div>
<div class="movie_item_content_title">title</div>
<div class="movie_item_content_plot">plot</div>
</div>
<div class="movie_item_toolbar">
Lorem Ipsum...
</div>
</div>
You don't have to float both movie_item_poster
AND movie_item_content
. Just float one of them...
#movie_item {
position: relative;
margin-top: 10px;
height: 175px;
}
.movie_item_poster {
float: left;
height: 150px;
width: 100px;
}
.movie_item_content {
position: relative;
}
.movie_item_content_title {
}
.movie_item_content_year {
float: right;
}
.movie_item_content_plot {
}
.movie_item_toolbar {
clear: both;
vertical-align: bottom;
width: 100%;
height: 25px;
}
Below is a fully functional example of what I believe you're trying to do (with a functional snippet).
Based on your question, you seem to be modifying 1 property in state
for all of your elements. That's why when you click on one, all of them are being changed.
In particular, notice that the state tracks an index of which element is active. When MyClickable
is clicked, it tells the Container
its index, Container
updates the state
, and subsequently the isActive
property of the appropriate MyClickable
s.
class Container extends React.Component {_x000D_
state = {_x000D_
activeIndex: null_x000D_
}_x000D_
_x000D_
handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
</div>_x000D_
}_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
handleClick = () => this.props.onClick(this.props.index)_x000D_
_x000D_
render() {_x000D_
return <button_x000D_
type='button'_x000D_
className={_x000D_
this.props.isActive ? 'active' : 'album'_x000D_
}_x000D_
onClick={ this.handleClick }_x000D_
>_x000D_
<span>{ this.props.name }</span>_x000D_
</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
display: block;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable
elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
You can pass values from one page to another by followings..
Response.Redirect
Cookies
Application Variables
HttpContext
Response.Redirect
SET :
Response.Redirect("Defaultaspx?Name=Pandian");
GET :
string Name = Request.QueryString["Name"];
Cookies
SET :
HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian";
GET :
string name = Request.Cookies["Name"].Value;
Application Variables
SET :
Application["Name"] = "pandian";
GET :
string Name = Application["Name"].ToString();
Refer the full content here : Pass values from one to another
have you looked at layoutIfNeeded?
The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?
layoutIfNeeded Lays out the subviews if needed.
- (void)layoutIfNeeded
Discussion Use this method to force the layout of subviews before drawing.
Availability Available in iPhone OS 2.0 and later.
>>> from datetime import date
>>>
>>> repr(date.today()) # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
>>> eval(_) # _ is the output of the last command
datetime.date(2009, 1, 16)
The output is a string that can be parsed by the python interpreter and results in an equal object.
If that's not possible, it should return a string in the form of <...some useful description...>
.
For your first question try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
(available since API 8)
To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.
What worked for me was fs.promises.
Example One:
const fs = require("fs")
fs.promises
.writeFile(__dirname + '/test.json', "data", { encoding: 'utf8' })
.then(() => {
// Do whatever you want to do.
console.log('Done');
});
Example Two. Using Async-Await:
const fs = require("fs")
async function writeToFile() {
await fs.promises.writeFile(__dirname + '/test-22.json', "data", {
encoding: 'utf8'
});
console.log("done")
}
writeToFile()
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
my problem was not including the ../ before the image name
background-image: url("../image.png");
My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.
Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely +
and /
, and maybe =
too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.
You can use the HttpUtility.UrlEncode
method to encode your Base64 string:
string msg = "Please click on the link below or paste it into a browser "
+ "to verify your email account.<br /><br /><a href=\""
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";
This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.
One solution is to warn the user that the app needs non-private mode to work.
UPDATE: This has been fixed in Safari 11, so the behaviour is now aligned with other browsers.
I found that in my code when I used a ration or percentage for line-height line-height;1.5;
My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px;
so that I could predict exactly how many pixels each page would take with a given number of lines.
I would think that now you have the range for each of the row, you can easily manipulate that range with the offset(row, column) action? What is the point of counting the records filtered (unless you need that count in a variable)? So instead of (or as well as in the same block) write your code action to move each row to an empty hidden sheet and once all done, you can do any work you like from the transferred range data?
You can find more information directly on this link: http://datatables.net/examples/basic_init/filter_only.html
$(document).ready(function() {
$('#example').dataTable({
"bPaginate": false,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false });
});
Hope that helps !
EDIT : If you are lazy, "bLengthChange": false, is the one you need to change :)
Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:
Development Provisioning Profile
allows you to do itDistribution Provisioning Profile
[About] and Apple after review reassign it by they own keyDevelopment Provisioning Profile
is stored on device and contains:
Xcode
by default take cares about
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
Since function pointers are often typed callbacks, you might want to have a look at type safe callbacks. The same applies to entry points, etc of functions that are not callbacks.
C is quite fickle and forgiving at the same time :)
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
OFFICE 2013 INSTRUCTIONS:
(For Windows 7 (x64) | MS Office 32-Bit)
Option 1 | Check if ability already exists | 2 minutes
Option 2 | The "Monthview" Control doesn't currently exist | 5 minutes
Okay, either of these two steps should work for you if you have Office 2013 (32-Bit) on Windows 7 (x64). Some of the steps may be different if you have a different combo of Windows 7 & Office 2013.
The "Monthview" control will be your fully fleshed out 'DatePicker'. It comes equipped with its own properties and image. It works very well. Good luck.
Site: "bonCodigo" from above (this is an updated extension of his work)
Site: "AMM" from above (this is just an exension of his addition)
Site: Various Microsoft Support webpages
I use this one to check every 10 seconds process is running and start if not and allows multiple arguments:
#!/bin/sh
PROCESS="$1"
PROCANDARGS=$*
while :
do
RESULT=`pgrep ${PROCESS}`
if [ "${RESULT:-null}" = null ]; then
echo "${PROCESS} not running, starting "$PROCANDARGS
$PROCANDARGS &
else
echo "running"
fi
sleep 10
done
Here's my code that works, as of today, with some of the latest browsers.
Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.
String userAgent = "Unknown";
String osType = "Unknown";
String osVersion = "Unknown";
String browserType = "Unknown";
String browserVersion = "Unknown";
String deviceType = "Unknown";
try {
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
//userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
boolean exceptionTest = false;
if(exceptionTest) throw new Exception("EXCEPTION TEST");
if (userAgent.indexOf("Windows NT") >= 0) {
osType = "Windows";
osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));
} else if (userAgent.indexOf("Mac OS") >= 0) {
osType = "Mac";
osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));
if(userAgent.indexOf("iPhone") >= 0) {
deviceType = "iPhone";
} else if(userAgent.indexOf("iPad") >= 0) {
deviceType = "iPad";
}
} else if (userAgent.indexOf("X11") >= 0) {
osType = "Unix";
osVersion = "Unknown";
} else if (userAgent.indexOf("android") >= 0) {
osType = "Android";
osVersion = "Unknown";
}
logger.trace("end of os section");
if (userAgent.contains("Edge/")) {
browserType = "Edge";
browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];
} else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
browserType = "Safari";
browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];
} else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
browserType = "Opera";
browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];
} else if (userAgent.contains("Chrome/")) {
browserType = "Chrome";
browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
browserVersion = browserVersion.split(" ")[0];
} else if (userAgent.contains("Firefox/")) {
browserType = "Firefox";
browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
}
logger.trace("end of browser section");
} catch (Exception ex) {
logger.error("ERROR: " +ex);
}
logger.debug(
"\n userAgent: " + userAgent
+ "\n osType: " + osType
+ "\n osVersion: " + osVersion
+ "\n browserType: " + browserType
+ "\n browserVersion: " + browserVersion
+ "\n deviceType: " + deviceType
);
Logger Output:
userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
osType: Windows
osVersion: 10.0
browserType: Opera
browserVersion: 60.0.3255.165
deviceType: Unknown
This is slightly modified version of @aandis answer. When it comes to raw string, prefix 'r' character before the string. For example:
sql = r"""
SELECT field1, field2, field3, field4
FROM table
WHERE condition1 = 1
AND condition2 = 2;
"""
This is recommended when your query has any special character like '\' which requires escaping and lint tools like flake8 reports it as error.
For Linux users, assuming you run a compositing window manager (Compiz), you can just turn the window negative. I use Eclipse like this all the time, the normal (whitie) looks is blowing my eyes off.
You can use javax.xml.bind.DatatypeConverter
class
DatatypeConverter.printDateTime
&
DatatypeConverter.parseDateTime
Instead of using this
as the accepted answer suggests, use $parent
instead. So in your partial1.html
you'll have:
<form ng-submit="$parent.addLine()">
<input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>
If you want to learn more about the scope in ng-include
or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include
As all answers posted above are well explained, I want to add something which I faced today.
When you export something using exports then you have to use it with variable. Like,
File1.js
exports.a = 5;
In another file
File2.js
const A = require("./File1.js");
console.log(A.a);
and using module.exports
File1.js
module.exports.a = 5;
In File2.js
const A = require("./File1.js");
console.log(A.a);
and default module.exports
File1.js
module.exports = 5;
in File2.js
const A = require("./File2.js");
console.log(A);
If you are using AppCompatActivity
then add this in styles.xml
<style name="TransparentCompat" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation</item>
</style>
In manifest
file you can add this theme to activity tag like this
android:theme="@style/TransparentCompat"
for more details read this article
A char
doesn't have any methods - it's a Java primitive. You're looking for the Character wrapper class.
The usage would be:
if(Character.isLetter(ch)) { //... }
Add the below to your manifest:
<activity android:name=".AppPreferenceActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Using the onMouseLeave event prevents bubbling and allows you to easily detect when the mouse leaves the browser window.
<html onmouseleave="alert('You left!')"></html>
This is a MultiThreading Issue and Using Properly Synchronized Blocks This can be prevented. Without putting extra things on UI Thread and causing loss of responsiveness of app.
I also faced the same. And as the most accepted answer suggests making change to adapter data from UI Thread can solve the issue. That will work but is a quick and easy solution but not the best one.
As you can see for a normal case. Updating data adapter from background thread and calling notifyDataSetChanged in UI thread works.
This illegalStateException arises when a ui thread is updating the view and another background thread changes the data again. That moment causes this issue.
So if you will synchronize all the code which is changing the adapter data and making notifydatasetchange call. This issue should be gone. As gone for me and i am still updating the data from background thread.
Here is my case specific code for others to refer.
My loader on the main screen loads the phone book contacts into my data sources in the background.
@Override
public Void loadInBackground() {
Log.v(TAG, "Init loadings contacts");
synchronized (SingleTonProvider.getInstance()) {
PhoneBookManager.preparePhoneBookContacts(getContext());
}
}
This PhoneBookManager.getPhoneBookContacts reads contact from phonebook and fills them in the hashmaps. Which is directly usable for List Adapters to draw list.
There is a button on my screen. That opens a activity where these phone numbers are listed. If i directly setAdapter over the list before the previous thread finishes its work which is fast naviagtion case happens less often. It pops up the exception .Which is title of this SO question. So i have to do something like this in the second activity.
My loader in the second activity waits for first thread to complete. Till it shows a progress bar. Check the loadInBackground of both the loaders.
Then it creates the adapter and deliver it to the activity where on ui thread i call setAdapter.
That solved my issue.
This code is a snippet only. You need to change it to compile well for you.
@Override
public Loader<PhoneBookContactAdapter> onCreateLoader(int arg0, Bundle arg1) {
return new PhoneBookContactLoader(this);
}
@Override
public void onLoadFinished(Loader<PhoneBookContactAdapter> arg0, PhoneBookContactAdapter arg1) {
contactList.setAdapter(adapter = arg1);
}
/*
* AsyncLoader to load phonebook and notify the list once done.
*/
private static class PhoneBookContactLoader extends AsyncTaskLoader<PhoneBookContactAdapter> {
private PhoneBookContactAdapter adapter;
public PhoneBookContactLoader(Context context) {
super(context);
}
@Override
public PhoneBookContactAdapter loadInBackground() {
synchronized (SingleTonProvider.getInstance()) {
return adapter = new PhoneBookContactAdapter(getContext());
}
}
}
Hope this helps
For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says
moment().valueOf()
or
+moment();
you can also get it through moment().format('x')
(or .format('X')
[capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.
My code worked fine on all machines but only on this one started giving problem (which used to work find I guess). Used echo "document_root" path to debug and also looked closely at the error, found this
Warning: include(D:/MyProjects/testproject//functions/connections.php): failed to open stream:
You can easily see where the problems are. The problems are // before functions
$document_root = $_SERVER['DOCUMENT_ROOT'];
echo "root: $document_root";
include($document_root.'/functions/connections.php');
So simply remove the lading / from include and it should work fine. What is interesting is this behaviors is different on different versions. I run the same code on Laptop, Macbook Pro and this PC, all worked fine untill. Hope this helps someone.
Hi sorry for bump this post just face this problem and i would like to show my case.
My code look like this.
<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>
Javascript code
<script>
var product = {
// Define your function
'add':(product_id)=>{
// Do some thing here
},
'delete':(product_id)=>{
// Do some thig here
}
}
</script>
Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):
SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X
Try Shift-Tab-Tab
a bigger documentation appears, than with Shift-Tab
. It's the same but you can scroll down.
Shift-Tab-Tab-Tab
and the tooltip will linger for 10 seconds while you type.
Shift-Tab-Tab-Tab-Tab
and the docstring appears in the pager (small part at the bottom of the window) and stays there.
Added some more logic to solution provided by @Andrew Burgess. Here is the full solution:
Created a action filter to get errors for ajax request:
public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode =
(int)HttpStatusCode.BadRequest;
}
}
}
Added the filter to my controller method as:
[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}
Added a common script for jquery validation:
function onAjaxFormError(data) {
var form = this;
var errorResponse = data.responseJSON;
$.each(errorResponse, function (index, value) {
// Element highlight
var element = $(form).find('#' + value.key);
element = element[0];
highLightError(element, 'input-validation-error');
// Error message
var validationMessageElement = $('span[data-valmsg-for="' + value.key + '"]');
validationMessageElement.removeClass('field-validation-valid');
validationMessageElement.addClass('field-validation-error');
validationMessageElement.text(value.errors[0]);
});
}
$.validator.setDefaults({
ignore: [],
highlight: highLightError,
unhighlight: unhighlightError
});
var highLightError = function(element, errorClass) {
element = $(element);
element.addClass(errorClass);
}
var unhighLightError = function(element, errorClass) {
element = $(element);
element.removeClass(errorClass);
}
Finally added the error javascript method to my Ajax Begin form:
@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}
map
doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map
.
map
in Python 3 is equivalent to this:
def map(func, iterable):
for i in iterable:
yield func(i)
and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yield
ing.
Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map
, particularly if you're using a lambda expression as the first argument:
[func(i) for i in iterable]
As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -
>>> a = "hello, world"
>>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')
A use of map
here would be if you start with a list of strings instead of a single string - map
can listify all of them individually:
>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
Note that map(list, a)
is equivalent in Python 2, but in Python 3 you need the list
call if you want to do anything other than feed it into a for
loop (or a processing function such as sum
that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:
>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
I do believe the easiest way is to first go to instant and then to string like:
String d = new Date().toInstant().toString();
Which will result in:
2017-09-08T12:56:45.331Z
http://www.pip-installer.org/en/latest/installing.html is really the canonical answer to this question.
Specifically, the systemwide instructions are:
$ curl -O http://python-distribute.org/distribute_setup.py
$ python distribute_setup.py
$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ python get-pip.py
The section quoted in the question is the virtualenv
instructions rather than the systemwide ones. The easy_install
instructions have been around for longer, but it isn't necessary to do it that way any more.
get page content by page name:
<?php
$page = get_page_by_title( 'page-name' );
$content = apply_filters('the_content', $page->post_content);
echo $content;
?>
Another interesting variant question can be:
How would you make "12345"
as "12 23 34 45"
without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
A status code of 0 in an NSHTTPURLResponse
object generally means there was no response, and can occur for various reasons. The server will never return a status of 0 as this is not a valid HTTP status code.
In your case, you are appearing to get a status code of 0 because the request is timing out and 0 is just the default value for the property. The timeout itself could be for various reasons, such as the server simply not responding in time, being blocked by a firewall, or your entire network connection being down. Usually in the case of the latter though the phone is smart enough to know it doesn't have a network connection and will fail immediately. However, it will still fail with an apparent status code of 0.
Note that in cases where the status code is 0, the real error is captured in the returned NSError
object, not the NSHTTPURLResponse
.
HTTP status 408
is pretty uncommon in my experience. I've never encountered one myself. But it is apparently used in cases where the client needs to maintain an active socket connection to the server, and the server is waiting on the client to send more data over the open socket, but it doesn't in a given amount of time and the server ends the connection with a 408
status code, essentially telling the client "you took too long".
Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
and Java 8 you could do
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
Update: For pre 26 use Joda time
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);
In app/build.gradle file, add like this-
dependencies {
compile 'joda-time:joda-time:2.9.4'
}
Very nice solution by praneybehl, but if someone wants to save the data as a csv
file and using a blob
method then they can refer this:
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//this trick will generate a temp "a" tag
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
blob = new Blob([csv], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = (ReportTitle || 'UserExport') + '.csv';
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
Note that the answer provided by ViNce does NOT include the end date for the period.
If you are using PHP 5.3+, your best bet is to use a function like this:
/**
* Generate an array of string dates between 2 dates
*
* @param string $start Start date
* @param string $end End date
* @param string $format Output format (Default: Y-m-d)
*
* @return array
*/
function getDatesFromRange($start, $end, $format = 'Y-m-d') {
$array = array();
$interval = new DateInterval('P1D');
$realEnd = new DateTime($end);
$realEnd->add($interval);
$period = new DatePeriod(new DateTime($start), $interval, $realEnd);
foreach($period as $date) {
$array[] = $date->format($format);
}
return $array;
}
Then, you would call the function as expected:
getDatesFromRange('2010-10-01', '2010-10-05');
Note about DatePeriod
class: You can use the 4th parameter of DatePeriod to exclude the start date (DatePeriod::EXCLUDE_START_DATE
) but you cannot, at this time, include the end date.
find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash
bash 4 (recursive)
shopt -s globstar
for xls in /path/**/*.xls
do
xls2csv "$xls" "${xls%.xls}.csv"
done
python3
, self explanatory I guess
from urllib.parse import urlparse, urlencode, parse_qsl
url = 'https://www.linkedin.com/jobs/search?keywords=engineer'
parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)
print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
There are many metrics out there for evaluating whether two images look like/how much they look like.
I will not go into any code here, because I think it should be a scientific problem, other than a technical problem.
Generally, the question is related to human's perception on images, so each algorithm has its support on human visual system traits.
Classic approaches are:
Visible differences predictor: an algorithm for the assessment of image fidelity (https://www.spiedigitallibrary.org/conference-proceedings-of-spie/1666/0000/Visible-differences-predictor--an-algorithm-for-the-assessment-of/10.1117/12.135952.short?SSO=1)
Image Quality Assessment: From Error Visibility to Structural Similarity (http://www.cns.nyu.edu/pub/lcv/wang03-reprint.pdf)
FSIM: A Feature Similarity Index for Image Quality Assessment (https://www4.comp.polyu.edu.hk/~cslzhang/IQA/TIP_IQA_FSIM.pdf)
Among them, SSIM (Image Quality Assessment: From Error Visibility to Structural Similarity ) is the easiest to calculate and its overhead is also small, as reported in another paper "Image Quality Assessment Based on Gradient Similarity" (https://www.semanticscholar.org/paper/Image-Quality-Assessment-Based-on-Gradient-Liu-Lin/2b819bef80c02d5d4cb56f27b202535e119df988).
There are many more other approaches. Take a look at Google Scholar and search for something like "visual difference", "image quality assessment", etc, if you are interested/really care about the art.
Some answers are partially wrong, and some facts in them are partially wrong as well.
Answer your question: Yes! You can.
In Typescript
class A {
private a1;
private a2;
}
Generates the following code in Javascript:
var A = /** @class */ (function () {
function A() {
}
return A;
}());
as @Erik_Cupal said, you could just do:
let a = new A();
let array = return Object.getOwnPropertyNames(a);
But this is incomplete. What happens if your class has a custom constructor? You need to do a trick with Typescript because it will not compile. You need to assign as any:
let className:any = A;
let a = new className();// the members will have value undefined
A general solution will be:
class A {
private a1;
private a2;
constructor(a1:number, a2:string){
this.a1 = a1;
this.a2 = a2;
}
}
class Describer{
describeClass( typeOfClass:any){
let a = new typeOfClass();
let array = Object.getOwnPropertyNames(a);
return array;//you can apply any filter here
}
}
For better understanding this will reference depending on the context.
i had a situation to work generic now and used this:
class Test {
// your class definition
}
nameByType = function(type){
return type.prototype["constructor"]["name"];
};
console.log(nameByType(Test));
thats the only way i found to get the class name by type input if you don't have a instance of an object.
(written in ES2017)
dot notation also works fine
console.log(Test.prototype.constructor.name); // returns "Test"
For some time now, you can also only rely on the data.table
package and its IDate
class plus associated functions. (Check ?as.IDate()
). So, no need to additionally install lubridate
.
require(data.table)
some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions
if you send the variable from PHP, you can obtain it with this before sending:
$string=nl2br($string);
Try this Bulk Rename Utility It works well. Maybe not reinvent the wheel. If you don't necessary need a script this is a good way to go.
I have a similar thing going. I have a lot of cases where I do:
thedict = {}
for item in ('foo', 'bar', 'baz'):
mydict = thedict.get(item, {})
mydict = get_value_for(item)
thedict[item] = mydict
But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of
value = mydict.get('foo', {}).get('bar', {}).get('baz', 0)
So instead, I made:
def dictgetter(thedict, default, *args):
totalargs = len(args)
for i,arg in enumerate(args):
if i+1 == totalargs:
thedict = thedict.get(arg, default)
else:
thedict = thedict.get(arg, {})
return thedict
Which has the same effect if you do:
value = dictgetter(mydict, 0, 'foo', 'bar', 'baz')
Better? I think so.
Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.
Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile SourceFile, "C:\destfolder\", True
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
'Replace the file
fso.CopyFile SourceFile, "C:\destfolder\", True
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Else
'The file does not exist in the destination folder. Safe to copy file to this folder.
fso.CopyFile SourceFile, "C:\destfolder\", True
End If
Set fso = Nothing
jst create a new DB in mysql.Select that new DB.(if you r using mysql phpmyadmin now on the top it'l be like 'Server:...* >> Database ).Now go to import tab select file.Import!
From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
I had the same problem when setting the center of the map with map.setCenter()
. Using Number()
solved for me. Had to use parseFloat
to truncate the data.
code snippet:
var centerLat = parseFloat(data.lat).toFixed(0);
var centerLng = parseFloat(data.long).toFixed(0);
map.setCenter({
lat: Number(centerLat),
lng: Number(centerLng)
});
"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.
GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html
(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:
GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \
git clone myuser@myGitRemoteServer:/my/remote/git_repo/path
This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).
How about:
df['new_col'] = range(1, len(df) + 1)
Alternatively if you want the index to be the ranks and store the original index as a column:
df = df.reset_index()
How I update my deviceToken
First when I login I send the first device token under the user collection and the current logged in user.
After that, I just override onNewToken(token:String)
in my FirebaseMessagingService()
and just update that value if a new token is generated for that user
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
}
override fun onNewToken(token: String) {
super.onNewToken(token)
val currentUser= FirebaseAuth.getInstance().currentUser?.uid
if(currentUser != null){
FirebaseFirestore.getInstance().collection("user").document(currentUser).update("deviceToken",token)
}
}
}
Each time your app opens it will check for a new token, if the user is not yet signed in it will not update the token, if the user is already logged in you can check for a newToken
The ones method is much faster than using repmat:
>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds.
And, in my opinion, makes for much more readable code.
With Swift 2.0 and Xcode 7.0.1 you can create this function:
// Creates a UIColor from a Hex string.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
return UIColor.grayColor()
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
and then use it in this way:
let color1 = colorWithHexString("#1F437C")
Updated For Swift 4
func colorWithHexString (hex:String) -> UIColor {
var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
if (cString.characters.count != 6) {
return UIColor.gray
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
For me, it was because I was trying to pull a branch which was already deleted from Github.
If you do not find interest in overriding save
method, you can do
model_fields = [f.name for f in YourModel._meta.get_fields()]
valid_data = {
key: new_data[key]
for key in model_fields
if key in new_data.keys()
}
for (key, value) in valid_data.items():
if getattr(instance, key) != value:
print ('Data has changed')
setattr(instance, key, value)
instance.save()
If you run your playbook with ansible-playbook -vvv
you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).
I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this
# fails
- name: Add all instance public IPs to host group
add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
loop: "{{ ec2.instances }}"
but that fails too.
So this is not an answer. Just some debugging help and things not to try.
A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.
pcollision = n / capacity
So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.
O(n) = O(k * n)
We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.
pcollision x 2 = (n / capacity)2
This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to
pcollision x k = (n / capacity)k
And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.
We talk about this by saying that the hash-map has O(1) access with high probability
I think what he is trying to say is to use the
getContentPane().setBackground(Color.the_Color_you_want_here)
but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)
Eg:
jPanel.setbackground(Color.BLUE)
Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.
The major differences are:
A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.
A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.
Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.
You can use @Rohan answer https://stackoverflow.com/a/23609343/3297761
But if you want to make each controller reaload after a view change you can use
myApp.config(function($ionicConfigProvider) { $ionicConfigProvider.views.maxCache(0); ... }
It's not in standard C, so the behavior is undefined.
Some implementation uses it to clear stdin
buffer.
From C11 7.21.5.2 The fflush function, fflush
works only with output/update stream, not input stream.
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
The original solution (setting the ForkJoinPool common parallelism property) no longer works. Looking at the links in the original answer, an update which breaks this has been back ported to Java 8. As mentioned in the linked threads, this solution was not guaranteed to work forever. Based on that, the solution is the forkjoinpool.submit with .get solution discussed in the accepted answer. I think the backport fixes the unreliability of this solution also.
ForkJoinPool fjpool = new ForkJoinPool(10);
System.out.println("stream.parallel");
IntStream range = IntStream.range(0, 20);
fjpool.submit(() -> range.parallel()
.forEach((int theInt) ->
{
try { Thread.sleep(100); } catch (Exception ignore) {}
System.out.println(Thread.currentThread().getName() + " -- " + theInt);
})).get();
System.out.println("list.parallelStream");
int [] array = IntStream.range(0, 20).toArray();
List<Integer> list = new ArrayList<>();
for (int theInt: array)
{
list.add(theInt);
}
fjpool.submit(() -> list.parallelStream()
.forEach((theInt) ->
{
try { Thread.sleep(100); } catch (Exception ignore) {}
System.out.println(Thread.currentThread().getName() + " -- " + theInt);
})).get();
You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.
In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:
#include <termios.h>
struct termios info;
tcgetattr(0, &info); /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON; /* disable canonical mode */
info.c_cc[VMIN] = 1; /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0; /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */
Now when you read from stdin (with getchar()
, or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.
Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.
int* array = new int[size];
Use padding in percentages too and remove from the width:
padding: 5%; width: 90%;
Try memory profiler. memory profiler
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 13.61 MB 7.64 MB a = [1] * (10 ** 6)
6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)
7 13.61 MB -152.59 MB del b
8 13.61 MB 0.00 MB return a
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
// Merge object2 into object1
$.extend( object1, object2 );
Put a global variable to generate the ids.
<script>
$(function(){
// Variable to get ids for the checkboxes
var idCounter=1;
$("#btn1").click(function(){
var val = $("#txtAdd").val();
$("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
idCounter ++;
});
});
</script>
<div id='divContainer'></div>
<input type="text" id="txtAdd" />
<button id="btn1">Click</button>
Create a function with return format yyyy-mm-hh hh:mi:ss.sss
create function fn_retornaFecha (@i_fecha datetime)
returns varchar(23)
as
begin
declare
@w_fecha varchar(23),
@w_anio varchar(4),
@w_mes varchar(2),
@w_dia varchar(2),
@w_hh varchar(2),
@w_nn varchar(2),
@w_ss varchar(2),
@w_sss varchar(3)
select @w_fecha = null
if ltrim(rtrim(@i_fecha)) is not null
begin
select
@w_anio = replicate('0',4-char_length( convert(varchar(4), year(@i_fecha)) )) + convert(varchar(4), year(@i_fecha)),
@w_mes = replicate('0',2-char_length( convert(varchar(2),month(@i_fecha)) )) + convert(varchar(2),month(@i_fecha)),
@w_dia = replicate('0',2-char_length( convert(varchar(2), day(@i_fecha)) )) + convert(varchar(2), day(@i_fecha)) ,
@w_hh = replicate('0',2-char_length( convert(varchar(2),datepart( hh, @i_fecha ) ) )) + convert(varchar(2),datepart( hh, @i_fecha ) ),
@w_nn = replicate('0',2-char_length( convert(varchar(2),datepart( mi, @i_fecha ) ) )) + convert(varchar(2),datepart( mi, @i_fecha ) ),
@w_ss = replicate('0',2-char_length( convert(varchar(2),datepart( ss, @i_fecha ) ) )) + convert(varchar(2),datepart( ss, @i_fecha ) ),
@w_sss = convert(varchar(3),datepart( ms, @i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, @i_fecha ) ) ))
select @w_fecha = @w_anio + '-' + @w_mes + '-' + @w_dia + ' ' + @w_hh + ':' + @w_nn + ':' + @w_ss + '.' + @w_sss
end
return @w_fecha
end
go
Example
select fn_retornaFecha(getdate())
and the result is: 2016-12-21 10:12:50.123
May be You are using pgadmin by connecting remote host then U are trying to update there from your system but it searches for that file in remote system's file system... its the error wat I faced May be its also for u check it
You can sed's -i
option to edit in-place without using temporary file:
sed -i '/^$/d' file
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
A fairly simple option would be to create a javascript function called on the form's "onsubmit" event to enable the radiobutton back so that it's value is posted with the rest of the form.
It does not seem to be an omission on HTML specs, but a design choice (a logical one, IMHO), a radiobutton can't be readonly as a button can't be, if you don't want to use it, then disable it.
I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance
but just the Class
object to use isAssignableFrom
.
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
Upgrade Automapper to version 6.2.2. It helped me
For attached properties you can either call SetValue on the object for which you want to assign the value:
tblock.SetValue(Grid.RowProperty, 4);
Or call the static Set method (not as an instance method like you tried) for the property on the owner type, in this case SetRow:
Grid.SetRow(tblock, 4);
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
Since the loop below only modifies elements already seen, it would be considered acceptable:
a = ['a',' b', 'c ', ' d ']
for i, s in enumerate(a):
a[i] = s.strip()
print(a) # -> ['a', 'b', 'c', 'd']
Which is different from:
a[:] = [s.strip() for s in a]
in that it doesn't require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.
Caution: Although you can modify entries this way, you can't change the number of items in the list
without risking the chance of encountering problems.
Here's an example of what I mean—deleting an entry messes-up the indexing from that point on:
b = ['a', ' b', 'c ', ' d ']
for i, s in enumerate(b):
if s.strip() != b[i]: # leading or trailing whitespace?
del b[i]
print(b) # -> ['a', 'c '] # WRONG!
(The result is wrong because it didn't delete all the items it should have.)
Update
Since this is a fairly popular answer, here's how to effectively delete entries "in-place" (even though that's not exactly the question):
b = ['a',' b', 'c ', ' d ']
b[:] = [entry for entry in b if entry.strip() == entry]
print(b) # -> ['a'] # CORRECT
Perhaps an example will help:
git rm --cached asd
git commit -m "the file asd is gone from the repository"
versus
git reset HEAD -- asd
git commit -m "the file asd remains in the repository"
Note that if you haven't changed anything else, the second commit won't actually do anything.
As greg said you can embed HTML content in Markdown, but one of the points of Markdown is to avoid having to have extensive (or any, for that matter) CSS/HTML markup knowledge, right? This is what I do:
In my Markdown file I simply instruct all my wiki editors to embed wrap all images with something that looks like this:
'<div> // Put image here </div>`
(of course.. they don't know what <div>
means, but that shouldn't matter)
So the Markdown file looks like this:
<div>
![optional image description][1]
</div>
[1]: /image/path
And in the CSS content that wraps the whole page I can do whatever I want with the image tag:
img {
float: right;
}
Of course you can do more with the CSS content... (in this particular case, wrapping the img
tag with div prevents other text from wrapping against the image... this is just an example, though), but IMHO the point of Markdown is that you don't want potentially non-technical people getting into the ins and outs of CSS/HTML.. it's up to you as a web developer to make your CSS content that wraps the page as generic and clean as possible, but then again your editors need not know about that.
-- I like this as the data type and the format remains consistent with a date time data type
;with cte as(
select
cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
from dbo.mytable cd
where utcdate between '2014-01-14' and '2014-01-15'
group by
cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte
If you want to pause then use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
To sleep for one second or for 10 minutes
TimeUnit.MINUTES.sleep(10);
Or Thread Sleep
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
see also the official documentation
TimeUnit.SECONDS.sleep()
will call Thread.sleep
. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations.
but if you want to solve your issue
int timeToWait = 10; //second
System.out.print("Scanning")
try {
for (int i=0; i<timeToWait ; i++) {
Thread.sleep(1000);
System.out.print(".")
}
} catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
}
Or just use old-school DOM methods when JQ has a monkey in the middle somewhere.
var myElement = $('#my_element')[0];
var myElClass = myElement.getAttribute('class').split(/\s+/g);
//splits class into an array based on 1+ white space characters
myElClass.push('new_class');
myElement.setAttribute('class', myElClass.join(' '));
//$(myElement) to return to JQ wrapper-land
Learn the DOM people. Even in 2016's framework-palooza it helps quite regularly. Also, if you ever hear someone compare the DOM to assembly, kick them for me.
When you decorate a model property with [DataType(DataType.Date)]
the default template in ASP.NET MVC 4 generates an input field of type="date"
:
<input class="text-box single-line"
data-val="true"
data-val-date="The field EstPurchaseDate must be a date."
id="EstPurchaseDate"
name="EstPurchaseDate"
type="date" value="9/28/2012" />
Browsers that support HTML5 such Google Chrome render this input field with a date picker.
In order to correctly display the date, the value must be formatted as 2012-09-28
. Quote from the specification:
value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.
You could enforce this format using the DisplayFormat
attribute:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
Find out the web server user
open up terminal and type
lsof -i tcp:80
This will show you the user of the web server process Here is an example from a raspberry pi running debian:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 7478 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7664 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7794 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
The user is www-data
If you give ownership of the web files to the web server:
chown www-data:www-data -R /opt/lamp/htdocs
And chmod 755 for good measure:
chmod 755 -R /opt/lamp/htdocs
Let me know how you go, maybe you need to use 'sudo' before the command, i.e.
sudo chown www-data:www-data -R /opt/lamp/htdocs
if it doesn't work, please give us the output of:
ls -al /opt/lamp/htdocs
Use this plugin: https://github.com/admsev/jquery-play-sound
$.playSound('http://example.org/sound.mp3');
As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.
1) Use this chrome extension, Requestly to redirect your url from the https
version of your url to the http
version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don't have to change your app at all, and you can simply "rewrite" your url using this extension.
2) Change the code of your app to optionally make your endpoint redirect to the http
version of your url instead of the https
version (or vice versa). If you do this, the request will fail with status code 0.
In angularJS, you can use angular.element which is the lite version of jQuery. You can do pretty much everything with it, so you don't need to include jQuery.
So basically, you can rewrite your code to something like this:
link: function (scope, iElement, iAttrs) {
var svgTag = angular.element('<svg width="600" height="100" class="svg"></svg>');
angular.element(svgTag).appendTo(iElement[0]);
//...
}
Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.
As was answered here - Deserialize JSON into C# dynamic object?
It's pretty simple using Json.NET:
dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
Or using Newtonsoft.Json.Linq :
dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
why can't I use a property like self.myView
instead of a local variable like myView?
try using:
NSDictionaryOfVariableBindings(_view)
instead of self.view
The res.header('Access-Control-Allow-Origin', '*');
wouldn't work with Autorization header.
Just enable pre-flight request, using cors library:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.options('*', cors())
The easiest way (requires Glide 4.x.x)
Glide.with(context).load(uri).apply(RequestOptions().circleCrop()).into(imageView)
The first thing you need to know is that HashSet
acts like a Set
, which means you add your object directly to the HashSet
and it cannot contain duplicates. You just add your value directly in HashSet
.
However, HashMap
is a Map
type. That means every time you add an entry, you add a key-value pair.
In HashMap
you can have duplicate values, but not duplicate keys. In HashMap
the new entry will replace the old one. The most recent entry will be in the HashMap
.
Understanding Link between HashMap and HashSet:
Remember, HashMap
can not have duplicate keys. Behind the scene HashSet
uses a HashMap
.
When you attempt to add any object into a HashSet
, this entry is actually stored as a key in the HashMap
- the same HashMap
that is used behind the scene of HashSet
. Since this underlying HashMap
needs a key-value pair, a dummy value is generated for us.
Now when you try to insert another duplicate object into the same HashSet
, it will again attempt to be insert it as a key in the HashMap
lying underneath. However, HashMap
does not support duplicates. Hence, HashSet
will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.
Summary:
HashMap
allows duplicate values
, but not keys
.
HashSet
cannot contains duplicates.
To play with whether the addition of an object is successfully completed or not, you can check the boolean
value returned when you call .add()
and see if it returns true
or false
. If it returned true
, it was inserted.
You need to use ECHO
. Also, put the quotes around the entire file path if it contains spaces.
One other note, use >
to overwrite a file if it exists or create if it does not exist. Use >>
to append to an existing file or create if it does not exist.
Overwrite the file with a blank line:
ECHO.>"C:\My folder\Myfile.log"
Append a blank line to a file:
ECHO.>>"C:\My folder\Myfile.log"
Append text to a file:
ECHO Some text>>"C:\My folder\Myfile.log"
Append a variable to a file:
ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"
Media types do not allow you to detect touch capabilities as part of the standard:
http://www.w3.org/TR/css3-mediaqueries/
So, there is no way to do it consistently via CSS or media queries, you will have to resort to JavaScript.
No need to use Modernizr, you can just use plain JavaScript:
<script type="text/javascript">
var is_touch_device = 'ontouchstart' in document.documentElement;
if(is_touch_device) alert("touch is enabled!");
</script>
As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:
df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))
The .transform()
processes each column as a series. Contrary to .apply()
which passes the columns aggregated in a DataFrame.
Consequently you can apply the Series method map()
.
Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)
accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map()
method
Try using the property ForeColor. Like this :
TextBox1.ForeColor = Color.Red;
The problem happened because I was trying to bind a HTML element before it was created.
My script was loaded on top of the HTML and it needs to be loaded at the bottom of my HTML code.
From msdn:
The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.
The Sort() method is the standard Array.Sort(), which takes in IComparables (among other overloads), so if you sort by creation date, it will handle localization based on the machine settings.
Description of the possible values:
left
: No floating elements allowed on the left sideright
: No floating elements allowed on the right sideboth
: No floating elements allowed on either the left or the right sidenone
: Default. Allows floating elements on both sidesinherit
: Specifies that the value of the clear property should be inherited from the parent element
Source: w3schools.com
Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).
http://connect.microsoft.com/PowerShell/feedback/details/376207/
They suggest using --%
as a way to force PowerShell to stop trying to interpret the text to the right.
For example:
MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
datetime.time
can not do it - But you could use datetime.datetime.now()
start = datetime.datetime.now()
sleep(10)
end = datetime.datetime.now()
duration = end - start
To list all local groups which have users assigned to them, use this command:
cut -d: -f1 /etc/group | sort
For more info- > Unix groups, Cut command, sort command
The current answers are a bit confusing and misleading, and they are missing some important DNS implications. I'll try to summarize where things stand clearly.
IDisposable
objects should ideally be disposed when you are done with them, especially those that own Named/shared OS resources. HttpClient
is no exception, since as Darrel Miller points out it allocates cancellation tokens, and request/response bodies can be unmanaged streams.Connection:close
header after DNS changes take place. Another possibility involves recycling the HttpClient
on the client side, either periodically or via some mechanism that learns about the DNS change. See https://github.com/dotnet/corefx/issues/11224 for more information (I suggest reading it carefully before blindly using the code suggested in the linked blog post).SQL Server's SQLBulkCopy is blindingly fast. Unfortunately, I found that OracleBulkCopy is far slower. Also it has problems:
Actually System.Data.OracleClient.OracleDataAdapter is faster than OracleBulkCopy if you want to fill a table with small records but many rows. You need to tune the batch size though, the optimum BatchSize for OracleDataAdapter is smaller than for OracleBulkCopy.
I ran my test on a Windows 7 machine with an x86 executable and the 32 bits ODP.Net client 2.112.1.0. . The OracleDataAdapter is part of System.Data.OracleClient 2.0.0.0. My test set is about 600,000 rows with a record size of max. 102 bytes (average size 43 chars). Data source is a 25 MB text file, read in line by line as a stream.
In my test I built up the input data table to a fixed table size and then used either OracleBulkCopy or OracleDataAdapter to copy the data block to the server. I left BatchSize as 0 in OracleBulkCopy (so that the current table contents is copied as one batch) and set it to the table size in OracleDataAdapter (again that should create a single batch internally). Best results:
For comparison:
Same client machine, test server is SQL Server 2008 R2. For SQL Server, bulk copy is clearly the best way to go. Not only is it overall fastest, but server load is also lower than when using data adapter. It is a pity that OracleBulkCopy does not offer quite the same experience - the BulkCopy API is much easier to use than DataAdapter.
At the end of the day it doesn't matter because C++ compilers can deal with the files in either format. If it's a real issue within your team, flip a coin and move on to the actual work.
You can delete a particular single line with its line number by
sed -i '33d' file
This will delete the line on 33 line number and save the updated file.
I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:
func dateFormat(layout string, d float64) string{
intTime := int64(d)
t := time.Unix(intTime, 0)
if layout == "" {
layout = "2006-01-02 15:04:05"
}
return t.Format(layout)
}
If you want to do rsync and use custom user and custom ssh key, you need to write this key in rsync options.
---
- name: rsync
hosts: serverA,serverB,serverC,serverD,serverE,serverF
gather_facts: no
vars:
ansible_user: oracle
ansible_ssh_private_key_file: ./mykey
src_file: "/path/to/file.txt"
tasks:
- name: Copy Remote-To-Remote from serverA to server{B..F}
synchronize:
src: "{{ src_file }}"
dest: "{{ src_file }}"
rsync_opts:
- "-e ssh -i /remote/path/to/mykey"
delegate_to: serverA
There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.
Here is a useful link:
Yes, open a postscript()
device with a filename ending in .eps
, do your plot(s) and call dev.off()
.
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
A robust solution is to delegate counting to a subroutine invoked with call
; the subroutine uses goto
statements to emulate a loop in which shift
is used to consume the (subroutine-only) arguments iteratively:
@echo off
setlocal
:: Call the argument-counting subroutine with all arguments received,
:: without interfering with the ability to reference the arguments
:: with %1, ... later.
call :count_args %*
:: Print the result.
echo %ReturnValue% argument(s) received.
:: Exit the batch file.
exit /b
:: Subroutine that counts the arguments given.
:: Returns the count in %ReturnValue%
:count_args
set /a ReturnValue = 0
:count_args_for
if %1.==. goto :eof
set /a ReturnValue += 1
shift
goto count_args_for
A pure RESTful API should use the underlying protocol standard features:
For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.
RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.
Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.
I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.
You cannot move a running docker container from one host to another.
You can commit the changes in your container to an image with docker commit
, move the image onto a new host, and then start a new container with docker run
. This will preserve any data that your application has created inside the container.
Nb: It does not preserve data that is stored inside volumes; you need to move data volumes manually to new host.
use zzz instead of TZD
Example:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
Response:
2011-08-09T11:50:00:02+02:00