The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."
For ex .. add class:
btn-lg - LARGE
btn-sm - SMALL
btn-xs - Very small
<button type=button class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button>
<button type=button class="btn btn-default">
<span class="glyphicon glyphicon-star" aria-hidden=true></span>Star
</button>
<button type=button class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button>
<button type=button class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button>
Ref link Bootstrap : Glyphicons Bootstrap
$(document.body)
is using the global reference document
to get a reference to the body
, whereas $('body')
is a selector in which jQuery will get the reference to the <body>
element on the document
.
No major difference that I can see, not any noticeable performance gain from one to the other.
You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.
Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
You could use the following utility method-
public static double round(double valueToRound, int numberOfDecimalPlaces)
{
double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);
double interestedInZeroDPs = valueToRound * multipicationFactor;
return Math.round(interestedInZeroDPs) / multipicationFactor;
}
Following Steps are much enough to back button:
Step 1: This code should be in Manifest.xml
<activity android:name=".activity.ChildActivity"
android:parentActivityName=".activity.ParentActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activity.ParentActivity" /></activity>
Step 2: You won't give
finish();
in your Parent Activity while starting Child Activity.
Step 3: If you need to come back to Parent Activity from Child Activity, Then you just give this code for Child Activity.
startActivity(new Intent(ParentActivity.this, ChildActivity.class));
My question is: Why is not calling
return
faster
It’s faster because return
is a (primitive) function in R, which means that using it in code incurs the cost of a function call. Compare this to most other programming languages, where return
is a keyword, but not a function call: it doesn’t translate to any runtime code execution.
That said, calling a primitive function in this way is pretty fast in R, and calling return
incurs a minuscule overhead. This isn’t the argument for omitting return
.
or better, and thus preferable?
Because there’s no reason to use it.
Because it’s redundant, and it doesn’t add useful redundancy.
To be clear: redundancy can sometimes be useful. But most redundancy isn’t of this kind. Instead, it’s of the kind that adds visual clutter without adding information: it’s the programming equivalent of a filler word or chartjunk).
Consider the following example of an explanatory comment, which is universally recognised as bad redundancy because the comment merely paraphrases what the code already expresses:
# Add one to the result
result = x + 1
Using return
in R falls in the same category, because R is a functional programming language, and in R every function call has a value. This is a fundamental property of R. And once you see R code from the perspective that every expression (including every function call) has a value, the question then becomes: “why should I use return
?” There needs to be a positive reason, since the default is not to use it.
One such positive reason is to signal early exit from a function, say in a guard clause:
f = function (a, b) {
if (! precondition(a)) return() # same as `return(NULL)`!
calculation(b)
}
This is a valid, non-redundant use of return
. However, such guard clauses are rare in R compared to other languages, and since every expression has a value, a regular if
does not require return
:
sign = function (num) {
if (num > 0) {
1
} else if (num < 0) {
-1
} else {
0
}
}
We can even rewrite f
like this:
f = function (a, b) {
if (precondition(a)) calculation(b)
}
… where if (cond) expr
is the same as if (cond) expr else NULL
.
Finally, I’d like to forestall three common objections:
Some people argue that using return
adds clarity, because it signals “this function returns a value”. But as explained above, every function returns something in R. Thinking of return
as a marker of returning a value isn’t just redundant, it’s actively misleading.
Relatedly, the Zen of Python has a marvellous guideline that should always be followed:
Explicit is better than implicit.
How does dropping redundant return
not violate this? Because the return value of a function in a functional language is always explicit: it’s its last expression. This is again the same argument about explicitness vs redundancy.
In fact, if you want explicitness, use it to highlight the exception to the rule: mark functions that don’t return a meaningful value, which are only called for their side-effects (such as cat
). Except R has a better marker than return
for this case: invisible
. For instance, I would write
save_results = function (results, file) {
# … code that writes the results to a file …
invisible()
}
But what about long functions? Won’t it be easy to lose track of what is being returned?
Two answers: first, not really. The rule is clear: the last expression of a function is its value. There’s nothing to keep track of.
But more importantly, the problem in long functions isn’t the lack of explicit return
markers. It’s the length of the function. Long functions almost (?) always violate the single responsibility principle and even when they don’t they will benefit from being broken apart for readability.
Page 2 is in a new tab/window ? If it's this, use the code bellow :
try {
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
String act = driver.getCurrentUrl();
}
}catch(Exception e){
System.out.println("fail");
}
The two functions you need are documented here:
In short:
// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");
// Resize src so that is has the same size as img
cv::resize(src, src, img.size());
And please, please, stop using the old and completely deprecated IplImage* classes
use contentDocument
to achieve this
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
var ulObj = innerDoc.getElementById("ID_TO_SEARCH");
To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()
internal sealed class CtorExplorer
{
protected int a = 0;
protected static int b = 0;
}
Word Break will mimic some of the intent
input[type=text] {
word-wrap: break-word;
word-break: break-all;
height: 80px;
}
_x000D_
<input type="text" value="The quick brown fox jumped over the lazy dog" />
_x000D_
As a workaround, this solution lost its effectiveness on some browsers. Please check the demo: http://cssdesk.com/dbCSQ
Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.
Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\
Here is a the list of ajax libraries comparison based on the features and support. I prefer to use fetch for only client side development or isomorphic-fetch for using in both client side and server side development.
For more information on isomorphic-fetch vs fetch
Just replace:
return d.age - d1.age;
By:
return ((Integer)d.age).compareTo(d1.age);
Or invert to reverse the list:
return ((Integer)d1.age).compareTo(d.age);
EDIT:
Fixed the "memory problem".
Indeed, the better solution is change the age
field in the Dog
class to Integer
, because there many benefits, like the null
possibility...
Change table's default charset:
ALTER TABLE etape_prospection
CHARACTER SET utf8,
COLLATE utf8_general_ci;
To change string column charset exceute this query:
ALTER TABLE etape_prospection
CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;
Using the below line
SELECT LEFT(subject , 10) FROM tbl
Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.
Those solutions mentioned change how your program work.
You can off course put #if DEBUG
and #endif
around the Console calls, but if you really want to prevent the window from closing only on your dev machine under Visual Studio or if VS isn't running only if you explicitly configure it, and you don't want the annoying 'Press any key to exit...'
when running from the command line, the way to go is to use the System.Diagnostics.Debugger
API's.
If you only want that to work in DEBUG
, simply wrap this code in a [Conditional("DEBUG")] void BreakConditional()
method.
// Test some configuration option or another
bool launch;
var env = Environment.GetEnvironmentVariable("LAUNCH_DEBUGGER_IF_NOT_ATTACHED");
if (!bool.TryParse(env, out launch))
launch = false;
// Break either if a debugger is already attached, or if configured to launch
if (launch || Debugger.IsAttached) {
if (Debugger.IsAttached || Debugger.Launch())
Debugger.Break();
}
This also works to debug programs that need elevated privileges, or that need to be able to elevate themselves.
DateTime.now.new_offset(0)
will work in standard Ruby (i.e. without ActiveSupport).
I developed my own function that convert human readable memory size to different sizes.
function convertMemorySize($strval, string $to_unit = 'b')
{
$strval = strtolower(str_replace(' ', '', $strval));
$val = floatval($strval);
$to_unit = strtolower(trim($to_unit))[0];
$from_unit = str_replace($val, '', $strval);
$from_unit = empty($from_unit) ? 'b' : trim($from_unit)[0];
$units = 'kmgtph'; // (k)ilobyte, (m)egabyte, (g)igabyte and so on...
// Convert to bytes
if ($from_unit !== 'b')
$val *= 1024 ** (strpos($units, $from_unit) + 1);
// Convert to unit
if ($to_unit !== 'b')
$val /= 1024 ** (strpos($units, $to_unit) + 1);
return $val;
}
convertMemorySize('1024Kb', 'Mb'); // 1
convertMemorySize('1024', 'k') // 1
convertMemorySize('5.2Mb', 'b') // 5452595.2
convertMemorySize('10 kilobytes', 'bytes') // 10240
convertMemorySize(2048, 'k') // By default convert from bytes, result is 2
This function accepts any memory size abbreviation like "Megabyte, MB, Mb, mb, m, kilobyte, K, KB, b, Terabyte, T...." so it is typo safe.
On java 8+
Map.getOrDefault(Object key,V defaultValue)
Getting this error, I changed the
c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD
for both code project and associated Google Test project. This solved the issue.
Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
Compiler shows following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Storyboard (<UIStoryboard: 0x7fedf2d5c9a0>) doesn't contain a
ViewController with identifier 'SBAddEmployeeVC''
Here the object of the storyboard created is not the main storyboard which contains our ViewControllers. As storyboard file on which we work is named as Main.storyboard. So we need to have reference of object of the Main.storyboard.
Use following code for that :
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
Here storyboardWithName
is the name of the storyboard file we are working with and bundle
specifies the bundle in which our storyboard is (i.e. mainBundle
).
Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)]
above your mandatory parameters), but it's also the only option that you won't hate yourself for later.
More below:
[Console]::ReadLine
is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.
Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
You're trying to ask for parameters.
You should use the [Parameter(Mandatory=$true)]
attribute, and correct typing, to ask for the parameters.
If you use this on a [SecureString]
, it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]
), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]
) then it will become help text for the prompt.
I use a classical javascript to set value to hidden input
$scope.SetPersonValue = function (PersonValue)
{
document.getElementById('TypeOfPerson').value = PersonValue;
if (PersonValue != 'person')
{
document.getElementById('Discount').checked = false;
$scope.isCollapsed = true;
}
else
{
$scope.isCollapsed = false;
}
}
I can't see a new-line after that last brace.
As you know: "If a source file that is not empty does not end in a new-line character, ... the behavior is undefined".
From my recent experience i would recommend ksoap library to consume a Soap WCF Service, its actually really easy, this anddev thread migh help you out too.
When you use Theme.AppCompat in your application you can use FullScreenTheme by adding the code below to styles.
<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
and also mention in your manifest file.
<activity
android:name=".activities.FullViewActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"
/>
The problem is insufficient memory to load context.
Try to set VM options:
-da -Xmx2048m -Xms1024m -XX:MaxPermSize=2048m
The Process described by Igor and CharlesB Works to me, since IDE's like NetBeans and Eclipse permit specify the location of the JDK, even software like Apache Tomcat (the ZIP Distribution) use BASH - FILES to set it up (then specify the JDK location using relatives URI).
I Have a USB-HardDisk With NetBeans, Eclipse, Apache Tomcat working with a JDK in "portable mode".
I Had a way to extract a copy of the JDK from the installers files: Install it, Copy it in other place and then uninstall it. A dirty way to extract it, but was successfull.
The place to put EXTRA - LIBS was: %PLACE_WHERE_JDK_ARE%\jre\lib\ext
Yo could also set labels = FALSE
inside axis(...)
and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here
I also ran into this situation and figured out how to do it using FrameLayout. The following output is produced by the code given below.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/contactbook_icon"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="140"
android:textSize="12dp"
android:textColor="#FFFFFF"
android:layout_gravity="bottom|right"
android:layout_margin="15dp" />
</FrameLayout>
Change the margin value to adjust the text position over the image. Removing margin might make the text to go out of the view sometimes.
Go to the first line from which you would like to delete, and press the keys dG
The main difference between localStorage
and sessionStorage
is that sessionStorage
is unique per tab. If you close the tab the sessionStorage
gets deleted, localStorage
does not. Also you cannot communicate between tabs :)
Another subtle difference is that for example on Safari (8.0.3) localStorage
has a limit of 2551 k characters but sessionStorage
has unlimited storage
On Chrome (v43) both localStorage
and sessionStorage
are limited to 5101 k characters (no difference between normal / incognito mode)
On Firefox both localStorage
and sessionStorage
are limited to 5120 k characters (no difference between normal / private mode )
No difference in speed whatsoever :)
There's also a problem with Mobile Safari and Mobile Chrome, Private Mode Safari & Chrome have a maximum space of 0KB
git tag --sort=committerdate | tail -1
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
It's not a HTTP response code, but it is documented by WhatWG as a valid value for the status attribute of an XMLHttpRequest
or a Fetch response.
Broadly speaking, it is a default value used when there is no real HTTP status code to report and/or an error occurred sending the request or receiving the response. Possible scenarios where this is the case include, but are not limited to:
First, to reiterate: 0 is not a HTTP status code. There's a complete list of them in RFC 7231 Section 6.1, that doesn't include 0, and the intro to section 6 states clearly that
The status-code element is a three-digit integer code
which 0 is not.
However, 0 as a value of the .status
attribute of an XMLHttpRequest object is documented, although it's a little tricky to track down all the relevant details. We begin at https://xhr.spec.whatwg.org/#the-status-attribute, documenting the .status
attribute, which simply states:
That may sound vacuous and tautological, but in reality there is information here! Remember that this documentation is talking here about the .response
attribute of an XMLHttpRequest
, not a response, so this tells us that the definition of the status on an XHR object is deferred to the definition of a response's status in the Fetch spec.
But what response object? What if we haven't actually received a response yet? The inline link on the word "response" takes us to https://xhr.spec.whatwg.org/#response, which explains:
An
XMLHttpRequest
has an associated response. Unless stated otherwise it is a network error.
So the response whose status we're getting is by default a network error. And by searching for everywhere the phrase "set response to" is used in the XHR spec, we can see that it's set in five places:
To a network error, when:
open()
method is called, orsend()
method)abort()
method is called, causing the request error steps to runTo the response produced by sending the request using Fetch, by way of either the Fetch process response task (if the XHR request is asychronous) or the Fetch process response end-of-body task (if the XHR request is synchronous).
Looking in the Fetch standard, we can see that:
A network error is a response whose status is always
0
so we can immediately tell that we'll see a status of 0 on an XHR object in any of the cases where the XHR spec says the response should be set to a network error. (Interestingly, this includes the case where the body's stream gets "errored", which the Fetch spec tells us can happen during parsing the body after having received the status - so in theory I suppose it is possible for an XHR object to have its status set to 200, then encounter an out-of-memory error or something while receiving the body and so change its status back to 0.)
We also note in the Fetch standard that a couple of other response types exist whose status is defined to be 0, whose existence relates to cross-origin requests and the same-origin policy:
An opaque filtered response is a filtered response whose ... status is
0
...An opaque-redirect filtered response is a filtered response whose ... status is
0
...
(various other details about these two response types omitted).
But beyond these, there are also many cases where the Fetch algorithm (rather than the XHR spec, which we've already looked at) calls for the browser to return a network error! Indeed, the phrase "return a network error" appears 40 times in the Fetch standard. I will not try to list all 40 here, but I note that they include:
In other words: whenever something goes wrong other than getting a real HTTP error status code like a 500 or 400 from the server, you end up with a status attribute of 0 on your XHR object or Fetch response object in the browser. The number of possible specific causes enumerated in spec is vast.
Finally: if you're interested in the history of the spec for some reason, note that this answer was completely rewritten in 2020, and that you may be interested in the previous revision of this answer, which parsed essentially the same conclusions out of the older (and much simpler) W3 spec for XHR, before these were replaced by the more modern and more complicated WhatWG specs this answers refers to.
I had the same problem. So here is the real answer: Mount the system under /proc
.
Here is my command:
mount -o rw,remount /proc /system
It works, and in fact is the only way I can overcome the Read-only System problem.
For me, the error message said I had too many simulator files open to build Swift. When I quit the simulator and built again, everything worked.
Just use indexing
df.iloc[:-1,:]
That's why iloc exists. You can also use head or tail.
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
for mysql 'text':
@Column(columnDefinition = "TEXT")
private String description;
for mysql 'longtext':
@Lob
private String description;
I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout
to 1min as suggested by this link
Basically, with prepared statements the data coming in from a potential hacker is treated as data - and there's no way it can be intermixed with your application SQL and/or be interpreted as SQL (which can happen when data passed in is placed directly into your application SQL).
This is because prepared statements "prepare" the SQL query first to find an efficient query plan, and send the actual values that presumably come in from a form later - at that time the query is actually executed.
More great info here:
My solution, it´s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating @foreach but now work with a double @foreach and double @if:
<div class="form-group">
<label for="tagLabel">Tags: </label>
<select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
@foreach($tags as $id => $name)
@if (is_array(Request::old('tag_id')))
<option value="{{ $id }}"
@foreach (Request::old('tag_id') as $idold)
@if($idold==$id)
selected
@endif
@endforeach
style="padding:5px;">{{ $name }}</option>
@else
<option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
@endif
@endforeach
</select>
</div>
this is the code por jquery chosen (the blade.php code doesn´t need this code to work)
$(".chosen-tag").chosen({
placeholder_text_multiple: "Selecciona alguna etiqueta",
no_results_text: "No hay resultados para la busqueda",
search_contains: true,
width: '500px'
});
Here is a way to do it using String
's built-in regex capabilities:
String lastWord = sentence.replaceAll("^.*?(\\w+)\\W*$", "$1");
The idea is to match the whole string from ^
to $
, capture the last sequence of \w+
in a capturing group 1, and replace the whole sentence with it using $1
.
you can just do
select rownum, l.* from student l where name like %ram%
this assigns the row number as the rows are fetched (so no guaranteed ordering of course).
if you wanted to order first do:
select rownum, l.*
from (select * from student l where name like %ram% order by...) l;
An example of how we use it would be on a priority queue of debit/credit card transactions. We have millions of these and the effort of the work depends on the input string type. If the transaction is of type CHECK we have very little processing but if it is a point of sale then there is lots to do such as merge with meta data (category, label, tags, etc) and provide services (email/sms alerts, fraud detection, low funds balance, etc). Based on the input type we compose classes of various traits (called mixins) necessary to handle the job and then perform the work. All of these jobs come into the same queue in realtime mode from different financial institutions. Once the data is cleansed it is sent to different data stores for persistence, analytics, or pushed to a socket connection, or to Lift comet actor. Working actors are constantly self load balancing the work so that we can process the data as fast as possible. We can also snap in additional services, persistence models, and stm for critical decision points.
The Erlang OTP style message passing on the JVM makes a great system for developing realtime systems on the shoulders of existing libraries and application servers.
Akka allows you to do message passing like you would in a traditional esb but with speed! It also gives you tools in the framework to manage the vast amount of actor pools, remote nodes, and fault tolerance that you need for your solution.
@echo off
title Test
echo Select a language. (de/en)
set /p language=
IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN
echo Not found.
goto commonexit
:languageDE
echo German
goto commonexit
:languageEN
echo English
goto commonexit
:commonexit
pause
The point is that batch simply continues through instructions, line by line until it reaches a goto
, exit
or end-of-file. It has no concept of sections
to control flow.
Hence, entering de
would jump to :languagede
then simply continue executing instructions until the file ends, showing de
then en
then not found
.
import os
[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text
The outer most val for sublist in ...
loop flattens the list to be one dimensional. The j
loop collects a list of every file basename and joins it to the current path. Finally, the i
loop iterates over all directories and sub directories.
This example uses the hard-coded path ./
in the os.walk(...)
call, you can supplement any path string you like.
Note: os.path.expanduser
and/or os.path.expandvars
can be used for paths strings like ~/
Its easy to add in file basename tests and directoryname tests.
For Example, testing for *.jpg
files:
... for j in i[2] if j.endswith('.jpg')] ...
Additionally, excluding the .git
directory:
... for i in os.walk('./') if '.git' not in i[0].split('/')]
Below cmd will work if we dont have @ in password:
git pull https://username:pass@[email protected]/my/repository
If you have @ in password then replace it by %40 as shown below:
git pull https://username:pass%[email protected]/my/repository
Sounds like you should have two copies on your server. A bare copy, that you can push/pull from, which your would push your changes when you're done, and then you would clone this into you web directory and set up a cronjob to update git pull from your web directory every day or so.
It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:
public List<Node> getAll() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
return query.list();
}
Where your class has 2 sets like:
public class Node implements Serializable {
@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;
@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;
}
This is pretty hacky, but it works for me. I was trying to achieve consistent spacing/margins.
.grid {
width: 1024px;
display: flex;
flex-flow: row wrap;
padding: 32px;
background-color: #ddd;
&:after {
content: "";
flex: auto;
margin-left:-1%;
}
.item {
flex: 1 0 24.25%;
max-width: 24.25%;
margin-bottom: 10px;
text-align: center;
background-color: #bbb;
&:nth-child(4n+2),
&:nth-child(4n+3),
&:nth-child(4n+4) {
margin-left: 1%;
}
&:nth-child(4n+1):nth-last-child(-n+4),
&:nth-child(4n+1):nth-last-child(-n+4) ~ .item {
margin-bottom: 0;
}
}
}
http://codepen.io/rustydev/pen/f7c8920e0beb0ba9a904da7ebd9970ae/
Overload less than operator, then sort. This is an example I found off the web...
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};
std::sort(myvector.begin(), myvector.end());
Source: here
ok, so I think it's actually possible (for the sake of argument):
>>> your_list = [5,6,7]
>>> 2 in zip(*enumerate(your_list))[0]
True
>>> 3 in zip(*enumerate(your_list))[0]
False
Use the object syntax.
v-bind:class="{'fa-checkbox-marked': content['cravings'], 'fa-checkbox-blank-outline': !content['cravings']}"
When the object gets more complicated, extract it into a method.
v-bind:class="getClass()"
methods:{
getClass(){
return {
'fa-checkbox-marked': this.content['cravings'],
'fa-checkbox-blank-outline': !this.content['cravings']}
}
}
Finally, you could make this work for any content property like this.
v-bind:class="getClass('cravings')"
methods:{
getClass(property){
return {
'fa-checkbox-marked': this.content[property],
'fa-checkbox-blank-outline': !this.content[property]
}
}
}
<div class="select">
<select name="you_are" id="dropdown" class="selection">
<option value="0" disabled selected>Select</option>
<option value="1">Student</option>
<option value="2">Full-time Job</option>
<option value="2">Part-time Job</option>
<option value="3">Job-Seeker</option>
<option value="4">Nothing Yet</option>
</select>
</div>
Insted of styling the select why dont you add a div out-side the select.
and style then in CSS
.select{
width: 100%;
height: 45px;
position: relative;
}
.select::after{
content: '\f0d7';
position: absolute;
top: 0px;
right: 10px;
font-family: 'Font Awesome 5 Free';
font-weight: 900;
color: #0b660b;
font-size: 45px;
z-index: 2;
}
#dropdown{
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
height: 45px;
width: 100%;
outline: none;
border: none;
border-bottom: 2px solid #0b660b;
font-size: 20px;
background-color: #0b660b23;
box-sizing: border-box;
padding-left: 10px;
padding-right: 10px;
}
There is a drawback of shared pointer: shared_pointer can't handle the parent-child cycle dependency. Means if the parent class uses the object of child class using a shared pointer, in the same file if child class uses the object of the parent class. The shared pointer will be failed to destruct all objects, even shared pointer is not at all calling the destructor in cycle dependency scenario. basically shared pointer doesn't support the reference count mechanism.
This drawback we can overcome using weak_pointer.
Please, note that Open and Close the connection is not necessary when using DataAdapter.
So I suggest please update this code and remove the open and close of the connection:
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
conn.Open(); // this line of code is uncessessary
Console.WriteLine("connection opened successfuly");
adapt.Fill(table);
conn.Close(); // this line of code is uncessessary
Console.WriteLine("connection closed successfuly");
The code shown in this example does not explicitly open and close the Connection. The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it also closes the connection when Fill is finished. This can simplify your code when you deal with a single operation such as a Fill or an Update. However, if you are performing multiple operations that require an open connection, you can improve the performance of your application by explicitly calling the Open method of the Connection, performing the operations against the data source, and then calling the Close method of the Connection. You should try to keep connections to the data source open as briefly as possible to free resources for use by other client applications.
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
1
2
Chair
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog
I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum
FROM table
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name
The result should be something :
-
0
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows
The whole idea is doing some simple check into the SELECT and sorting with the result.
The conflict message:
CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD
means that res/layout/dialog_item.xml
was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).
So you have to decide whether
git rm res/layout/dialog_item.xml
"or
git add res/layout/dialog_item.xml
"Then you finalize merge with "git commit
".
Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.
Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.
def getVector(data_array,col):
vector = []
imax = len(data_array)
for i in range(imax):
vector.append(data_array[i][col])
return ( vector )
a = ([1,2,3], [4,5,6])
b = getVector(a,1)
print(b)
Out>[2,5]
So if you need to transpose, you can do something like this:
def transposeArray(data_array):
# need to test if this is a 1D array
# can't do a len(data_array[0]) if it's 1D
two_d = True
if isinstance(data_array[0], list):
dimx = len(data_array[0])
else:
dimx = 1
two_d = False
dimy = len(data_array)
# init output transposed array
data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
# fill output transposed array
for i in range(dimx):
for j in range(dimy):
if two_d:
data_array_t[j][i] = data_array[i][j]
else:
data_array_t[j][i] = data_array[j]
return data_array_t
XML code:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false" />
</android.support.v4.widget.NestedScrollView>
in java code :
recycleView = (RecyclerView) findViewById(R.id.recycleView);
recycleView.setNestedScrollingEnabled(false);
This code is a very good example for a dynamic column with a cursor, since you cannot use '+' in @STATEMENT:
ALTER PROCEDURE dbo.spTEST
AS
SET NOCOUNT ON
DECLARE @query NVARCHAR(4000) = N'' --DATA FILTER
DECLARE @inputList NVARCHAR(4000) = ''
DECLARE @field sysname = '' --COLUMN NAME
DECLARE @my_cur CURSOR
EXECUTE SP_EXECUTESQL
N'SET @my_cur = CURSOR FAST_FORWARD FOR
SELECT
CASE @field
WHEN ''fn'' then fn
WHEN ''n_family_name'' then n_family_name
END
FROM
dbo.vCard
WHERE
CASE @field
WHEN ''fn'' then fn
WHEN ''n_family_name'' then n_family_name
END
LIKE ''%''+@query+''%'';
OPEN @my_cur;',
N'@field sysname, @query NVARCHAR(4000), @my_cur CURSOR OUTPUT',
@field = @field,
@query = @query,
@my_cur = @my_cur OUTPUT
FETCH NEXT FROM @my_cur INTO @inputList
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @inputList
FETCH NEXT FROM @my_cur INTO @inputList
END
RETURN
It's a named export vs a default export. export const
is a named export that exports a const declaration or declarations.
To emphasize: what matters here is the export
keyword as const
is used to declare a const declaration or declarations. export
may also be applied to other declarations such as class or function declarations.
Default Export (export default
)
You can have one default export per file. When you import you have to specify a name and import like so:
import MyDefaultExport from "./MyFileWithADefaultExport";
You can give this any name you like.
Named Export (export
)
With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:
// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";
// use MyClass, MyOtherClass, and MyClass2Alias here
Or it's possible to use a default along with named imports in the same statement:
import MyDefaultExport, { MyClass, MyOtherClass} from "./MyClass";
Namespace Import
It's also possible to import everything from the file on an object:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass, MyClasses.MyOtherClass and MyClasses.default here
Notes
A default export is actually a named export with the name default
so you are able to import it with a named import:
import { default as MyDefaultExport } from "./MyFileWithADefaultExport";
Use this simple code for generate med-strong password 12 length
$password_string = '!@#$%*&abcdefghijklmnpqrstuwxyzABCDEFGHJKLMNPQRSTUWXYZ23456789';
$password = substr(str_shuffle($password_string), 0, 12);
Aggregated List of Libraries
You can always use Array.prototype.reverse()
var data = _.sortBy(array_of_objects, ['type', 'name']).reverse();
Here are two approaches you can read raw resources using Kotlin.
You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.
Cheers mate
// R.raw.data_post
this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
If you can't use JodaTime, you can do the following:
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
There is more than one way to do that, the easiest I think would be:
find /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7
also this should work:
(cd /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7; ls | xargs -i echo `pwd`/{})
If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]'
, '[^a-zA-Z0-9][^a-zA-Z0-9]'
, ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.
A very simple solution to Q2 which I'm surprised nobody answered already. Use the method from Q1 to find the sum of the two missing numbers. Let's denote it by S, then one of the missing numbers is smaller than S/2 and the other is bigger than S/2 (duh). Sum all the numbers from 1 to S/2 and compare it to the formula's result (similarly to the method in Q1) to find the lower between the missing numbers. Subtract it from S to find the bigger missing number.
Please use the following query to list the tables in your DB.
select name from sys.Tables
In Addition, you can add a where
condition, to skip system generated tables and lists only user created table by adding type ='U'
Ex : select name from sys.Tables where type ='U'
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');
Try to change #include <gl/glut.h>
to #include "gl/glut.h"
in Visual Studio 2013.
A simple solution is – just to ignore user interactions :-)
video {
pointer-events: none;
}
A PivotTable might suit, though I am not quite certain of the layout of your data:
The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:
Now there is the pandas_profiling
package, which is a more complete alternative to df.describe()
.
If your pandas dataframe is df
, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.
import pandas_profiling
pandas_profiling.ProfileReport(df)
See the example notebook detailing the usage.
File one:
angular.module('myApp.controllers', []);
File two:
angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){
}]);
File three:
angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){
}]);
Include in that order. I recommend 3 files so the module declaration is on its own.
As for folder structure there are many many many opinions on the subject, but these two are pretty good
I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.
/*_x000D_
* A simple React component_x000D_
*/_x000D_
class App extends React.Component {_x000D_
constructor(params) {_x000D_
super(params) _x000D_
// initial gender state set from props_x000D_
this.state = {_x000D_
gender: this.props.gender_x000D_
}_x000D_
this.setGender = this.setGender.bind(this)_x000D_
}_x000D_
_x000D_
setGender(e) {_x000D_
this.setState({_x000D_
gender: e.target.value_x000D_
})_x000D_
}_x000D_
_x000D_
render() {_x000D_
const {gender} = this.state_x000D_
return <div>_x000D_
Gender:_x000D_
<div>_x000D_
<input type="radio" checked={gender == "male"} _x000D_
onClick={this.setGender} value="male" /> Male_x000D_
<input type="radio" checked={gender == "female"} _x000D_
onClick={this.setGender} value="female" /> Female_x000D_
</div>_x000D_
{ "Select Gender: " } {gender}_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* Render the above component into the div#app_x000D_
*/_x000D_
ReactDOM.render(<App gender="male" />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
HTML5: async
, defer
In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:
<script src="myscript.js"></script>
<script async src="myscript.js"></script>
<script defer src="myscript.js"></script>
Without async
or defer
, browser will run your script immediately, before rendering the elements that's below your script tag.
With async
(asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.
With defer
, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)
This slide show shows how to get both keys updated June 2013.
http://www.slideshare.net/Tweetganic/generate-twitter-applications
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType
is called on an object at runtime. In both cases the result is an object of the type System.Type
containing meta-information on a type.
Example where compile-time and run-time types are equal
string s = "hello";
Type t1 = typeof(string);
Type t2 = s.GetType();
t1 == t2 ==> true
Example where compile-time and run-time types are different
object obj = "hello";
Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType(); // ==> string!
t1 == t2 ==> false
i.e., the compile time type (static type) of the variable obj
is not the same as the runtime type of the object referenced by obj
.
Testing types
If, however, you only want to know whether mycontrol
is a TextBox
then you can simply test
if (mycontrol is TextBox)
Note that this is not completely equivalent to
if (mycontrol.GetType() == typeof(TextBox))
because mycontrol
could have a type that is derived from TextBox
. In that case the first comparison yields true
and the second false
! The first and easier variant is OK in most cases, since a control derived from TextBox
inherits everything that TextBox
has, probably adds more to it and is therefore assignment compatible to TextBox
.
public class MySpecializedTextBox : TextBox
{
}
MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting
If you have the following test followed by a cast and T is nullable ...
if (obj is T) {
T x = (T)obj; // The casting tests, whether obj is T again!
...
}
... you can change it to ...
T x = obj as T;
if (x != null) {
...
}
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as
operator followed by a test for null
is more performing.
Starting with C# 7.0 you can simplify the code by using pattern matching:
if (obj is T t) {
// t is a variable of type T having a non-null value.
...
}
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
if (o is int? ni) ===> does NOT compile!
This is because either the value is null
or it is an int
. This works for int? o
as well as for object o = new Nullable<int>(x);
:
if (o is int i) ===> OK!
I like it, because it eliminates the need to access the Nullable<T>.Value
property.
This is a little late answer, but I found this awesome post about NgModelController
, which I think is exactly what you were looking for.
TL;DR - you can use require: 'ngModel'
and then add NgModelController
to your linking function:
link: function(scope, iElement, iAttrs, ngModelCtrl) {
//TODO
}
This way, no hacks needed - you are using Angular's built-in ng-model
I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren't coding in C.
There is no law requiring only one exit point for a method in all programming languages. Some people insist on the superiority of this style, and sometimes they elevate it to a "rule" or "law" but this belief is not backed up by any evidence or research.
More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and try..finally
blocks (and using
blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation.
There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.
Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.
I have talked about this at greater length on my blog.
None of those worked for me. Try this.
console.log($(canvasjQueryElement)[0].width)
Concurrent programming regards operations that appear to overlap and is primarily concerned with the complexity that arises due to non-deterministic control flow. The quantitative costs associated with concurrent programs are typically both throughput and latency. Concurrent programs are often IO bound but not always, e.g. concurrent garbage collectors are entirely on-CPU. The pedagogical example of a concurrent program is a web crawler. This program initiates requests for web pages and accepts the responses concurrently as the results of the downloads become available, accumulating a set of pages that have already been visited. Control flow is non-deterministic because the responses are not necessarily received in the same order each time the program is run. This characteristic can make it very hard to debug concurrent programs. Some applications are fundamentally concurrent, e.g. web servers must handle client connections concurrently. Erlang is perhaps the most promising upcoming language for highly concurrent programming.
Parallel programming concerns operations that are overlapped for the specific goal of improving throughput. The difficulties of concurrent programming are evaded by making control flow deterministic. Typically, programs spawn sets of child tasks that run in parallel and the parent task only continues once every subtask has finished. This makes parallel programs much easier to debug. The hard part of parallel programming is performance optimization with respect to issues such as granularity and communication. The latter is still an issue in the context of multicores because there is a considerable cost associated with transferring data from one cache to another. Dense matrix-matrix multiply is a pedagogical example of parallel programming and it can be solved efficiently by using Straasen's divide-and-conquer algorithm and attacking the sub-problems in parallel. Cilk is perhaps the most promising language for high-performance parallel programming on shared-memory computers (including multicores).
Copied from my answer: https://stackoverflow.com/a/3982782
For primitive types (including bytes), use System.Buffer.BlockCopy
instead of System.Array.Copy
. It's faster.
I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:
System.Array.Copy
- 0.2187556 secondsSystem.Buffer.BlockCopy
- 0.1406286 secondsI increased the size of each array to 100 elements and re-ran the test:
System.Array.Copy
- 0.2812554 secondsSystem.Buffer.BlockCopy
- 0.2500048 secondsI increased the size of each array to 1000 elements and re-ran the test:
System.Array.Copy
- 1.0781457 secondsSystem.Buffer.BlockCopy
- 1.0156445 secondsFinally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:
System.Array.Copy
- 13.4533833 secondsSystem.Buffer.BlockCopy
- 13.1096267 secondsSo, if you need a new byte array, use
byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);
But, if you can use an IEnumerable<byte>
, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.
IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);
If you have an arbitrary number of arrays and are using .NET 3.5, you can make the System.Buffer.BlockCopy
solution more generic like this:
private byte[] Combine(params byte[][] arrays)
{
byte[] rv = new byte[arrays.Sum(a => a.Length)];
int offset = 0;
foreach (byte[] array in arrays) {
System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
offset += array.Length;
}
return rv;
}
*Note: The above block requires you adding the following namespace at the the top for it to work.
using System.Linq;
To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:
System.Array.Copy
- 78.20550510 secondsSystem.Buffer.BlockCopy
- 77.89261900 secondsThe point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.
You can also run your app like any other console applications but only after the publish.
Let's suppose you have the simple console app named MyTestConsoleApp. Open the package manager console and run the following command:
dotnet publish -c Debug -r win10-x64
-c flag mean that you want to use the debug configuration (in other case you should use Release value) - r flag mean that your application will be runned on Windows platform with x64 architecture.
When the publish procedure will be finished your will see the *.exe file located in your bin/Debug/publish directory.
Now you can call it via command line tools. So open the CMD window (or terminal) move to the directory where your *.exe file is located and write the next command:
>> MyTestConsoleApp.exe argument-list
For example:
>> MyTestConsoleApp.exe --input some_text -r true
I wouldn't recommend the HAVING
keyword for newbies, it is essentially for legacy purposes.
I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:
I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.
So I've taken a literal interpretation.
The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES
but it could be a VIEW
:
WITH PAYMENT_TALLIES (user_id, zip, tally)
AS
(
SELECT user_id, zip, COUNT(*) AS tally
FROM PAYMENT
GROUP
BY user_id, zip
)
SELECT DISTINCT *
FROM PAYMENT AS P
WHERE EXISTS (
SELECT *
FROM PAYMENT_TALLIES AS PT
WHERE P.user_id = PT.user_id
AND PT.tally > 1
);
Following block should work:
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
{% endif %}
Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.
So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.
You can also clear the packages directory and allow NuGet to re-download missing packages
it solved the issue for me
There is one more way to achieve it:-
Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
.Top = 30
.Left = 30
.Width = 200
.Height = 340
.ColumnHeads = True
.ColumnCount = 2
.ColumnWidths = "100;100"
.MultiSelect = fmMultiSelectExtended
.RowSource = "Sheet1!C4:D25"
End With End Sub
Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.
The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!
There's also MoSync Mobile SDK
GPL and commercial licensing. There's a good overview of their approach here.
Add theme to spinner
<Spinner style="@style/SpinnerTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Add spinnerTheme to styles.xml
<style name="SpinnerTheme" parent="android:Widget.Spinner">
<item name="android:background">@drawable/spinner_background</item>
</style>
Add New -> "Vector Asset" to drawable with e.g. "ic_keyboard_arrow_down_24dp"
Add spinner_background.xml to drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item android:drawable="@drawable/ic_keyboard_arrow_down_24dp" android:gravity="center_vertical|right" android:right="5dp"/>
</layer-list>
</item>
</selector>
For those who found this on google - there is a solution for this right now:
Socket.disconnect()
kicks the client (server-side). No chance for the client to stay connected :)
Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().
Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:
This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).
For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.
You could use COUNT(1) instead
In case you're using gradle, here is a full farJar task:
version = '1.0'
//create a single Jar with all dependencies
task fatJar(type: Jar) {
manifest {
attributes 'Implementation-Title': 'Gradle Jar File Example',
'Implementation-Version': version,
'Main-Class': 'com.example.main'
}
baseName = project.name + '-all'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
with jar
}
With C++11, the above would be possible for basic types as
class Foo {
public:
static constexpr int MEMBER = 1;
};
The constexpr
part creates a static expression as opposed to a static variable - and that behaves just like an extremely simple inline method definition. The approach proved a bit wobbly with C-string constexprs inside template classes, though.
A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal()
on the semaphore when a file is downloaded. The consumer calls wait()
on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.
A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait()
can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.
A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.
A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized
keyword. The synchronized
keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.
My vote would be for Conditional
[Conditional("DEBUG")]
public void DebugOnlyFunction()
{
// your code here
}
You can use this to add a function with advanced debugging features; like Debug.Write
, it is only called in debug builds, and so allows you to encapsulate complex debug logic outside the main flow of your program.
I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.
You can download the code by going to the Code tab and click the small 'Download' icon. As the author does not provide any pre-built downloads, you must compile it yourself. (I believe you can get it through NuGet though). There is no longer a .dll in the bin/ folder.
There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();
Make sure you checkout the Github page for the newest version and some better code examples.
Use a progress bar with the style set to Marquee
. This represents an indeterminate progress bar.
myProgressBar.Style = ProgressBarStyle.Marquee;
You can also use the MarqueeAnimationSpeed
property to set how long it will take the little block of color to animate across your progress bar.
Had the same error with PHP 7 on XAMPP and OSX.
The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That's how I did it:
Get root / intermediate certificate
First of all I had to figure out what's the root and the intermediate certificate.
The most convenient way is maybe an online cert-tool like the ssl-shopper
There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).
All I need to do is just search the internet for both of them. In my case, this is the root:
thawte DV SSL SHA256 CA
And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.
Get the host certificate
Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:
openssl s_client -showcerts -connect whatsyoururl.de:443 </dev/null 2>/dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert
Now bring them all together
Now just merge all of them into one file. (Maybe it's good to just put them into one folder, I just merged them into one file). You can do it like this:
cat /tmp/thawteRoot.crt > /tmp/chain.crt
cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt
tell PHP where to find the chain
There is this handy function openssl_get_cert_locations() that'll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).
So this is now my PHP-Code
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
"verify_peer"=> true,
"verify_peer_name"=> true,
),
);
$response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));
That's all. file_get_contents() is working again. Without CURL and hopefully without security flaws.
If you know the width of the span you could just stuff in a left margin.
Try this:
.center { text-align: center}
div.center span { display: table; }
Add the "center: class to your .
If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.
mysqladmin
is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).
You type that command from a shell prompt.
Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:
FLUSH HOSTS;
you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)
Adding user in docker and running your app under that user is very good practice for security point of view. To do that I would recommend below steps:
FROM node:10-alpine
# Copy source to container
RUN mkdir -p /usr/app/src
# Copy source code
COPY src /usr/app/src
COPY package.json /usr/app
COPY package-lock.json /usr/app
WORKDIR /usr/app
# Running npm install for production purpose will not run dev dependencies.
RUN npm install -only=production
# Create a user group 'xyzgroup'
RUN addgroup -S xyzgroup
# Create a user 'appuser' under 'xyzgroup'
RUN adduser -S -D -h /usr/app/src appuser xyzgroup
# Chown all the files to the app user.
RUN chown -R appuser:xyzgroup /usr/app
# Switch to 'appuser'
USER appuser
# Open the mapped port
EXPOSE 3000
# Start the process
CMD ["npm", "start"]
Above steps is a full example of the copying NodeJS project files, creating a user group and user, assigning permissions to the user for the project folder, switching to the newly created user and running the app under that user.
On CentOS 6.x and Redhat 6.x systems, the openjdk-devel package contains the jdk. It's sensible enough if you are familiar with the -devel pattern used in RedHat, but confusing if you're looking for a jdk package that conforms to java naming standards.
There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps
This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.
javascript it a rather timtoady language )
I'm late to the party but I found some useful instructions in github help page and I wanted to share them here.
Sometimes, Git can't make your change to a remote repository without losing commits. When this happens, your push is refused.
If another person has pushed to the same branch as you, Git won't be able to push your changes:
$ git push origin master
To https://github.com/USERNAME/REPOSITORY.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again. See the
'Note about fast-forwards' section of 'git push --help' for details.
You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:
$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work
Or, you can simply use git pull
to perform both commands at once:
$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work
Since API 21 there is an option set letter spacing. You can call method setLetterSpacing or set it in XML with attribute letterSpacing.
You could trying using a grid system like http://960.gs/
Your code would be something like this, assuming you're using a "12 column" layout:
<div class="container_12">
<div class="grid_4">1</div><div class="grid_4">2</div><div class="grid_4">3</div>
<div class="clear"></div>
<div class="grid_12">123</div>
</div>
cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.
In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
You can make HTTP requests without cURL, too, though it requires allow_url_fopen
to be enabled in your php.ini
file.
// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');
I am new to Rust, but this solution seems to work:
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref GLOBAL: Arc<Mutex<GlobalType> =
Arc::new(Mutex::new(GlobalType::new()));
}
Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.
Both solutions should provide a safe approach to using global variables.
Properties prop = new Properties();
String fileName = "./src/test/resources/predefined.properties";
FileInputStream inputStream = new FileInputStream(fileName);
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
It's because Arrays.asList(array)
return List<int[]>
. array
argument is treated as one value you want to wrap (you get list of arrays of ints), not as vararg.
Note that it does work with object types (not primitives):
public boolean contains(final String[] array, final String key) {
return Arrays.asList(array).contains(key);
}
or even:
public <T> boolean contains(final T[] array, final T key) {
return Arrays.asList(array).contains(key);
}
But you cannot have List<int>
and autoboxing is not working here.
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
Suppose if you want to replace the above with some other info.
COMMAND(:%s/\/sys\/sim\/source\/gm\/kg\/jl\/ls\/owow\/lsal/sys.pkg.mpu.umc.kdk./g)
In this the above will be get replaced with (sys.pkg.mpu.umc.kdk.
) .
You don't need an index, as the List<T>
class allows you to remove items by value rather than index by using the Remove
function.
foreach(car item in list1) list2.Remove(item);
This is all that is needed:
<!doctype html>
<script src="/path.js"></script>
You know, I like to keep it simple, but clear... So here's what I use, in C:
i,n,c
,etc... (Only one letter. If one letter isn't
clear, then make it a Local Variable)lowerCamelCase
g_lowerCamelCase
ALL_CAPS
p_
to the prefix. For global variables it would be gp_var
, for local variables p_var
, for const variables p_VAR
. If far pointers are used then use an fp_
instead of p_
.ModuleCamelCase
(Module = full module name, or a 2-3 letter abbreviation, but still in CamelCase
.)lowerCamelCase
ModuleCamelCase
ALL_CAPS
ModuleCamelCase
CamelCase
CamelCase
I typedef my structs, but use the same name for both the tag and the typedef. The tag is not meant to be commonly used. Instead it's preferrable to use the typedef. I also forward declare the typedef in the public module header for encapsulation and so that I can use the typedef'd name in the definition.
Full struct
Example:
typdef struct TheName TheName;
struct TheName{
int var;
TheName *p_link;
};
You could use AJAX to send a POST request if you don't want forms.
Using jquery $.post method it is pretty simple:
$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
alert('successfully posted key1=value1&key2=value2 to foo.php');
});
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
The simplest example I can think of in JavaScript is the setTimeout()
function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs
library to read a file. The fs
module exposes two unique API functions: readFile
and readFileSync
.
The readFile
function is asynchronous while readFileSync
is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile
and readFileSync
instead of readFile
and readFileAsync
. Here is an example of using both functions.
Synchronous:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txt
are read into memory and stored in the variable data
. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
Asynchronous (with callback):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments err
and data
. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err
has a value before you do anything else. If so, stop execution of the callback and log the error.
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch
block.
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch
. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
//by importing Decimal format we can do...
import java.util.Scanner;
import java.text.DecimalFormat;
public class Average
{
public static void main(String[] args)
{
int sub1,sub2,sub3,total;
Scanner in = new Scanner(System.in);
System.out.print("Enter Subject 1 Marks : ");
sub1 = in.nextInt();
System.out.print("Enter Subject 2 Marks : ");
sub2 = in.nextInt();
System.out.print("Enter Subject 3 Marks : ");
sub3 = in.nextInt();
total = sub1 + sub2 + sub3;
System.out.println("Total Marks of Subjects = " + total);
res = (float)total;
average = res/3;
System.out.println("Before Rounding Decimal.. Average = " +average +"%");
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("After Rounding Decimal.. Average = " +df.format(average)+"%");
}
}
/* Output
Enter Subject 1 Marks : 72
Enter Subject 2 Marks : 42
Enter Subject 3 Marks : 52
Total Marks of Subjects = 166
Before Rounding Decimal.. Average = 55.333332%
After Rounding Decimal.. Average = 55.33%
*/
/* Output
Enter Subject 1 Marks : 98
Enter Subject 2 Marks : 88
Enter Subject 3 Marks : 78
Total Marks of Subjects = 264
Before Rounding Decimal.. Average = 88.0%
After Rounding Decimal.. Average = 88%
*/
/* You can Find Avrerage values in two ouputs before rounding average
And After rounding Average..*/
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
Use svn revert --recursive folder_name
svn revert
is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.
http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
I think you can find the answer you want in these two posts. They are mentioning Flash Builder, but essentially, the talk is about its Eclipse base.
Clear improperly cached compile errors in FlexBuilder: http://blog.aherrman.com/2010/05/clear-improperly-cached-compile-errors.html
How to fix Flash Builder broken workspace: http://va.lent.in/how-to-fix-flash-builder-broken-workspace/
Here is my code for disabling all scrolling in webview:
// disable scroll on touch
webview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
To only hide the scrollbars, but not disable scrolling:
WebView.setVerticalScrollBarEnabled(false);
WebView.setHorizontalScrollBarEnabled(false);
or you can try using single column layout but this only works with simple pages and it disables horizontal scrolling:
//Only disabled the horizontal scrolling:
webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
You can also try to wrap your webview with vertically scrolling scrollview and disable all scrolling on the webview:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical" >
<WebView
android:id="@+id/mywebview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />
</ScrollView>
And set
webview.setScrollContainer(false);
Don't forget to add the webview.setOnTouchListener(...)
code above to disable all scrolling in the webview. The vertical ScrollView will allow for scrolling of the WebView's content.
You are missing the selector in the .on
function:
.on(eventType, selector, function)
This selector is very important!
If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler
See jQuery 1.9 .live() is not a function for more details.
For what it's worth; I had this error on a app that was running services in the background. On one of them a timeout dialog had to be shown to the user. That dialog was the issue causing this error if the app was no longer running in the foreground.
In our case showing the dialog wasn't useful when app was in background so we just kept track of that (boolean flagged onPause en onResume) and then only show the dialog when the app is actually visible to the user.
If you want to use SelectedValue then your combobox must be databound.
To set up the combobox:
ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
To get the data:
Function GetMailItems() As List(Of MailItem)
Dim mailItems = New List(Of MailItem)
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
End While
End If
Return mailItems
End Function
Public Class MailItem
Public Sub New(ByVal id As Integer, ByVal name As String)
mID = id
mName = name
End Sub
Private mID As Integer
Public Property ID() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
End Class
When using IN
with a collection-valued parameter you don't need (...)
:
@NamedQuery(name = "EventLog.viewDatesInclude",
query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND "
+ "el.timeMark <= :dateTo AND "
+ "el.name IN :inclList")
If you want to move from c:\
and you want to go to c:\Documents and settings
, write on console: c:\Documents\[space]+tab
and cygwin will autocomplete it as c:\Documents\ and\ settings/
This command did it for me:
zip -r Target.zip Source -x "*.DS_Store"
Target.zip
is the zip file to create. Source
is the source file/folder to zip up. And the _x
parameter specifies the file/folder to not include. If the above doesn't work for whatever reason, try this instead:
zip -r Target.zip Source -x "*.DS_Store" -x "__MACOSX"
Try this
@font-face { _x000D_
src: url(fonts/Market_vilis.ttf) format("truetype");_x000D_
}_x000D_
div.FontMarket { _x000D_
font-family: Market Deco;_x000D_
}
_x000D_
<div class="FontMarket">KhonKaen Market</div>
_x000D_
vilis.org
Not quite 1 query, still quite short and sweet:
-- Disable all referential integrity constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name +' drop constraint ' + Constraint_Name from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO
-- Drop all tables
EXEC sp_msforeachtable 'DROP TABLE ?'
GO
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
For me following worked:
in directive declare it like this:
.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
myFunction: '=',
},
templateUrl: 'myDirective.html'
};
})
In directive template use it in following way:
<select ng-change="myFunction(selectedAmount)">
And then when you use the directive, pass the function like this:
<data-my-directive
data-my-function="setSelectedAmount">
</data-my-directive>
You pass the function by its declaration and it is called from directive and parameters are populated.
Just do one thing, We need to set the name property for the same types. for eg.
Try below:
<form>
<div id="group1">
<input type="radio" value="val1" name="group1">
<input type="radio" value="val2" name="group1">
</div>
</form>
And also we can do it in angular1,angular 2 or in jquery also.
<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>
Modify the existing layout params and set layout params again
//Get the current layout params and update the Gravity
(iv.layoutParams as FrameLayout.LayoutParams).gravity = Gravity.START
//Set layout params again (this updates the view)
iv.layoutParams = layoutParams
For scala
import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))
i think the main things to remember about parsing csv is that it follows some simple rules:
a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns
have a read of this post to see what i am talking about
it's actually very easy to do once you have the hang of it and becomes very useful.
doctormad's solution is not correct. try this:
$var = '1a';
if ((int) $var == $var) {
var_dump("$var is an integer, really?");
}
this prints
1a is an integer, really?"
use filter_var() with FILTER_VALIDATE_INT argument
$data = Array('0', '1', '1a', '1.1', '1e', '0x24', PHP_INT_MAX+1);
array_walk($data, function ($num){
$is_int = filter_var($num, FILTER_VALIDATE_INT);
if ($is_int === false)
var_dump("$num is not int");
});
this prints
1a is not int
1.1 is not int
1e is not int
0x24 is not int
9.2233720368548E+18 is not int
You can use the adb
command which comes in the tools dir of the SDK:
adb shell
It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:
adb pull /sdcard/the_file_you_want.txt
Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)
Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.
I was getting this message for the <specFlow>
element and therefore I added a specflow.xsd
file to the solution this answer (with some modifications to allow for the <plugins>
element).
Thereafter I (like Pressacco), right clicked within the file buffer of app.config
and selected properties, and within Schemas
, I added "specflow.xsd"
to the end. The entirety of Schemas
now reads:
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
alternative commands that does same job
tr -d ",$" < infile
awk 'gsub(",$","")' infile
How about
...
C() : arr{ {1,2,3} }
{}
...
?
Compiles fine on g++ 4.8
you can also try lsblk ... is in util-linux ... but i have a question too
fdisk -l /dev/sdl
no result
grep sdl /proc/partitions
8 176 15632384 sdl
8 177 15628288 sdl1
lsblk | grep sdl
sdl 8:176 1 14.9G 0 disk
`-sdl1 8:177 1 14.9G 0 part
fdisk is good but not that good ... seems like it cannot "see" everything
in my particular example i have a stick that have also a card reader build in it and i can see only the stick using fdisk:
fdisk -l /dev/sdk
Disk /dev/sdk: 15.9 GB, 15931539456 bytes
255 heads, 63 sectors/track, 1936 cylinders, total 31116288 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xbe24be24
Device Boot Start End Blocks Id System
/dev/sdk1 * 8192 31116287 15554048 c W95 FAT32 (LBA)
but not the card (card being /dev/sdl)
also, file -s is inefficient ...
file -s /dev/sdl1
/dev/sdl1: sticky x86 boot sector, code offset 0x52, OEM-ID "NTFS ", sectors/cluster 8, reserved sectors 0, Media descriptor 0xf8, heads 255, hidden sectors 8192, dos < 4.0 BootSector (0x0)
that's nice ... BUT
fdisk -l /dev/sdb
/dev/sdb1 2048 156301487 78149720 fd Linux raid autodetect
/dev/sdb2 156301488 160086527 1892520 82 Linux swap / Solaris
file -s /dev/sdb1
/dev/sdb1: sticky \0
to see information about a disk that cannot be accesed by fdisk, you can use parted:
parted /dev/sdl print
Model: Mass Storage Device (scsi)
Disk /dev/sdl: 16.0GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 4194kB 16.0GB 16.0GB primary ntfs
arted /dev/sdb print
Model: ATA Maxtor 6Y080P0 (scsi)
Disk /dev/sdb: 82.0GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 1049kB 80.0GB 80.0GB primary raid
2 80.0GB 82.0GB 1938MB primary linux-swap(v1)
I combined two solutions in one method and it works for me for API 24 and for API 21. Others I didn't test.
The code in Kotlin:
private fun isAppInForeground(context: Context): Boolean {
val appProcessInfo = ActivityManager.RunningAppProcessInfo()
ActivityManager.getMyMemoryState(appProcessInfo)
if (appProcessInfo.importance == IMPORTANCE_FOREGROUND ||
appProcessInfo.importance == IMPORTANCE_VISIBLE) {
return true
} else if (appProcessInfo.importance == IMPORTANCE_TOP_SLEEPING ||
appProcessInfo.importance == IMPORTANCE_BACKGROUND) {
return false
}
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val foregroundTaskInfo = am.getRunningTasks(1)[0]
val foregroundTaskPackageName = foregroundTaskInfo.topActivity.packageName
return foregroundTaskPackageName.toLowerCase() == context.packageName.toLowerCase()
}
and in Manifest
<!-- Check whether app in background or foreground -->
<uses-permission android:name="android.permission.GET_TASKS" />
Even if there are tools that allow you to mock your database in one way or another (e.g. jOOQ's MockConnection
, which can be seen in this answer - disclaimer, I work for jOOQ's vendor), I would advise not to mock larger databases with complex queries.
Even if you just want to integration-test your ORM, beware that an ORM issues a very complex series of queries to your database, that may vary in
Mocking all that to produce sensible dummy data is quite hard, unless you're actually building a little database inside your mock, which interprets the transmitted SQL statements. Having said so, use a well-known integration-test database that you can easily reset with well-known data, against which you can run your integration tests.
As said in the comments, the problem lies in your script. Actually, there are 2 problems:
None
somewhere. Maybe due to the defaultdict ?show()
after each subplot. show()
should be called once at the end of your script. The alternative is to use interactive mode, look for ion
in matplotlib's documentation.Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException
this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
You need
.abc,.ab {
display: none;
}
#f:hover ~ .ab {
display: block;
}
#s:hover ~ .abc {
display: block;
}
#s:hover ~ .a,
#f:hover ~ .a{
display: none;
}
Updated demo at http://jsfiddle.net/gaby/n5fzB/2/
The problem in your original CSS was that the ,
in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a
means #f:hover ~ .abc
and .a
. You set that to display:none
so it was always set to be hidden for all .a
elements.
Because both a
and b
have only one axis, as their shape is (3)
, and the axis parameter specifically refers to the axis of the elements to concatenate.
this example should clarify what concatenate
is doing with axis. Take two vectors with two axis, with shape (2,3)
:
a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])
concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):
np.concatenate((a,b), axis=0)
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):
np.concatenate((a, b), axis=1)
array([[ 1, 5, 9, 3, 7, 11],
[ 2, 6, 10, 4, 8, 12]])
to obtain the output you presented, you can use vstack
a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
[4, 5, 6]])
You can still do it with concatenate
, but you need to reshape them first:
np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
[4, 5, 6]])
Finally, as proposed in the comments, one way to reshape them is to use newaxis
:
np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))
Use StringBuilder
:
String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
sb.append(c);
str = sb.toString();
One-liner:
new StringBuilder().append(a).append(b).append(c).toString();
Doing ""+a+b+c
gives:
new StringBuilder().append("").append(a).append(b).append(c).toString();
I asked some time ago related question.
#include #include
not original cv.h
This error may be also related to the fact that you have an error in your "spring.datasource.url" when you gave a wrong db name for example
Nornally the tag is used for that, with a change in style.
Like
<p>This is my text <span class="highlight"> and these words are different</span></p>
,
You set the css in the header (or rather, in a separate css file) to make your "highlight" text assume the color you wish.
(e.g.: with
<style type="text/css">
.highlight {color: orange}
</style>
in the header. Avoid using the tag <font />
for that at all costs. :-)
It works perfectly for me too.
<project>
.....
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>WebContent\WEB-INF\web.xml</webXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
An alternative solution to using the <ripple>
tag (which I personally prefer not to do, because the colors are not "default"), is the following:
Create a drawable for the button background, and include <item android:drawable="?attr/selectableItemBackground">
in the <layer-list>
Then (and I think this is the important part) programmatically set backgroundResource(R.drawable.custom_button)
on your button instance.
Button btn_temp = view.findViewById(R.id.btn_temp);
btn_temp.setBackgroundResource(R.drawable.custom_button);
<Button
android:id="@+id/btn_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button"
android:text="Test" />
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="10dp" />
</shape>
</item>
<item android:drawable="?attr/selectableItemBackground" />
</layer-list>
css :hover
kinda is like js onmouseover
row1 {
// your css
}
row1:hover {
color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
border: 1px solid red;
}
not too sure how it works but css applies styles to echo'ed ids
In my case, the original repository was a bare one.
So, I had to type (in windows):
mkdir dest
cd dest
git init
git remote add origin a\valid\yet\bare\repository
git pull origin master
To check if a repository is a bare one:
git rev-parse --is-bare-repository
HTML
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="main_body">
some text
</div>
</body>
</html>
CSS
body
{
width: 100%;
Height: 100%;
}
#main_body
{
background: #ff3333;
width: 200px;
position: absolute;
}?
JS ( jQuery )
$(function(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var main = $("#main_body");
$("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});
See example here
Here is a reliable solution that works with 32bit and 64bit applications.
Add these references:
using System.Diagnostics;
using System.Management;
Add this method to your project:
public static string GetProcessPath(int processId)
{
string MethodResult = "";
try
{
string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
{
using (ManagementObjectCollection moc = mos.Get())
{
string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();
MethodResult = ExecutablePath;
}
}
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
Now use it like so:
int RootProcessId = Process.GetCurrentProcess().Id;
GetProcessPath(RootProcessId);
Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.
Extra, for those interested:
Process.GetProcesses()
...will give you an array of all the currently running processes, and...
Process.GetCurrentProcess()
...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*
Maybe I can still help somebody out who bumps into this question, because this is a very old issue.
I needed this as well and wrote a behavior to take care of this. So here is the behavior:
public class StretchMaxWidthBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
((FrameworkElement)this.AssociatedObject.Parent).SizeChanged += this.OnSizeChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
((FrameworkElement)this.AssociatedObject.Parent).SizeChanged -= this.OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
this.SetAlignments();
}
private void SetAlignments()
{
var slot = LayoutInformation.GetLayoutSlot(this.AssociatedObject);
var newWidth = slot.Width;
var newHeight = slot.Height;
if (!double.IsInfinity(this.AssociatedObject.MaxWidth))
{
if (this.AssociatedObject.MaxWidth < newWidth)
{
this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Left;
this.AssociatedObject.Width = this.AssociatedObject.MaxWidth;
}
else
{
this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Stretch;
this.AssociatedObject.Width = double.NaN;
}
}
if (!double.IsInfinity(this.AssociatedObject.MaxHeight))
{
if (this.AssociatedObject.MaxHeight < newHeight)
{
this.AssociatedObject.VerticalAlignment = VerticalAlignment.Top;
this.AssociatedObject.Height = this.AssociatedObject.MaxHeight;
}
else
{
this.AssociatedObject.VerticalAlignment = VerticalAlignment.Stretch;
this.AssociatedObject.Height = double.NaN;
}
}
}
}
Then you can use it like so:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Label" />
<TextBox Grid.Column="1" MaxWidth="600">
<i:Interaction.Behaviors>
<cbh:StretchMaxWidthBehavior/>
</i:Interaction.Behaviors>
</TextBox>
</Grid>
And finally to forget to use the System.Windows.Interactivity
namespace to use the behavior.
Right, I'm not sure if it will work for others but worked for me.
I changed proxyPort
to 8080 and used jcenter instead of Maven. But I had to apply expeption to use HTTP instead of HTTPS. This is what I have in my build.gradle for build script and allprojects
buildscript {
repositories {
jcenter {
url "http://jcenter.bintray.com/"
}
}
}
allprojects {
repositories {
jcenter {
url "http://jcenter.bintray.com/"
}
}
}
UPDATE: 06/08
I have recently updated Gradle and plugin version and had some problems. It was complaining about plugin com.android.application
I did some digging around and changed
jcenter {
url "http://jcenter.bintray.com/"
}
to
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Try this
> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like or or any no]["Column name in which you want to add data"] = Value;
var date = new Date("2012-01-18T16:03");
console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );
As of pandas 0.20.3, use .to_pydatetime()
to convert any pandas.DateTimeIndex
instances to Python datetime.datetime
.
You could try Trevor, which uses Docker to run your Travis build.
From its description:
I often need to run tests for multiple versions of Node.js. But I don't want to switch versions manually using n/nvm or push the code to Travis CI just to run the tests.
That's why I created Trevor. It reads .travis.yml and runs tests in all versions you requested, just like Travis CI. Now, you can test before push and keep your git history clean.
Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.
Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid())
(_getpid()
on Windows), but that still won't be random.
The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random
(Linux) or CryptGenRandom()
(Windows), or from a service like random.org
.
What about:
#region Using Statements
using System;
using System.Xml;
#endregion
class Program {
static void Main( string[ ] args ) {
XmlDocument doc = new XmlDocument( );
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore( xmlDeclaration, root );
//(2) string.Empty makes cleaner code
XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
doc.AppendChild( element1 );
XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
element1.AppendChild( element2 );
XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text1 = doc.CreateTextNode( "text" );
element3.AppendChild( text1 );
element2.AppendChild( element3 );
XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text2 = doc.CreateTextNode( "other text" );
element4.AppendChild( text2 );
element2.AppendChild( element4 );
doc.Save( "D:\\document.xml" );
}
}
(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?
The result is:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>other text</level2>
</level1>
</body>
But I recommend you to use LINQ to XML which is simpler and more readable like here:
#region Using Statements
using System;
using System.Xml.Linq;
#endregion
class Program {
static void Main( string[ ] args ) {
XDocument doc = new XDocument( new XElement( "body",
new XElement( "level1",
new XElement( "level2", "text" ),
new XElement( "level2", "other text" ) ) ) );
doc.Save( "D:\\document.xml" );
}
}
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
in Global.asax add
public override void Init()
{
this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
give it a shot ;)
If the problem persists probably Hyper-V on your system is corrupted, so
Go in Control Panel -> [Programs] -> [Windows Features] and completely uncheck all Hyper-V related components. Restart the system.
Enable Hyper-V again. Restart.
For me, i was cloning a project from github which used a version of gradle higher than that which i had installed. I had two choices:
Open gradle.wrapper-properties of a project you have that's building successfully, and copy the line that says distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
. Use this to replace the same value in the project that's failing. That should do the trick.
Your build might still fail if the gradle version used to build the project is higher than that which you just added. For this you should update the gradle version to the latest.
Map.of
literalsAs of Java 9, there is yet another way to instantiate a Map
. You can create an unmodifiable map from zero, one, or several pairs of objects in a single-line of code. This is quite convenient in many situations.
For an empty Map
that cannot be modified, call Map.of()
. Why would you want an empty set that cannot be changed? One common case is to avoid returning a NULL where you have no valid content.
For a single key-value pair, call Map.of( myKey , myValue )
. For example, Map.of( "favorite_color" , "purple" )
.
For multiple key-value pairs, use a series of key-value pairs. ``Map.of( "favorite_foreground_color" , "purple" , "favorite_background_color" , "cream" )`.
If those pairs are difficult to read, you may want to use Map.of
and pass Map.Entry
objects.
Note that we get back an object of the Map
interface. We do not know the underlying concrete class used to make our object. Indeed, the Java team is free to used different concrete classes for different data, or to vary the class in future releases of Java.
The rules discussed in other Answers still apply here, with regard to type-safety. You declare your intended types, and your passed objects must comply. If you want values of various types, use Object
.
Map< String , Color > preferences = Map.of( "favorite_color" , Color.BLUE ) ;
To be complete, a short introduction for "shell noobs":
First of all, start your shell - you can find it inside the common desktop environments under the name "Terminal" or "Shell" somewhere in the desktops application menu.
You can also try using the key combo CTRL+F2, followed by one of those commands (depending on the desktop envrionment you're using) and the ENTER key:
xfce4-terminal
gnome-console
terminal
rxvt
konsole
If all of the above fail, try using xterm
- it'll work in most cases.
Hint for the following commands: Execute the commands without the $
- it's just a marker identifying that you're on the shell.
After that just fire up mongod
with the --version
flag:
$ mongod --version
It shows you then something like
$ mongod --version
db version v2.4.6
Wed Oct 16 16:17:00.241 git version: nogitversion
To update it just execute
$ sudo apt-get update
and then
$ sudo apt-get install mongodb
I got similar error msgs. I run svn clean-up, and then tried "get clock" for a few times. Then this error was gone.