Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
E.g
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.
In batch you could do it like this:
@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
If you don't need the variable !var!
elsewhere in the loop, you could simplify that to
@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
However, like C.B. I'd prefer PowerShell if at all possible:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
Again, this could be simplified if you don't need $var
elsewhere in the loop:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
I know the post is kinda old, but I have found a solution easy that works on Debian based distribution without compiling nginx from source.
First install nginx-extras package
sudo apt install nginx-extras
Then load the nginx http headers more module by editing nginx.conf and adding the following line inside the server block
load_module modules/ngx_http_headers_more_filter_module.so;
Once it's done you'll have access to both more_set_headers and more_clear_headers directives.
COM is definitely not a good way to go. More specifically, it's a no go if you're dealing with web environment...
I've used with success the following open source projects:
ExcelPackage for OOXML formats (Office 2007)
NPOI for .XLS format (Office 2003)
Take a look at these blog posts:
stoi is available "since C++11". Make sure your compiler is up to date.
You can try atoi(hours0.c_str()) instead.
It's because you have:
def readTTable(fname):
try:
without a matching except
block after the try:
block. Every try
must have at least one matching except
.
See the Errors and Exceptions section of the Python tutorial.
Follow the instructions given here at NodeSource which is dedicated to creating a sustainable ecosystem for Node.js.
For Node.js >= 4.X
# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs
# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_4.x | bash -
apt-get install -y nodejs
If you want to sum the digit of a number, one way to do it is using sum()
+ a generator expression:
sum(int(i) for i in str(155))
I modified a little your code using sum()
, maybe you want to take a look at it:
birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln
Simple and effective.
Eslint 6.7.0 brought "ignorePatterns" to write it in .eslintrc.json like this example:
{
"ignorePatterns": ["fileToBeIgnored.js"],
"rules": {
//...
}
}
Adding this to your code android:focusableInTouchMode="true"
will make sure that your keypad doesn't appear on startup for your edittext box. You want to add this line to your linear layout that contains the EditTextBox. You should be able to play with this to solve both your problems. I have tested this. Simple solution.
ie: In your app_list_view.xml file
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusableInTouchMode="true">
<EditText
android:id="@+id/filter_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="@id/android:list"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:layout_width="fill_parent"
android:focusable="true"
android:descendantFocusability="beforeDescendants"/>
</LinearLayout>
------------------ EDIT: To Make keyboard appear on startup -----------------------
This is to make they Keyboard appear on the username edittextbox on startup. All I've done is added an empty Scrollview to the bottom of the .xml file, this puts the first edittext into focus and pops up the keyboard. I admit this is a hack, but I am assuming you just want this to work. I've tested it, and it works fine.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dip"
android:paddingRight="20dip">
<EditText
android:id="@+id/userName"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
/>
<EditText
android:id="@+id/password"
android:password="true"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password" />
<ScrollView
android:id="@+id/ScrollView01"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ScrollView>
</LinearLayout>
If you are looking for a more eloquent solution, I've found this question which might help you out, it is not as simple as the solution above but probably a better solution. I haven't tested it but it apparently works. I think it is similar to the solution you've tried which didn't work for you though.
Hope this is what you are looking for.
Cheers!
open your Redis cli and There two possible option that you could use:
FLUSHDB - Delete all the keys of the currently selected DB. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.
Just in case anyone else encounters the same problems.
Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().
You can easily find out investigating the Laravel source:
// Illuminate\Database\Eloquent\Model.php
...
/**
* Get an attribute from the model.
*
* @param string $key
* @return mixed
*/
public function getAttribute($key)
{
$inAttributes = array_key_exists($key, $this->attributes);
// If the key references an attribute, we can just go ahead and return the
// plain attribute value from the model. This allows every attribute to
// be dynamically accessed through the _get method without accessors.
if ($inAttributes || $this->hasGetMutator($key))
{
return $this->getAttributeValue($key);
}
// If the key already exists in the relationships array, it just means the
// relationship has already been loaded, so we'll just return it out of
// here because there is no need to query within the relations twice.
if (array_key_exists($key, $this->relations))
{
return $this->relations[$key];
}
// If the "attribute" exists as a method on the model, we will just assume
// it is a relationship and will load and return results from the query
// and hydrate the relationship's value on the "relationships" array.
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
}
This also explains why my code worked, whenever I loaded the data using the load() method before.
Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.
The length of the array is 7, the NUL character \0
still counts as a character and the string is still terminated with an implicit \0
See this link to see a working example
Note that had you declared str
as char str[6]= "Hello\0";
the length would be 6 because the implicit NUL is only added if it can fit (which it can't in this example.)
§ 6.7.8/p14
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Sucessive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
char str[] = "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[5]= "Hello\0"; /* sizeof == 5, str is "Hello" with no NUL (no longer a C-string, just an array of char). This may trigger compiler warning */
char str[6]= "Hello\0"; /* sizeof == 6, Explicit NUL only */
char str[7]= "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[8]= "Hello\0"; /* sizeof == 8, Explicit + two Implicit NUL */
(() => {
'use strict';
const needle = 'SortOrder|Page'; // example
if ( needle === '' || needle === '{{1}}' ) {
return;
}
const needles = needle.split(/\s*\|\s*/);
const querystripper = ev => {
if (ev) { window.removeEventListener(ev.type, querystripper, true);}
try {
const url = new URL(location.href);
const params = new URLSearchParams(url.search.slice(1));
for (const needleremover of needles) {
if (params.has(needleremover)) {
url.searchParams.delete(needleremover);
window.location.href = url;
}
}
} catch (ex) { }
};
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', querystripper, true);
} else {
querystripper();
}
})();
That's how I did it, also has RegEx support.
Well, technically '\0'
is a character while "\0"
is a string, so if you're checking for the null termination character the former is correct. However, as Chris Lutz points out in his answer, your comparison won't work in it's current form.
HAVING
operates on aggregates. Since COUNT
is an aggregate function, you can't use it in a WHERE
clause.
Here's some reading from MSDN on aggregate functions.
Send the passwordbox control as a parameter to your login command.
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
if (count($arr) >= 2)
{
// array has at least 2 elements
}
sizeof()
is an alias for count()
. Both work with non-arrays too, but they will only return values greater than 1 if the argument is either an array or a Countable
object, so you're pretty safe with this.
Another option, along the same lines as Blorgbeard is out's, is to use something like:
SET /P pw=C:\^>
The ^
escapes the >
so that the password prompt will look like a standard cmd console prompt.
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
In SSMS expand your database in Object Explorer, go to Tables, right click on the table you're interested in and select Script Table As, Create To, New Query Editor Window.
Do a find and replace (CTRL + H) to change the table name (i.e. put ABC
in the Find What field and ABC_1
in the Replace With then click OK).
The other answers showing how to do this by SQL also work well, but the difference with this method is you'll also get any indexes, constraints and triggers.
If you want to include data, after creating this table run the below script to copy all data from ABC (keeping the same ID values if you have an identity field):
set identity_insert ABC_1 on
insert into ABC_1 (column1, column2) select column1, column2 from ABC
set identity_insert ABC_1 off
Don't know if this will help anyone, but I solved a similar problem by specifying specific width sizes in percentage for each column. Obviously, this would work best if each column has content with width that doesn't vary too widely.
Your mistake is using the datetime
module instead of the date
module. You meant to do this:
from datetime import date
date = models.DateField(_("Date"), default=date.today)
If you only want to capture the current date the proper way to handle this is to use the auto_now_add
parameter:
date = models.DateField(_("Date"), auto_now_add=True)
However, the modelfield docs clearly state that auto_now_add
and auto_now
will always use the current date and are not a default value that you can override.
From: http://georgovassilis.blogspot.ca/2015/10/spring-mvc-rest-controller-says-406.html
You've got this Spring @RestController and mapped a URL that contains an email as part of the URL path. You cunningly worked around the dot truncation issue [1] and you are ready to roll. And suddenly, on some URLs, Spring will return a 406 [2] which says that the browser requested a certain content type and Spring can't serialize the response to that content type. The point is, you've been doing Spring applications for years and you did all the MVC declarations right and you included Jackson and basically you are stuck. Even worse, it will spit that error out only on some emails in the URL path, most notably those ending in a ".com" domain.
@RequestMapping(value = "/agenda/{email:.+}", method = RequestMethod.GET)
public List<AgendaEntryDTO> checkAgenda(@PathVariable("email") String email)
The issue [3] is quite tricky: the application server performs some content negotiation and convinces Spring that the browser requested a "application/x-msdownload" content, despite that occurring nowhere in the request the browser actually submitted.
The solution is to specify a content negotiation manager for the web application context:
<mvc:annotation-driven enable-matrix-variables="true"
content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="false" />
<property name="parameterName" value="mediaType" />
<property name="ignoreAcceptHeader" value="false" />
<property name="useJaf" value="false" />
</bean>
I don't think you can save it without it appearing, but just for saving in multiple formats use the print command. See the answer posted here: Save an imagesc output in Matlab
MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.
The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.
By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)
The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.
As 18 8-bit chars: 144 bits
As 18 4-bit nybbles: 72 bits
As 2 32-bit integers: 64 bits
Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.
So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.
With an 7-bit int: 0 - 99
With a 15-bit int: 0 - 9,999
With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)
1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.
This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.
Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.
In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.
The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.
As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.
I was able to do this for Android 2.1 devices and above using an App Compatibility library theme applied to the app element in the manifest:
<application
...
android:theme="@style/AppTheme" />
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
...
<item name="windowNoTitle">true</item>
<item name="android:windowNoTitle">true</item>
</style>
Note: You will need to include the com.android.support:appcompat-v7
library in your build.gradle file
I can handle this way:
select to_number(to_char(sysdate,'MI')) - to_number(to_char(*YOUR_DATA_VALUE*,'MI')),max(exp_time) from ...
Or if you want to the hour just change the MI;
select to_number(to_char(sysdate,'HH24')) - to_number(to_char(*YOUR_DATA_VALUE*,'HH24')),max(exp_time) from ...
the others don't work for me. Good luck.
If you have a hash structure like this:
Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}
Then this is how I got it to work:
params.require(:link).permit(:title, time_span: [[:start, :end]])
I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.
Because of the adds and removes in arbitrary places on the list,
I went with the LinkedList
implementation.
/* traverses tree starting with given node */
private static List<Node> traverse(Node n)
{
return traverse(Arrays.asList(n));
}
/* traverses tree starting with given nodes */
private static List<Node> traverse(List<Node> nodes)
{
List<Node> open = new LinkedList<Node>(nodes);
List<Node> visited = new LinkedList<Node>();
ListIterator<Node> it = open.listIterator();
while (it.hasNext() || it.hasPrevious())
{
Node unvisited;
if (it.hasNext())
unvisited = it.next();
else
unvisited = it.previous();
it.remove();
List<Node> children = getChildren(unvisited);
for (Node child : children)
it.add(child);
visited.add(unvisited);
}
return visited;
}
private static List<Node> getChildren(Node n)
{
List<Node> children = asList(n.getChildNodes());
Iterator<Node> it = children.iterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
private static List<Node> asList(NodeList nodes)
{
List<Node> list = new ArrayList<Node>(nodes.getLength());
for (int i = 0, l = nodes.getLength(); i < l; i++)
list.add(nodes.item(i));
return list;
}
declare @date date=getdate()
declare @st_date date,@end_dt date
set @st_date=convert(varchar(5),year(@date))+'-'+convert(varchar(5),month(@date))+'-01'
set @end_dt=DATEADD(day,-1, DATEADD(month,1,@st_date))
---------**************--------------
select @st_date as [START DATE],@end_dt AS [END DATE]
You ignore case when you treat the data, not when you retrieve/store it. If you want to store everything in lowercase use String#toLowerCase, in uppercase use String#toUpperCase.
Then when you have to actually treat it, you may use out of the bow methods, like String#equalsIgnoreCase(java.lang.String). If nothing exists in the Java API that fulfill your needs, then you'll have to write your own logic.
Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:
^[a-zA-Z ._-]*$
If you use the case-insensitive modifier, you can shorten this to
^[a-z ._-]*$
Note that the space is significant (it is just a character like any other).
Run it like this on the command line:
java -jar /path/to/your/jar/jarFile.jar
There are always weird issues with browser support of getElementById, try using the following instead:
// document.getElementsBySelector are part of the prototype.js library available at http://api.prototypejs.org/dom/Element/prototype/getElementsBySelector/
function disbtn(e) {
if ( someCondition == true ) {
document.getElementsBySelector("#btn1")[0].setAttribute("disabled", "disabled");
} else {
document.getElementsBySelector("#btn1")[0].removeAttribute("disabled");
}
}
Alternatively, embrace jQuery where you could simply do this:
function disbtn(e) {
if ( someCondition == true ) {
$("#btn1").attr("disabled", "disabled");
} else {
$("#btn1").removeAttr("disabled");
}
}
Use codecs module's open() to read file:
import codecs
with codecs.open(file_name, 'r', encoding='utf-8', errors='ignore') as fdata:
I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:
$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
$availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
$date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
Start-Sleep -s 2
}
This produces the following output:
2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)
You can hit Ctrl+C
to abort the loop.
So, you can connect to any Windows machine with this command:
Enter-PSSession -ComputerName MyServerName -Credential MyUserName
...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.
In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.
The application has to be both compiled and linked with -g
option. I.e. you need to put -g
in both CPPFLAGS
and LDFLAGS
.
This may seem like a shot in the dark but make sure PHP has been complied with OpenSSL if SMTP requires SSL.
To check use phpinfo()
Hope it helps!
The below code helps me to return a JSON object for JavaScript on the front end
My template code
template_file.json
{
"name": "{{name}}"
}
Python backed code
def download_json(request):
print("Downloading JSON")
# Response render a template as JSON object
return HttpResponse(render_to_response("template_file.json",dict(name="Alex Vera")),content_type="application/json")
File url.py
url(r'^download_as_json/$', views.download_json, name='download_json-url')
jQuery code for the front end
$.ajax({
url:'{% url 'download_json-url' %}'
}).done(function(data){
console.log('json ', data);
console.log('Name', data.name);
alert('hello ' + data.name);
});
What do you mean by "the proper size"? MATLAB figures are like vector graphics, so you can basically choose the size you want on your plot.
You can set the size of the paper and the position of the figure with the function set.
Example:
plot(epx(1:5));
set(gcf, 'PaperPosition', [0 0 5 5]); %Position plot at left hand corner with width 5 and height 5.
set(gcf, 'PaperSize', [5 5]); %Set the paper to have width 5 and height 5.
saveas(gcf, 'test', 'pdf') %Save figure
The above code will remove most of the borders, but not all. This is because the left-hand corner ([0 0]
in the position vector) is not the "true" left-hand corner. To remove more of the borders, you can adjust the PaperPosition
and PaperSize
vectors.
Example:
plot(exp(1:5))
set(gcf, 'PaperPosition', [-0.5 -0.25 6 5.5]); %Position the plot further to the left and down. Extend the plot to fill entire paper.
set(gcf, 'PaperSize', [5 5]); %Keep the same paper size
saveas(gcf, 'test', 'pdf')
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
Previous answer can be shortened and be more readable.
$('#commentForm').submit(function () {
$(this).append($.map(params, function (param) {
return $('<input>', {
type: 'hidden',
name: param.name,
value: param.value
})
}))
});
Angular 6 updated code for getting previous url as string.
import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';
export class AppComponent implements OnInit {
constructor (
public router: Router
) {
}
ngOnInit() {
this.router.events
.pipe(filter((e: any) => e instanceof RoutesRecognized),
pairwise()
).subscribe((e: any) => {
console.log(e[0].urlAfterRedirects); // previous url
});
}
For cases where the data element is inside the label like in this example:
<label for="subscription">Subscription period
<select id='subscription' name='subscription'>
<option></option>
<option>1 year</option>
<option>2 years</option>
<option>3 years</option>
</select>
</label>
all the previous answers will give an unexpected result:
"Subscription period 1 year 2 years 3 years "
While the expected result would be:
"Subscription period"
So, the correct solution will be like this:
const label = document.getElementById('yourLableId');
const labelText = Array.prototype.filter
.call(label.childNodes, x => x.nodeName === "#text")
.map(x => x.textContent)
.join(" ")
.trim();
I know this is a fairly old thread, but thought I might put in my two cents for those who find it useful.
The script (apologies about the uncreative method names):
window.Listener = {
_Active: [],
remove: function(attached, on, callback, capture){
for(var i = 0; i < this._Active.length; i++){
var current = this._Active[i];
if(current[0] === attached && current[1] === on && current[2] === callback){
attached.removeEventListener(on, callback, (capture || false));
return this._Active.splice(i, 1);
}
}
}, removeAtIndex(i){
if(this._Active[i]){
var remove = this._Active[i];
var attached = remove[0], on = remove[1], callback = remove[2];
attached.removeEventListener(on, callback, false);
return this._Active.splice(i, 1);
}
}, purge: function(){
for(var i = 0; i < this._Active.length; i++){
var current = this._Active[i];
current[0].removeEventListener(current[1], current[2]);
this._Active.splice(i, 1);
}
}, declare: function(attached, on, callback, capture){
attached.addEventListener(on, callback, (capture || false));
if(this._Active.push([attached, on, callback])){
return this._Active.length - 1;
}
}
};
And you can use it like so:
// declare a new onclick listener attached to the document
var clickListener = Listener.declare(document, "click" function(e){
// on click, remove the listener and log the clicked element
console.log(e.target);
Listener.removeAtIndex(clickListener);
});
// completely remove all active listeners
// (at least, ones declared via the Listener object)
Listener.purge();
// works exactly like removeEventListener
Listener.remove(element, on, callback);
If you are using Android then you can use android.util.Base64
class.
Encode:
passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );
Decode:
passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );
A simple and fast single line solution.
Note: I see that someone (not @unutbu) changed the referenced answer so that it no longer uses vars()['Foo']
— so the primary point of my post no longer applies.
FWIW, here's what I meant about @unutbu's answer only working with locally defined classes — and that using eval()
instead of vars()
would make it work with any accessible class, not only those defined in the current scope.
For those who dislike using eval()
, a way is also shown to avoid it.
First here's a concrete example demonstrating the potential problem with using vars()
:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
# unutbu's approach
def all_subclasses(cls):
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in all_subclasses(s)]
print(all_subclasses(vars()['Foo'])) # Fine because Foo is in scope
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
def func(): # won't work because Foo class is not locally defined
print(all_subclasses(vars()['Foo']))
try:
func() # not OK because Foo is not local to func()
except Exception as e:
print('calling func() raised exception: {!r}'.format(e))
# -> calling func() raised exception: KeyError('Foo',)
print(all_subclasses(eval('Foo'))) # OK
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
# using eval('xxx') instead of vars()['xxx']
def func2():
print(all_subclasses(eval('Foo')))
func2() # Works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
This could be improved by moving the eval('ClassName')
down into the function defined, which makes using it easier without loss of the additional generality gained by using eval()
which unlike vars()
is not context-sensitive:
# easier to use version
def all_subclasses2(classname):
direct_subclasses = eval(classname).__subclasses__()
return direct_subclasses + [g for s in direct_subclasses
for g in all_subclasses2(s.__name__)]
# pass 'xxx' instead of eval('xxx')
def func_ez():
print(all_subclasses2('Foo')) # simpler
func_ez()
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
Lastly, it's possible, and perhaps even important in some cases, to avoid using eval()
for security reasons, so here's a version without it:
def get_all_subclasses(cls):
""" Generator of all a class's subclasses. """
try:
for subclass in cls.__subclasses__():
yield subclass
for subclass in get_all_subclasses(subclass):
yield subclass
except TypeError:
return
def all_subclasses3(classname):
for cls in get_all_subclasses(object): # object is base of all new-style classes.
if cls.__name__.split('.')[-1] == classname:
break
else:
raise ValueError('class %s not found' % classname)
direct_subclasses = cls.__subclasses__()
return direct_subclasses + [g for s in direct_subclasses
for g in all_subclasses3(s.__name__)]
# no eval('xxx')
def func3():
print(all_subclasses3('Foo'))
func3() # Also works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
Go to Project location in Specified Folder
C:\Angular6\sample>
Here you can type the command
C:\Angular6\sample>ng g c users
Here g means generate , c means component ,users is the component name
it will generate the 4 files
users.component.html,
users.component.spec.ts,
users.component.ts,
users.component.css
Also u can switch AppPool to Integrated mode. Thnx to Michael Bianchi (https://stackoverflow.com/a/7956546/1143515), I only want to underline that.
Start Android Studios with more heap memory:
export JAVA_OPTS="-Xms6144m -Xmx6144m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"
open -a /Applications/Android\ Studio.app
I think you're looking for this:
elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)
result_list = [elements[i] for i in indices]
If you want this for a Single Class, you can use the PropertyNamingStrategy with the @JsonNaming, something like this:
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public static class Request {
String businessName;
String businessLegalName;
}
Will serialize to:
{
"business_name" : "",
"business_legal_name" : ""
}
Since Jackson 2.7
the LowerCaseWithUnderscoresStrategy
in deprecated in favor of SnakeCaseStrategy
, so you should use:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static class Request {
String businessName;
String businessLegalName;
}
Yes; copy the string to a char array, sort the char array, then copy that back into a string.
static string SortString(string input)
{
char[] characters = input.ToArray();
Array.Sort(characters);
return new string(characters);
}
On windows Eclipse installer app writes also below admin user directory. And when I started the same eclipse as normal (another) user, it could not find admin users ecplise directory. That directory is in eclipse.ini file. (This installer has made for neon eclipse.)
It was RAM problem for me.
I was having the same problem even on a server with 12 CPU cores and 32 GB RAM. I researched more and tried to free up RAM. Here is the command I used on Ubuntu 14.04 to free up RAM:
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
And, it fixed everything. I have set it under cron to run every hour.
crontab -e
0 * * * * bash /root/ram.sh;
And, you can use this command to check how much free RAM available:
free -h
And, you will get something like this:
total used free shared buffers cached
Mem: 31G 12G 18G 59M 1.9G 973M
-/+ buffers/cache: 9.9G 21G
Swap: 8.0G 368M 7.6G
Here's my effort to give a more complete answer (building on @john's answer).
The initial issue I encountered was changing the width and height of a canvas node (using styles), resulted in the contents just being "zoomed" or "shrunk." This was not the desired effect.
So, say you want to draw two rectangles of arbitrary size in a canvas that is 100px by 100px.
<canvas width="100" height="100"></canvas>
To ensure that the rectangles will not exceed the size of the canvas and therefore not be visible, you need to ensure that the canvas is big enough.
var $canvas = $('canvas'),
oldCanvas,
context = $canvas[0].getContext('2d');
function drawRects(x, y, width, height)
{
if (($canvas.width() < x+width) || $canvas.height() < y+height)
{
oldCanvas = $canvas[0].toDataURL("image/png")
$canvas[0].width = x+width;
$canvas[0].height = y+height;
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
context.drawImage(img, 0, 0);
};
}
context.strokeRect(x, y, width, height);
}
drawRects(5,5, 10, 10);
drawRects(15,15, 20, 20);
drawRects(35,35, 40, 40);
drawRects(75, 75, 80, 80);
Finally, here's the jsfiddle for this: http://jsfiddle.net/Rka6D/4/ .
from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
You can use AppendDataBoundItems=true
to easily add:
<asp:DropDownList ID="drpList" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="" Value="" />
</asp:DropDownList>
I'd use standard javascript:
for (var m in myMap){
for (var i=0;i<myMap[m].length;i++){
... do something with myMap[m][i] ...
}
}
Note the different ways of treating objects and arrays.
Any attribute that starts with data-
is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel
and other attributes for purposes other than their original intended purposes (rel
was often used to hold data for things like advanced tooltips).
In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).
html5doctor has a good article on the data- attribute.
Cycle 2 is another example of extensive use of the data- attribute.
from __future__ import with_statement
try:
with open( "a.txt" ) as f :
print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
print 'oops'
If you want different handling for errors from the open call vs the working code you could do:
try:
f = open('foo.txt')
except IOError:
print('error')
else:
with f:
print f.readlines()
You can use split:
'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
You can just use [string intValue]
or [string floatValue]
or [string doubleValue]
etc
You can also use NSNumberFormatter
class:
Sure, just pass a string value for that timestamp column in the format: '2011-05-16 15:36:38'
(you can also append a timezone there, like 'PST'
). PostgreSQL will automatically convert the string to a timestamp. See http://www.postgresql.org/docs/9.0/static/datatype-datetime.html#DATATYPE-DATETIME-INPUT
If you have a seeder in your database, run php artisan migrate:fresh --seed
Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-
var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}
What you are looking for is called Geocoding.
Google provides a Geocoding Web Service which should do what you're looking for. You will be able to do geocoding on your server.
JSON Example:
http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
XML Example:
http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
Edit:
Please note that this is now a deprecated method and you must provide your own Google API key to access this data.
You can use a simple regex like this:
public static string StripHTML(string input)
{
return Regex.Replace(input, "<.*?>", String.Empty);
}
Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)
Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?
This works the best for me:
Sometimes it's the simple answers that are the best ;+)
You can use JavaScript to do this, with onClick method. This maybe helps CSS3 transition click event
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
Not numpy but scipy provides exactly the shift functionality you want,
import numpy as np
from scipy.ndimage.interpolation import shift
xs = np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
shift(xs, 3, cval=np.NaN)
where default is to bring in a constant value from outside the array with value cval
, set here to nan
. This gives the desired output,
array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])
and the negative shift works similarly,
shift(xs, -3, cval=np.NaN)
Provides output
array([ 3., 4., 5., 6., 7., 8., 9., nan, nan, nan])
Another option is
if (myString?.trim()) {
...
}
In my opinion the shortest and easiest solution would be:
int length , n;
printf("Enter a number: ");
scanf("%d", &n);
length = 0;
while (n > 0) {
n = n / 10;
length++;
}
printf("Length of the number: %d", length);
mysqlcheck -r -f -uroot -p --use_frm db_name
will normally do the trick
Press ctrl + E followed by S key to remove the lines in Visual Studio 10
It is called an interface. Many OO languages have this feature. You might want to read through the php explanation here: http://de2.php.net/interface
I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).
To disable just edit csf.conf and disable SMTP_BLOCK like so:
###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"
I just ran the command with sudo:
sudo pip install numpy
Bear in mind that you will be asked for the user's password. This was tested on macOS High Sierra (10.13)
In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.
I restarted my Jupyter kernel and the error disappeared.
For those struggling through this using macOS, first install all the tools:
brew install tree findutils rename
Then when needed to rename, make an alias for GNU find (gfind) as find. Then run the code of @Michel Krelin:
alias find=gfind
find . -depth -name '* *' \
| while IFS= read -r f ; do mv -i "$f" "$(dirname "$f")/$(basename "$f"|tr ' ' _)" ; done
near the end of the parser function you missed a '}'
I find that no one mentions this difference:
__getattribute__
has a default implementation, but __getattr__
does not.
class A:
pass
a = A()
a.__getattr__ # error
a.__getattribute__ # return a method-wrapper
This has a clear meaning: since __getattribute__
has a default implementation, while __getattr__
not, clearly python encourages users to implement __getattr__
.
We can set java.util.Date time part to 00:00:00 By using LocalDate class of Java 8/Joda-datetime api:
Date datewithTime = new Date() ; // ex: Sat Apr 21 01:30:44 IST 2018
LocalDate localDate = LocalDate.fromDateFields(datewithTime);
Date datewithoutTime = localDate.toDate(); // Sat Apr 21 00:00:00 IST 2018
For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml
file. NetBeans can do so automatically.
That is, within the tomcat-users.xml
, which you can find in ${CATALINA_HOME}/conf
, or ${CATALINA_BASE}/conf
,
script-manager
roleExample, change
<user password="tomcat" roles="manager,admin" username="tomcat"/>
To
<user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
manager-script
role is declaredAdd
<role rolename="manager-script"/>
Actually the netbeans online-help incorrectly states:
Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the
tomcat-base-path/conf/tomcat-users.xml
file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to thebase-dir
directory.) The admin user entry in thetomcat-users.xml
file looks similar to the following:<user username="idea" password="woiehh" roles="manager"/>
The role should be manager-script
, and not manager
.
For a more complete tomcat-users.xml
file:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<role rolename="manager-gui"/>
<user password="tomcat" roles="manager-script" username="tomcat"/>
<user password="pass" roles="manager-gui" username="me"/>
</tomcat-users>
There is another nice posting on why am I getting the deployment error?
Use this tool (hosted here for free) to convert your curl command to equivalent Python requests code:
Example: This,
curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --compressed
Gets converted neatly to:
import requests
cookies = {
'SESSID': 'ABCDEF',
}
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Origin': 'https://www.example.com',
'Accept-Encoding': 'gzip, deflate, br',
}
data = 'Pathfinder'
response = requests.post('https://www.example.com/', headers=headers, cookies=cookies, data=data)
From jQuery's website
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
Python >= 3.5 alternative: unpack into a list literal [*newdict]
New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:
>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]
Unpacking with *
works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.
Adding .keys()
i.e [*newdict.keys()]
might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).
The *iterable
syntax is similar to doing list(iterable)
and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable
could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.
Though equivalent to list(newdict)
with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:
%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop
%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop
%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop
with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).
In a similar fashion, you can create tuples and sets of dictionary keys:
>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}
beware of the trailing comma in the tuple case!
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
public AbstractType New
{
get
{
return (AbstractType) Activator.CreateInstance(GetType());
}
}
On Linux, in order to relax access to the document root, you should edit the following file:
/etc/httpd/conf/httpd.conf
And depending on what directory level you want to relax access to, you have to change the directive
AllowOverride None
to
AllowOverride All
So, assuming you want to allow access to files on the /var/www/html directory, you should change the following lines from:
<Directory "/var/www/html">
AllowOverride None
</Directory>
to
<Directory "/var/www/html">
AllowOverride All
</Directory>
From the Intel Instructions
"The SDK Manager will download the installer to the "extras" directory, under the main SDK directory. Even though the SDK manager says "Installed" it actually means that the Intel HAXM executable was downloaded. You will still need to run the installer from the "extras" directory to finish installation.
Extract the installer inside the "extras" directory and follow the installation instructions for your platform."
Here you go:
date +%Y%m%d%H%M%S
As man date
says near the top, you can use the date
command like this:
date [OPTION]... [+FORMAT]
That is, you can give it a format parameter, starting with a +
.
You can probably guess the meaning of the formatting symbols I used:
%Y
is for year%m
is for month%d
is for dayYou can find this, and other formatting symbols in man date
.
You can use numpy.shape
.
import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])
Result:
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.shape(x)
(3, 2)
First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
I've tryed much to clear focus of an edit text. clearfocus() and focusable and other things never worked for me. So I came up with the idea of letting a fake edittext gain focus:
<LinearLayout
...
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
...
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--here comes your stuff-->
</LinearLayout>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fake"
android:textSize="1sp"/>
</LinearLayout>
then in your java code:
View view = Activity.this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
fake.requestFocus();
}
it will hide the keyboard and remove the focus of any edittext that has it. and also as you see the fake edittext is out of screen and can't be seen
Your status-codes are also a collection, so use Contains
:
var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
or in query syntax:
var filteredOrders = from order in orders.Order
where allowedStatus.Contains(order.StatusCode)
select order;
Ravi, for 4.0.1-rc.1:
<option>
elements inside <select>
.$element.val(yourarray).trigger("change");
after select2
init function.HTML:
<select name="Tags" id="Tags" class="form-control input-lg select2" multiple="multiple">
<option value="1">tag 1</option>
<option value="2">tag 2</option>
<option value="3">tag 3</option>
</select>
JS:
var $tagsControl = $("#Tags").select2({
ajax: {
url: '/Tags/Search',
dataType: 'json',
delay: 250,
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
},
cache: false
},
minimumInputLength: 2,
maximumSelectionLength: 6
});
var data = [];
var tags = $("#Tags option").each(function () {
data.push($(this).val());
});
$tagsControl.val(data).trigger("change");
This issue was reported but it still opened. https://github.com/select2/select2/issues/3116#issuecomment-146568753
As of Select2 4.x, it always returns an array, even for non-multi select lists.
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
For Select2 3.x and lower
Single select:
var data = $('your-original-element').select2('data');
if(data) {
alert(data.text);
}
Note that when there is no selection, the variable 'data' will be null.
Multi select:
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
alert(data[1].text);
alert(data[1].id);
From the 3.x docs:
data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.
data method invoked on a single-select with an unset value will return null, while a data method invoked on an empty multi-select will return [].
From the wampserver 3.x onwards, changing the listening port number of Apache does not require any particular Apache skills (http.conf, virtualhost,...), you just have to click button - assuming you're running Windows OS! :
NB: For alternative port: check official IANA Service Name and Transport Protocol Port Number Registry
I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)
int a = srand(time(NULL))
arr[i] = a;
Should be
arr[i] = rand();
And put srand(time(NULL))
somewhere at the very beginning of your program.
On Windows 64bits it´s works:
Copy and Past this command
cmake -G "MinGW Makefiles" -D CMAKE_CXX_COMPILER=mingw32-g++.exe -D WITH_IPP=OFF MAKE_MAKE_PROGRAM=mingw32-make.exe ..\
Execute this command mingw32-make
Execute this command mingw32-make install
DONE
After searching and trying multiple non working options to get my select default option working. I find a clean solution at: http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
<select class="ajg-stereo-fader-input-name ajg-select-left" ng-options="option.name for option in selectOptions" ng-model="inputLeft"></select>
<select class="ajg-stereo-fader-input-name ajg-select-right" ng-options="option.name for option in selectOptions" ng-model="inputRight"></select>
scope.inputLeft = scope.selectOptions[0];
scope.inputRight = scope.selectOptions[1];
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
This error can also be caused by leaving out inject when initializing a service/factory or whatever. For example, it can be thrown by doing this:
var service;
beforeEach(function(_TestService_) {
service = _TestService_;
});
To fix it just wrap the function with inject to properly retrieve the service:
var service;
beforeEach(inject(function(_TestService_) {
service = _TestService_;
}));
The problem is probably somewhere else. Try this code for example:
Sub test()
origNum = "006260006"
creditOrDebit = "D"
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
MsgBox "OK"
End If
End Sub
And you will see that your Or
works as expected. Are you sure that your ElseIf
statement is executed (it will not be executed if any of the if/elseif before is true)?
In the HTML which you have shared:
<div id="a">This is some
<div id="b">text</div>
</div>
The text This is some
is within a text node. To depict the text node in a structured way:
<div id="a">
This is some
<div id="b">text</div>
</div>
To extract and print the text This is some
from the text node using Selenium's python client you have 2 ways as follows:
Using splitlines()
: You can identify the parent element i.e. <div id="a">
, extract the innerHTML
and then use splitlines()
as follows:
using xpath:
print(driver.find_element_by_xpath("//div[@id='a']").get_attribute("innerHTML").splitlines()[0])
using xpath:
print(driver.find_element_by_css_selector("div#a").get_attribute("innerHTML").splitlines()[0])
Using execute_script()
: You can also use the execute_script()
method which can synchronously execute JavaScript in the current window/frame as follows:
using xpath and firstChild:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
using xpath and childNodes[n]:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].childNodes[1].textContent;', parent_element).strip())
Select [insert your fields here]
from tablename
where signin = (select max(signin) from tablename where ID = 1)
For a period I had to extract the Media ID myself quite frequently, so I wrote my own script (very likely it's based on some of the examples here). Together with other small scripts I used frequently, I started to upload them on www.findinstaid.com for my own quick access.
I added the option to enter a username to get the media ID of the 12 most recent posts, or to enter a URL to get the media ID of a specific post.
If it's convenient, everyone can use the link (I don't have any adds or any other monetary interests in the website - I only have a referral link on the 'Audit' tab to www.auditninja.io which I do also own, but also on this site, there are no adds or monetary interests - just hobby projects).
In C, to pass by reference you use the address-of operator &
which should be used against a variable, but in your case, since you have used the pointer variable p
, you do not need to prefix it with the address-of operator. It would have been true if you used &i
as the parameter: f(&i)
.
You can also add this, to dereference p
and see how that value matches i
:
printf("p=%d \n",*p);
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
There is a new charting library in town: JChartlib JChartLib http://freshmeat.net/projects/jchartlib
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :
#include "../libProject/libHeader.h"
).There's a difference between pausing a thread and stopping/killing it. If stopping for you mean killing the thread, then a restart simply means creating a new thread and launching.
There are methods for killing threads from a different thread (e.g., your spawner), but they are unsafe in general. It might be safer if your thread constantly checks some flag to see if it should continue (I assume there is some loop in your thread), and have the external "controller" change the state of that flag.
You can see a little more in: http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
May I ask why you want to kill the thread and restart it? Why not just have it wait until its services are needed again? Java has synchronization mechanisms exactly for that purpose. The thread will be sleeping until the controller notifies it to continue executing.
Try this:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
should be
$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
Two answers, both valid, depending on how sloppy you like to be:
1) No, it's not currently possible to inject audio into a phone conversation.
2) Yes, it's possible. It's also an ugly, ugly kludge. Turn on the hands free function of your phone. Create a media player, set the media source, set the volume to 1.0f (highest) and call player.start()
. If the microphone and speakers on the phone are of reasonable quality, the other party to the call will hear the music. He or she will also continue to hear anything you say, as well as ambient and other sounds in your immediate vicinity.
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();
Your CSV file might have variable number of columns and read_csv
inferred the number of columns from the first few rows. Two ways to solve it in this case:
1) Change the CSV file to have a dummy first line with max number of columns (and specify header=[0]
)
2) Or use names = list(range(0,N))
where N is the max number of columns.
Don't. Just catch the FileNotFoundException.
The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:
Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.
Using git show $REV:$FILE
as it was already pointed out by others is probably the right answer. I'm posting another answer because when I tried this method, I sometimes got the following error from git:
fatal: path 'link/foo' exists on disk, but not in 'HEAD'
The problem occurs when parts of the path to the file are a symbolic link. In those cases, the git show $REV:$FILE
method will not work. Steps to reproduce:
$ git init .
$ mkdir test
$ echo hello > test/foo
$ ln -s test link
$ git add .
$ git commit -m "initial commit"
$ cat link/foo
hello
$ git show HEAD:link/foo
fatal: path 'link/foo' exists on disk, but not in 'HEAD'
The problem is, that utilities like realpath
don't help here, because the symlink might not exist in the current commit anymore. I don't know about a good general solution. In my case, I knew that the symlink could only exist in the first component of the path, so I solved the problem by using the git show $REV:$FILE
method twice. This works, because when git show $REV:$FILE
is used on a symlink, then its target gets printed:
$ git show HEAD:link
test
Whereas with directories, the command will output a header, followed by the directory content:
$ git show HEAD:test
tree HEAD:test
foo
So in my case, I just checked the output of the first call to git show $REV:$FILE
and if it was only a single line, then I replaced the first component of my path with the result to resolve the symlink through git.
You are importing the module datetime, which doesn't have a strptime
function.
That module does have a datetime
object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime
object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime
method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
I stuck with the same issue. I have found easiest solution which I like to share.
1) Create new branch with your changes.
git checkout -b mybranch
2) (Optional) Push new branch code on remote server.
git push origin mybranch
3) Checkout back to master branch.
git checkout master
4) Reset master branch code with remote server and remove local commit.
git reset --hard origin/master
Try simply to reset last commit using --soft
flag
git reset --soft HEAD~1
Note :
For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"
simple do id:("12345") OR id:("7890") .... and so on
Try this if you have array and add objects to it.
$product_details = array();
foreach ($products_in_store as $key => $objects) {
$product_details[$key] = new stdClass(); //the magic
$product_details[$key]->product_id = $objects->id;
//see new object member created on the fly without warning.
}
This sends ARRAY of Objects for later use~!
jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)
var singleAjax = function singleAjax_constructor(url, params) {
// remember last jQuery's get request
if (this.lastInstance) {
this.lastInstance.abort(); // triggers .always() and .fail()
this.lastInstance = false;
}
// how to use Deferred : http://api.jquery.com/category/deferred-object/
var $def = new $.Deferred();
// pass the deferrer's request handlers into the get response handlers
this.lastInstance = $.get(url, params)
.fail($def.reject) // triggers .always() and .fail()
.success($def.resolve); // triggers .always() and .done()
// return the deferrer's "control object", the promise object
return $def.promise();
}
// initiate first call
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// second call kills first one
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// here you might use .always() .fail() .success() etc.
Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution.
Using componentWillReceiveProps
I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.
@propTypes =
element: React.PropTypes.shape({
version: React.PropTypes.number
params:
React.PropTypes.shape(
url: React.PropTypes.string.isRequired
filename: React.PropTypes.string.isRequired
title: React.PropTypes.string.isRequired
ext: React.PropTypes.string.isRequired
).isRequired
}).isRequired
componentWillReceiveProps: (nextProps) ->
element = ReactDOM.findDOMNode(this)
audio = element.querySelector('audio')
source = audio.querySelector('source')
# When the url changes, we refresh the component manually so it reloads the loaded file
if nextProps.element.params?.filename? and
nextProps.element.params.url isnt @props.element.params.url
source.src = nextProps.element.params.url
audio.load()
I had to do it this way, because even a change of state or a force redraw didn't work.
Simplest is to class-ify all of the divs:
div.rounded {
background: #CFFEB6 url('tr.gif') no-repeat top right;
}
div.rounded div.br {
background: url('br.gif') no-repeat bottom right;
}
div.rounded div.br div.bl {
background: url('bl.gif') no-repeat bottom left;
}
div.rounded div.br div.bl div.inner {
padding: 10px;
}
.button {
border: 1px solid #999;
background:#eeeeee url('');
text-align:center;
}
.button:hover {
background-color:#c4e2f2;
}
And then use:
<div class='round'><div class='br'><div class='bl'><div class='inner'>
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>
I solved this issue by install adb package. I'm using Ubuntu.
sudo apt install adb
I think this will help to you.
You could use Levenshtein distance to calculate the difference between two strings. http://en.wikipedia.org/wiki/Levenshtein_distance
There are also two different utilities called both "JarScan" that do exactly what you are asking for: JarScan (inetfeedback.com) and JarScan (java.net)
In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
@Override
public void setFocusable(boolean b) {
super.setFocusable(b);
}
And by adding this to your constructor:
setFocusable(true);
Or, if you are calling the function from a parent class/container:
JComponent childComponent = new JComponent();
childComponent.setFocusable(true);
And then doing all the KeyListener stuff mentioned by others.
No there's not and developers still don't know why google doesn't pay attention to this request!
As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!
UPDATE user_account student, (
SELECT teacher.education_facility_id as teacherid
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
) teach SET student.student_education_facility_id= teach.teacherid WHERE student.user_type = 'ROLE_STUDENT';
This is explained in the official Bootstrap 3 release docs:
Steps to disable responsive views
To disable responsive features, follow these steps. See it in action in the modified template below.
- Remove (or just don't add) the viewport
<meta>
mentioned in the CSS docs- Remove the max-width on the .container for all grid tiers with max-width: none !important; and set a regular width like width: 970px;. Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important with media queries or some selector-fu.
- If using navbars, undo all the navbar collapsing and expanding behavior (this is too much to show here, so peep the example).
- For grid layouts, make use of .col-xs-* classes in addition to or in place of the medium/large ones. Don't worry, the extra-small device grid scales up to all resolutions, so you're set there.
You'll still need Respond.js for IE8 (since our media queries are still there and need to be picked up). This just disables the "mobile site" of Bootstrap.
See also the example on GetBootstrap.com/examples/non-responsive/
Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.
<?php
$file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */
$pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);/* Name of the Image File*/
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
/* Adding image name _thumb for thumbnail image */
$file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
break;
case 'image/gif':
$img = imagecreatefromgif($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/gif');
break;
default: die();
}
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
?>
Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN
:
ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]
Note: unlike the sp_defaultdb
solution user and database names are provided without quotes. Brackets are needed if name had special chars (most common example will be domain user which is domain\username
and won't work without brackets).
just give elem.fadeOut(10).fadeIn(10);
Adding to what @dardisco mentioned about mefa::rep.data.frame()
, it's very flexible.
You can either repeat each row N times:
rep(df, each=N)
or repeat the entire dataframe N times (think: like when you recycle a vectorized argument)
rep(df, times=N)
Two thumbs up for mefa
! I had never heard of it until now and I had to write manual code to do this.
Try with javascript function like this
Html:
<a href="javascript:void(0)" onclick="open_win()">Target</a>
Javascript:
<script>
function open_win()
{
window.open("https://www.google.co.in/");
}
</script>
In a new ASP.Net 5 MVC project in a controller action you can still do this.Context
and this.Context.Request
It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.
public IActionResult About()
{
ViewBag.Message = "Your application description page.";
var schema = this.Context.Request.Scheme;
return View();
}
Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext
I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:
If you wish to print as you have specified then:
scala> def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]
scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)
scala> println(manOf(x))
scala.collection.immutable.List[Int]
If you are in repl mode then
scala> :type List(1,2,3)
List[Int]
Or if you just wish to know what the class type then as @monkjack explains "string".getClass
might solve the purpose
Please note that one should define a Handler
and a Runnable
in class scope, so that it is created once.removeCallbacks(Runnable)
works correctly unless one defines them multiple times. Please look at following examples for better understanding:
Incorrect way :
public class FooActivity extends Activity {
private void handleSomething(){
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
doIt();
}
};
if(shouldIDoIt){
//doIt() works after 3 seconds.
handler.postDelayed(runnable, 3000);
} else {
handler.removeCallbacks(runnable);
}
}
public void onClick(View v){
handleSomething();
}
}
If you call onClick(..)
method, you never stop doIt()
method calling before it call. Because each time creates new Handler
and new Runnable
instances. In this way, you lost necessary references which belong to handler and runnable instances.
Correct way :
public class FooActivity extends Activity {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
doIt();
}
};
private void handleSomething(){
if(shouldIDoIt){
//doIt() works after 3 seconds.
handler.postDelayed(runnable, 3000);
} else {
handler.removeCallbacks(runnable);
}
}
public void onClick(View v){
handleSomething();
}
}
In this way, you don't lost actual references and removeCallbacks(runnable)
works successfully.
Key sentence is that 'define them as global in your Activity
or Fragment
what you use'.
Testing this Javascript:
var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];
var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
sum += arr[i];
}
alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );
Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12
Instead, use ( ## + ## + ... + ##).toFixed(5) )
In IE 9, toFixed
works very well.
A supplementarily handy (but trivial) tip for installing older version of packages from source.
First, if you call "install.packages", it always installs the latest package from repo. If you want to install the older version of packages, say for compatibility, you can call install.packages("url_to_source", repo=NULL, type="source"). For example:
install.packages("http://cran.r-project.org/src/contrib/Archive/RNetLogo/RNetLogo_0.9-6.tar.gz", repo=NULL, type="source")
Without manually downloading packages to the local disk and switching to the command line or installing from local disk, I found it is very convenient and simplify the call (one-step).
Plus: you can use this trick with devtools library's dev_mode, in order to manage different versions of packages:
Reference: doc devtools
I use the len
function. It's much faster than empty
. len(df.index)
is even faster.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))
def empty(df):
return df.empty
def lenz(df):
return len(df) == 0
def lenzi(df):
return len(df.index) == 0
'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)
10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop
len on index seems to be faster
'''
(reposting this answer)
You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types
package main
import "fmt"
import "encoding/binary"
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
data := binary.BigEndian.Uint64(mySlice)
fmt.Println(data)
}
This function checks for other types of whitespace, not just space (tab, carriage return, etc.)
import some from 'lodash/fp/some'
const whitespaceCharacters = [' ', ' ',
'\b', '\t', '\n', '\v', '\f', '\r', `\"`, `\'`, `\\`,
'\u0008', '\u0009', '\u000A', '\u000B', '\u000C',
'\u000D', '\u0020','\u0022', '\u0027', '\u005C',
'\u00A0', '\u2028', '\u2029', '\uFEFF']
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
console.log(hasWhitespace('a')); // a, false
console.log(hasWhitespace(' ')); // space, true
console.log(hasWhitespace(' ')); // tab, true
console.log(hasWhitespace('\r')); // carriage return, true
If you don't want to use Lodash, then here is a simple some
implementation with 2 s
:
const ssome = (predicate, list) =>
{
const len = list.length;
for(const i = 0; i<len; i++)
{
if(predicate(list[i]) === true) {
return true;
}
}
return false;
};
Then just replace some
with ssome
.
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
For those in Node, use:
const { some } = require('lodash/fp');
Using explicit parameters, it would be:
$msbuild = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
start-Process -FilePath $msbuild -ArgumentList '/v:q','/nologo'
EDIT: quotes.
Most of the answers for this question can not helped me in 2020.
This notification from download site of Oracle may be the reason:
Important Oracle JDK License Update
The Oracle JDK License has changed for releases starting April 16, 2019.
I try to google a little bit and those tutorials below helped me a lot.
Remove completely the previous version of JVM installed on your PC.
sudo update-alternatives --remove-all java
sudo update-alternatives --remove-all javac
sudo update-alternatives --remove-all javaws
# /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
sudo rm -rf /usr/lib/jvm/jdk1.7.0
Check to see whether java is uninstalled or not
java -version
1.8.0_251
. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.cd /usr/lib/jvm
sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
sudo gedit /etc/environment
:/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
update-alternatives --list java
update-alternatives --list javac
The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):
<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
<TextBlock Text="Click here for popup!"/>
</ToggleButton>
<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
<Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
<CheckBox Content="This is a popup"/>
</Border>
</Popup>
"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:
public class BoolInverter : MarkupExtension, IValueConverter
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
return !(bool)value;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert(value, targetType, parameter, culture);
}
}
...which shows the handy technique of combining IValueConverter and MarkupExtension in one.
I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":
PreviewMouseDown += (s, e) =>
{
if (Popup.IsOpen)
{
Point p = e.GetPosition(Popup.Child);
if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
!IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
Popup.IsOpen = false;
}
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) =>
num >= lo && num <= hi;
You can Try using :- git ls-files -s
$ echo | mutt -a syslogs.tar.gz [email protected]
But it uses mutt, not mail (or mailx).
Stop stomping on round
somewhere else by binding an int
to it.
The icon file is added to your project as a content file.
SELECT id FROM a -- returns 1,4,2,3
UNION
SELECT id FROM b -- returns 2,1
order by 2,1
the solution from millhouse is not working anymore with recent version of mockito
This solution work with java 8 and mockito 2.2.9
where ArgumentMatcher
is an instanceof org.mockito.ArgumentMatcher
public class ClassOrSubclassMatcher<T> implements ArgumentMatcher<Class<T>> {
private final Class<T> targetClass;
public ClassOrSubclassMatcher(Class<T> targetClass) {
this.targetClass = targetClass;
}
@Override
public boolean matches(Class<T> obj) {
if (obj != null) {
if (obj instanceof Class) {
return targetClass.isAssignableFrom( obj);
}
}
return false;
}
}
And the use
when(a.method(ArgumentMatchers.argThat(new ClassOrSubclassMatcher<>(A.class)))).thenReturn(b);
If the Path is omitted the file will be saved automaticaly in the current directory. Try something like this:
ActiveWorkbook.SaveAs "Filename.xslx"
Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.
In Bootstrap 4 one should use the text-center
class to align inline-blocks.
NOTE: text-align:center;
defined in a custom class you apply to your parent element will work regardless of the Bootstrap version you are using. And that's exactly what .text-center
applies.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col text-center">_x000D_
<button class="btn btn-default">Centered button</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If the content to be centered is block or flex (not inline-
), one could use flexbox to center it:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">_x000D_
_x000D_
<div class="d-flex justify-content-center">_x000D_
<button class="btn btn-default">Centered button</button>_x000D_
</div>
_x000D_
... which applies display: flex; justify-content: center
to parent.
Note: don't use .row.justify-content-center
instead of .d-flex.justify-content-center
, as .row
applies negative margins on certain responsiveness intervals, which results into unexpected horizontal scrollbars (unless .row
is a direct child of .container
, which applies lateral padding to counteract the negative margin, on the correct responsiveness intervals). If you must use .row
, for whatever reason, override its margin and padding with .m-0.p-0
, in which case you end up with pretty much the same styles as .d-flex
.
Important note: The second solution is problematic when the centered content (the button) exceeds the width of the parent (.d-flex
) especially when the parent has viewport width, specifically because it makes it impossible to horizontally scroll to the start of the content (left-most).
So don't use it when the content to be centered could become wider than the available parent width and all content should be accessible.
in my case this fixed the problem:
sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev
as explained here
**
**
Below is the ansible play i used to remove the file when the file exists in the OS end.
- name: find out /etc/init.d/splunk file exists or not'
stat:
path: /etc/init.d/splunk
register: splunkresult
tags:
- always
- name: 'Remove splunk from init.d file if splunk already running'
file:
path: /etc/init.d/splunk
state: absent
when: splunkresult.stat.exists == true
ignore_errors: yes
tags:
- always
I have used play condition as like below
when: splunkresult.stat.exists == true --> Remove the file
you can give true/false based on your requirement
when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true
This worked for me.
ssh-agent /bin/sh
ssh-add /path/to/your/key
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
First Div
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
Second Div
</div>
</div>
This does the trick.
You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2
in Sheet 1 A2 and =Sheet2!B2
in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.
This would be better if your unique items change also, then all you would do is sort and be done.
You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.
Putting that into an Extension method to make it easier to work with.
using System;
using System.Xml;
using System.Xml.Linq;
namespace MyTest
{
internal class Program
{
private static void Main(string[] args)
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");
var xDocument = xmlDocument.ToXDocument();
var newXmlDocument = xDocument.ToXmlDocument();
Console.ReadLine();
}
}
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using(var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
}
}
Sources:
To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.
I found a way:
This for JavaScript:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
This for a PHP file which isn't your PHP file, but another, which path is written in url
variable of JS function callPHP
, and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
So, your PHP code remain equals except return values, which will be echoed:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
I suggest you to remember that jQuery is required:
Download it from Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or from Microsoft CDN: "I prefer Google! :)"
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster! The choice is to you!
Now you finished! I just tell you how to use callPHP
function. This is the JavaScript to call PHP:
//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
It worked for me:
CGFloat boldTextFontSize = 17.0f;
myLabel.text = [NSString stringWithFormat:@"%@ 2012/10/14 %@",@"Updated:",@"21:59 PM"];
NSRange range1 = [myLabel.text rangeOfString:@"Updated:"];
NSRange range2 = [myLabel.text rangeOfString:@"21:59 PM"];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:myLabel.text];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
range:range2];
myLabel.attributedText = attributedText;
For Swift version: See Here
You can do it using a regex :
/(http:\/\/)?(www)[^\/]+\//i
does it fit ?
You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']").each(function(){ ...
or
$("input:checkbox[name='ProductCode']").each(function(){ ...
It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName
method which will be used to select elements and be much faster than selecting by the name
attribute
If you already have a datetime object my_dt
you can change it to UTC with:
datetime.datetime.utcfromtimestamp(my_dt.timestamp())
according jdk source code from javasourcecode.org, HashSet use HashMap as its inside implementation, the code about put method of HashSet is below :
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
The rule is firstly check the hash, then check the reference and then call equals method of the object will be putted in.
PDFBox contains tools for text extraction.
iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.
iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.
You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:
sudo chmod 777 markers.xml
You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.
OP asked about running from node
not from mocha
. This is a very common use case, see Using Mocha Programatically
This is what injected describe and it into my tests.
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
I tried tdd
like in the docs, but that didn't work, bdd worked though.
A "BEFORE-INSERT"-trigger is the only way to realize same-table updates on an insert, and is only possible from MySQL 5.5+. However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case. Therefore the following example code which would set a previously-calculated surrogate key value based on the auto-increment value id
will compile, but not actually work since NEW.id will always be 0:
create table products(id int not null auto_increment, surrogatekey varchar(10), description text);
create trigger trgProductSurrogatekey before insert on product
for each row set NEW.surrogatekey =
(select surrogatekey from surrogatekeys where id = NEW.id);
I've found this way to create dataframe by raw without matrix.
With automatic column name
df<-data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
)
With column name
df<-setNames(
data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
),
c("col1","col2","col3")
)
Here's what worked for me with a similar list of strings in Notepad++ without any macros or anything else:
Click Edit -> Blank Operations -> EOL to space [All the items should now be in a single line separated by a 'space']
Select any 'space' and do a Replace All (by ',')
The h1 tags unfortunately do not receive the onmouseout events.
The simple Javascript snippet below will work for all elements and uses only 1 mouse event.
Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
This can also be done in pure CSS by adding the hover selector css property to the h1 tag.
This is the example given for multiple constructors in Programming in HTML5 with JavaScript and CSS3 - Exam Ref.
function Book() {
//just creates an empty book.
}
function Book(title, length, author) {
this.title = title;
this.Length = length;
this.author = author;
}
Book.prototype = {
ISBN: "",
Length: -1,
genre: "",
covering: "",
author: "",
currentPage: 0,
title: "",
flipTo: function FlipToAPage(pNum) {
this.currentPage = pNum;
},
turnPageForward: function turnForward() {
this.flipTo(this.currentPage++);
},
turnPageBackward: function turnBackward() {
this.flipTo(this.currentPage--);
}
};
var books = new Array(new Book(), new Book("First Edition", 350, "Random"));
If you have too many installers to find what you are looking for easily, here is some powershell to provide a filter and narrow it down a little by display name.
$filter = "*core*sdk*"; (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | % { $path = "Registry::$_"; Get-ItemProperty $path } | Where-Object { $_.DisplayName -like $filter } | Select-Object -Property DisplayName, PsChildName
A sample code that works for me on Windows:
import requests
with open('pic1.jpg', 'wb') as handle:
response = requests.get(pic_url, stream=True)
if not response.ok:
print response
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
If you do it in a migration then you could probably do it like this:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
Your annotations look fine. Here are the things to check:
make sure the annotation is javax.persistence.Entity
, and not org.hibernate.annotations.Entity
. The former makes the entity detectable. The latter is just an addition.
if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic
entity
make sure you don't have multiple ScopeTopic
classes in different packages, and you've imported the wrong one.
Is it absolutely necessary to work on several bugs at once? And by "at once," I mean "having files edited for multiple bugs at the same time." Because unless you absolutely need that, I'd only work on one bug at a time in your environment. That way you can use local branches & rebase, which I find far easier than managing a complex stash/stage.
Let's say master is at commit B. Now work on bug #1.
git checkout -b bug1
Now you're on branch bug1. Make some changes, commit, wait for code review. This is local, so you're not affecting anyone else, and it should be easy enough to make a patch from git diffs.
A-B < master
\
C < bug1
Now you're working on bug2. Go back to master with git checkout master
. Make a new branch, git checkout -b bug2
. Make changes, commit, wait for code review.
D < bug2
/
A-B < master
\
C < bug1
Let's pretend that someone else commits E & F on master while you're waiting on review.
D < bug2
/
A-B-E-F < master
\
C < bug1
When your code has been approved, you can rebase it on to master with the following steps:
git checkout bug1
git rebase master
git checkout master
git merge bug1
This will result in the following:
D < bug2
/
A-B-E-F-C' < master, bug1
Then you can push, delete your local bug1 branch, and off you go. One bug at a time in your workspace, but with using local branches your repository can handle multiple bugs. And this avoids a complicated stage/stash dance.
Answer to ctote's question in the comments:
Well, you can go back to stashing for each bug, and only work with one bug at a time. Atleast that saves you the staging issue. But having tried this, I personally find it troublesome. Stashes are a bit messy in a git log graph. And more importantly, if you screw something up you can't revert. If you have a dirty working directory and you pop a stash, you can't "undo" that pop. It's much harder to screw up already existing commits.
So git rebase -i
.
When you rebase one branch onto another, you can do it interactively (the -i flag). When you do this, you have the option to pick what you want to do with each commit. Pro Git is an awesome book which is also online in HTML format, and has a nice section on rebasing & squashing:
http://git-scm.com/book/ch6-4.html
I'll steal their example verbatim for convenience. Pretend you have the following commit history, and you want to rebase & squash bug1 onto master:
F < bug2
/
A-B-G-H < master
\
C-D-E < bug1
Here's what you will see when you type git rebase -i master bug1
pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file
#
# Commands:
# p, pick = use commit
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
To squash all commits of a branch down into a single commit, keep the first commit as "pick" and replace all subsequent "pick" entries with "squash" or simply "s". You will get the opportunity to change the commit message, too.
pick f7f3f6d changed my name a bit
s 310154e updated README formatting and added blame
s a5f4a0d added cat-file
#
# Commands:
# p, pick = use commit
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
So yeah, squashing is a bit of a pain, but I would still recommend it over heavy use of stashes.
It depends on the context.
final
class or method, the C# equivalent is sealed
.final
field, the C# equivalent is readonly
.final
local variable or method parameter, there's no direct C# equivalent.