For people who have no experience in building websites (like me) I tried a lot, only to find out that I hadn't used the .php
extension, but the .html
extension.
You also can use graceful restart the apache server with service apache2 reload
or apachectl -k graceful
.
As the apache doc says:
The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.
write .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle
.
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Gradle 1.7+, Android gradle plugin 0.6.+ are required.
Note, that only try with resources require minSdkVersion
19. Other features works on previous platforms.
I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.
Since you need to match content without including it in the result (must
match name="
but it's not part of the desired result) some form of
zero-width matching or group capturing is required. This can be done
easily with the following tools:
With Perl you could use the n
option to loop line by line and print
the content of a capturing group if it matches:
perl -ne 'print "$1\n" if /name="(.*?)"/' filename
If you have an improved version of grep, such as GNU grep, you may have
the -P
option available. This option will enable Perl-like regex,
allowing you to use \K
which is a shorthand lookbehind. It will reset
the match position, so anything before it is zero-width.
grep -Po 'name="\K.*?(?=")' filename
The o
option makes grep print only the matched text, instead of the
whole line.
Another way is to use a text editor directly. With Vim, one of the
various ways of accomplishing this would be to delete lines without
name=
and then extract the content from the resulting lines:
:v/.*name="\v([^"]+).*/d|%s//\1
If you don't have access to these tools, for some reason, something similar could be achieved with standard grep. However, without the look around it will require some cleanup later:
grep -o 'name="[^"]*"' filename
In all of the commands above the results will be sent to stdout
. It's
important to remember that you can always save them by piping it to a
file by appending:
> result
to the end of the command.
From the documentation I found this
JObject o = new JObject(
new JProperty("Name", "John Smith"),
new JProperty("BirthDate", new DateTime(1983, 3, 20))
);
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
Console.WriteLine(p.Name);
The class definition for Person
should be compatible to the following:
class Person {
public string Name { get; internal set; }
public DateTime BirthDate { get; internal set; }
}
Edit
If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.
If you want to use the --prefix
or -p
arguments, but want to avoid having to use the environment's full path to activate it, you need to edit the .condarc
config file before you create the environment.
The .condarc
file is in the home directory; C:\Users\<user>
on Windows. Edit the values under the envs_dirs
key to include the custom path for your environment. Assuming the custom path is D:\envs
, the file should end up looking something like this:
ssl_verify: true
channels:
- defaults
envs_dirs:
- C:\Users\<user>\Anaconda3\envs
- D:\envs
Then, when you create a new environment on that path, its name will appear along with the path when you run conda env list
, and you should be able to activate it using only the name, and not the full path.
In summary, if you edit .condarc
to include D:\envs
, and then run conda env create -p D:\envs\myenv python=x.x
, then activate myenv
(or source activate myenv
on Linux) should work.
Hope that helps!
P.S. I stumbled upon this through trial and error. I think what happens is when you edit the envs_dirs
key, conda updates ~\.conda\environments.txt
to include the environments found in all the directories specified under the envs_dirs
, so they can be accessed without using absolute paths.
Here's an example that you could use :
var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
dddd : Full day Name
Do : day of the Month
MMMM : Full Month name
YYYY : 4 digits Year
For more informations :
If you're still facing the issue even after replacing doGet()
with doPost()
and changing the form method="post"
. Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!
For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html
Around 4gb/hr is quite common.
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
To anyone who is still interested in this question: If: 1-decodeByteArray returns null 2-Base64.decode throws bad-base64 Exception
Here is the solution: -You should consider the value sent to you from API is Base64 Encoded and should be decoded first in order to cast it to a Bitmap object! -Take a look at your Base64 encoded String, If it starts with
data:image/jpg;base64
The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:
final String encodedString = "data:image/jpg;base64, ....";
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",") + 1);
Now the pureBase64Encoded object is ready to be decoded:
final byte[] decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT);
Now just simply use the line below to turn this into a Bitmap Object! :
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
Or if you're using the great library Glide:
Glide.with(CaptchaFragment.this).load(decodedBytes).crossFade().fitCenter().into(mCatpchaImageView);
This should do the job! It wasted one day on this and came up to this solution!
Note: If you are still getting bad-base64 error consider other Base64.decode flags like Base64.URL_SAFE and so on
Very late answer, but you can simply use:
import time
today = time.strftime("%Y-%m-%d")
# 2021-02-18
__getitem__
can be used to implement "lazy" dict
subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.
As a simple example, suppose you have two lists, keys
and values
, whereby {k:v for k,v in zip(keys, values)}
is the dictionary that you need, which must be made lazy for speed or efficiency purposes:
class LazyDict(dict):
def __init__(self, keys, values):
self.keys = keys
self.values = values
super().__init__()
def __getitem__(self, key):
if key not in self:
try:
i = self.keys.index(key)
self.__setitem__(self.keys.pop(i), self.values.pop(i))
except ValueError, IndexError:
raise KeyError("No such key-value pair!!")
return super().__getitem__(key)
Usage:
>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])
You could provide your function with the object and its attribute. Next, do what you need to do inside the function. Finally, assign the value returned in the promise to the right place in your object. Here's an example:
let myFunction = function (vm, feed) {
getFeed().then( data => {
vm[feed] = data
})
}
myFunction(vm, "feed")
You can also write a self-invoking function if you want.
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
Add it in database migrations, that way everyone gets it as they update. Handle all of your logic in the ruby/rails code, so you never have to mess with explicit ID settings.
For a three dimensional array you could try:
for c in array.transpose(1, 0, 2):
do_stuff(c)
See the docs on how array.transpose
works. Basically you are specifying which dimension to shift. In this case we are shifting the second dimension (e.g. columns) to the first dimension.
Perhaps not relevant if you're looking to do this ONLY using ansible. But it's much easier for me to have a function in my .bash_profile
and then run _check_machine host1 host2
function _check_machine() {
echo 'hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,'
hostlist=$1
for h in `echo $hostlist | sed 's/ /\n/g'`;
do
echo $h | grep -qE '[a-zA-Z]'
[ $? -ne 0 ] && h=plabb$h
echo -n $h,
ssh root@$h 'grep "^physical id" /proc/cpuinfo | sort -u | wc -l; grep "^cpu cores" /proc/cpuinfo |sort -u | awk "{print \$4}"; awk "{print \$2/1024/1024; exit 0}" /proc/meminfo; /usr/sbin/dmidecode | grep "Product Name"; cat /etc/redhat-release; /etc/facter/bios_facts.sh;' | sed 's/Red at Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | sed 's/Red Hat Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | tr "\n" ","
echo ''
done
}
E.g.
$ _machine_info '10 20 1036'
hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,
plabb10,2,4,47.1629,G6,5.11 (Tikanga),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb20,2,4,47.1229,G6,6.6 (Santiago),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb1036,2,12,189.12,Gen8,6.6 (Santiago),Custom,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
$
Needless to say function won't work for you as it is. You need to update it appropriately.
That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g.
field1=value1&field1=value2&field2=value3
).[4][5]
Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.
foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]
The request.getParameter("foo")
will also work on it, but it'll return only the first value.
String foo = request.getParameter("foo"); // value1
And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces []
in order to trigger the language to return an array of values instead of a single value.
foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true
In case you still use foo=value1&foo=value2&foo=value3
, then it'll return only the first value.
$foo = $_GET["foo"]; // value1
echo is_array($foo); // false
Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3
to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.
String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]
Edited: Kindly note that whereBetween('date',$start_date,$end_date)
is inclusive of the first date.
Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.
Instead of constantly generating project metadata via import->maven command, you can generate your project metadata once and the place it in your git repository along with the rest of your source code. After than, using import->git command will import a proper maven-enabled project, assuming you have maven tools installed.
Make sure to place into the source control system all files in project dir that start with '.' such as .classpath and .project along with the entire contents of the .settings directory.
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
CSS is designed to describe the presentation of documents. It has a few features for changing that presentation in reaction to user interaction (primarily :hover
for indicating that you are now pointing at something interactive).
Making something draggable isn't a simple matter of presentation. It is firmly in the territory of interactivity logic, which is handled by JavaScript.
What you want is not achievable.
Function overloading is done when you want to have the same function with different parameters
void Print(string s);//Print string
void Print(int i);//Print integer
Function overriding is done to give a different meaning to the function in the base class
class Stream//A stream of bytes
{
public virtual void Read();//read bytes
}
class FileStream:Stream//derived class
{
public override void Read();//read bytes from a file
}
class NetworkStream:Stream//derived class
{
public override void Read();//read bytes from a network
}
I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,
myApp.directive('scrollOnClick', function() {
return {
restrict: 'A',
link: function(scope, $elm, attrs) {
var idToScroll = attrs.href;
$elm.on('click', function(event) {
event.preventDefault();
var $target;
if (idToScroll) {
$target = $(idToScroll);
} else {
$target = $elm;
}
$("body").animate({scrollTop: $target.offset().top}, "slow");
return false;
});
}
}
});
>>> for i, s in enumerate(S):
One of the major changes it seems is that with Android Studio the test application is integrated into the application project.
I'm not sure if this helps your specific problem, but I found a guide on making tests with a Gradle project. Android Gradle user Guide
Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES
in your case
forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"
the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("somParam", "someValue")
.build();
Request request = new Request.Builder()
.url(BASE_URL + route)
.post(requestBody)
.build();
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
Check out http://www.asciitable.com/
Look at the Hx
, (Hex) column; 2C
maps to ,
Any unusual encoding can be checked this way
+----+-----+----+-----+----+-----+----+-----+
| Hx | Chr | Hx | Chr | Hx | Chr | Hx | Chr |
+----+-----+----+-----+----+-----+----+-----+
| 00 | NUL | 20 | SPC | 40 | @ | 60 | ` |
| 01 | SOH | 21 | ! | 41 | A | 61 | a |
| 02 | STX | 22 | " | 42 | B | 62 | b |
| 03 | ETX | 23 | # | 43 | C | 63 | c |
| 04 | EOT | 24 | $ | 44 | D | 64 | d |
| 05 | ENQ | 25 | % | 45 | E | 65 | e |
| 06 | ACK | 26 | & | 46 | F | 66 | f |
| 07 | BEL | 27 | ' | 47 | G | 67 | g |
| 08 | BS | 28 | ( | 48 | H | 68 | h |
| 09 | TAB | 29 | ) | 49 | I | 69 | i |
| 0A | LF | 2A | * | 4A | J | 6A | j |
| 0B | VT | 2B | + | 4B | K | 6B | k |
| 0C | FF | 2C | , | 4C | L | 6C | l |
| 0D | CR | 2D | - | 4D | M | 6D | m |
| 0E | SO | 2E | . | 4E | N | 6E | n |
| 0F | SI | 2F | / | 4F | O | 6F | o |
| 10 | DLE | 30 | 0 | 50 | P | 70 | p |
| 11 | DC1 | 31 | 1 | 51 | Q | 71 | q |
| 12 | DC2 | 32 | 2 | 52 | R | 72 | r |
| 13 | DC3 | 33 | 3 | 53 | S | 73 | s |
| 14 | DC4 | 34 | 4 | 54 | T | 74 | t |
| 15 | NAK | 35 | 5 | 55 | U | 75 | u |
| 16 | SYN | 36 | 6 | 56 | V | 76 | v |
| 17 | ETB | 37 | 7 | 57 | W | 77 | w |
| 18 | CAN | 38 | 8 | 58 | X | 78 | x |
| 19 | EM | 39 | 9 | 59 | Y | 79 | y |
| 1A | SUB | 3A | : | 5A | Z | 7A | z |
| 1B | ESC | 3B | ; | 5B | [ | 7B | { |
| 1C | FS | 3C | < | 5C | \ | 7C | | |
| 1D | GS | 3D | = | 5D | ] | 7D | } |
| 1E | RS | 3E | > | 5E | ^ | 7E | ~ |
| 1F | US | 3F | ? | 5F | _ | 7F | DEL |
+----+-----+----+-----+----+-----+----+-----+
The answer to this question is saying to use display:none and display:block, but this does not help for someone who is trying to use css transitions to show and hide content using the visibility property.
This also drove me crazy, because using display kills any css transitions.
One solution is to add this to the class that's using visibility:
overflow:hidden
For this to work is does depend on the layout, but it should keep the empty content within the div it resides in.
To discover any constraints used, use the code below:
-- Set the long data type for display purposes to 500000.
SET LONG 500000
-- Define a session scope variable.
VARIABLE output CLOB
-- Query the table definition through the <code>DBMS_METADATA</code> package.
SELECT dbms_metadata.get_ddl('TABLE','[Table Described]') INTO :output FROM dual;
This essentially shows a create statement for how the referenced table is made. By knowing how the table is created, you can see all of the table constraints.
Answer taken from Michael McLaughlin's blog: http://michaelmclaughlin.info/db1/lesson-5-querying-data/lab-5-querying-data/ From his Database Design I class.
There is a extremely efficient UIImage category named NYXImagesKit. It uses vDSP, CoreImage and vImage to be as fast as possible. It has a UIImage+Rotating category that saved my day :)
one simple way SELECT '123'+ 0
the most obvious way to make foreach
a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/
I don't why you would put a<p>
element there.
But another way of removing spaces in between the paragraphs is by declaring only one paragraph
<ul>
<p><li>HI THERE</li>
<br>
<li>ME</li>
</p>
</ul>
Simply use substr for string
ex.
var str = "Hello world!";
var res = str.substr(1, str.length);
Result = ello world!
Easiest solution:
class OuterClass:
outer_var = 1
class InnerClass:
def __init__(self):
self.inner_var = OuterClass.outer_var
It requires you to be explicit, but doesn't take much effort.
this should fix the issue
brew update
brew upgrade
brew cleanup
To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).
See the following for more discussion:
How do I properly clean up Excel interop objects?
To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).
A cleaner way to handle this is to query the spreadsheet using ADO:
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName()
works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
You may want to use the Continue
statement to continue with the innermost loop.
Excerpt from PowerShell
help file:
In a script, the
continue
statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:
for
foreach
while
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
We had renamed some of our webservice project namespaces and forgot to update the website httphandlers config section with the namespace of the renamed projects.
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
Try this instead
if ( (expiryDate - DateTime.Now ).TotalDays < 30 ) {
matchFound = true;
}
With my now ageing Borland C++ Builder compiler enums can be 1,2 or 4 bytes, although it does have a flag you can flip to force it to use ints.
I guess it's compiler specific.
Here, check out this function:
function seo_friendly_url($string){
$string = str_replace(array('[\', \']'), '', $string);
$string = preg_replace('/\[.*\]/U', '', $string);
$string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
$string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
return strtolower(trim($string, '-'));
}
For Lollipop and above. create a drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="line">
<stroke android:width="1dp"
android:color="@color/onePlusRed" />
</shape>
</item>
</selector>
and use it as foreground.
android:foreground="@drawable/strike_through"
You could also use MessageFormat too
string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");
A very fast implementation of the Sieve of Atkin is Dan Bernstein's primegen. This sieve is more efficient than the Sieve of Eratosthenes. His page has some benchmark information.
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123
would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.
I have a list of guidelines at http://soaprobe.blogspot.co.uk/2012/10/soa-rest-service-naming-guideline.html which we have used in prod. Guidelines are always debatable... I think consistency is sometimes more important than getting things perfect (if there is such a thing).
Another (async) approach, using Identity's UserManager and SigninManager to reflect the change in the Identity cookie (and to optionally remove claims from db table AspNetUserClaims):
// Get User and a claims-based identity
ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var Identity = new ClaimsIdentity(User.Identity);
// Remove existing claim and replace with a new value
await UserManager.RemoveClaimAsync(user.Id, Identity.FindFirst("AccountNo"));
await UserManager.AddClaimAsync(user.Id, new Claim("AccountNo", value));
// Re-Signin User to reflect the change in the Identity cookie
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// [optional] remove claims from claims table dbo.AspNetUserClaims, if not needed
var userClaims = UserManager.GetClaims(user.Id);
if (userClaims.Any())
{
foreach (var item in userClaims)
{
UserManager.RemoveClaim(user.Id, item);
}
}
Roger's answer was very helpful.
I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with
certutil -addstore Root Demo_CA.cer
which Roger's answer didn't quite cover.
Here is a batch file that worked for me (with my .inf file, not included). It shows how to do it all from start to finish, with no GUI tools at all (except for a few password prompts).
REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.
PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64
makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature ^
-sv Demo_CA.pvk Demo_CA.cer
makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
-sky signature ^
-ic Demo_CA.cer -iv Demo_CA.pvk ^
-sv Demo_SPC.pvk Demo_SPC.cer
pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
-pfx Demo_SPC.pfx ^
-po x
inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v
signtool sign /d "description" /du "www.yoyodyne.com" ^
/f Demo_SPC.pfx ^
/p x ^
/v driver\demoprinter.cat
certutil -addstore Root Demo_CA.cer
rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
certutil -delstore Root Demo_CA
I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.
public static void main(String... args) throws IOException {
final int runs = 5 * 1000 * 1000;
final ServerSocket ss = new ServerSocket(0);
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket serverConn = ss.accept();
String line = "Hello World!\n";
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
for (int count = 0; count < runs; count++)
br.write(line);
serverConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Socket conn = new Socket("localhost", ss.getLocalPort());
long start = System.nanoTime();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
List<String> responseData = new ArrayList<String>();
while ((line = in.readLine()) != null) {
responseData.add(line);
}
long time = System.nanoTime() - start;
System.out.println("Average time to read a line was " + time / runs + " ns.");
conn.close();
ss.close();
}
prints
Average time to read a line was 158 ns.
If you want to build a StringBuilder, keeping newlines I would suggets the following approach.
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
Still prints
Average time to read a line was 159 ns.
In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.
here is a jQuery plugin I came up with:
$.fn.cycle = function(timeout){
var $all_elem = $(this)
show_cycle_elem = function(index){
if(index == $all_elem.length) return; //you can make it start-over, if you want
$all_elem.hide().eq(index).fadeIn()
setTimeout(function(){show_cycle_elem(++index)}, timeout);
}
show_cycle_elem(0);
}
You need to have a common classname for all the divs you wan to cycle, use it like this:
$("div.cycleme").cycle(5000)
Suppose that you have a string like this :
String mDate="2019-09-17T10:56:07.827088"
Now we want to change this String
format separate date and time in Java and Kotlin.
JAVA:
we have a method for extract date :
public String getDate() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mDate);
dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return
is this : 09/17/2019
And we have method for extract time :
public String getTime() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mCreatedAt);
dateFormat = new SimpleDateFormat("h:mm a", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return
is this : 10:56 AM
KOTLIN:
we have a function for extract date :
fun getDate(): String? {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val date = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
return dateFormat.format(date!!)
}
Return
is this : 09/17/2019
And we have method for extract time :
fun getTime(): String {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val time = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("h:mm a", Locale.US)
return dateFormat.format(time!!)
}
Return
is this : 10:56 AM
Several pointers:
You need to handle a return value of 0, which tells you that the remote host closed the socket.
For nonblocking sockets, you also need to check an error return value (-1) and make sure that errno isn't EINPROGRESS, which is expected.
You definitely need better error handling - you're potentially leaking the buffer pointed to by 'buffer'. Which, I noticed, you don't allocate anywhere in this code snippet.
Someone else made a good point about how your buffer isn't a null terminated C string if your read() fills the entire buffer. That is indeed a problem, and a serious one.
Your buffer size is a bit small, but should work as long as you don't try to read more than 256 bytes, or whatever you allocate for it.
If you're worried about getting into an infinite loop when the remote host sends you a malformed message (a potential denial of service attack) then you should use select() with a timeout on the socket to check for readability, and only read if data is available, and bail out if select() times out.
Something like this might work for you:
fd_set read_set;
struct timeval timeout;
timeout.tv_sec = 60; // Time out after a minute
timeout.tv_usec = 0;
FD_ZERO(&read_set);
FD_SET(socketFileDescriptor, &read_set);
int r=select(socketFileDescriptor+1, &read_set, NULL, NULL, &timeout);
if( r<0 ) {
// Handle the error
}
if( r==0 ) {
// Timeout - handle that. You could try waiting again, close the socket...
}
if( r>0 ) {
// The socket is ready for reading - call read() on it.
}
Depending on the volume of data you expect to receive, the way you scan the entire message repeatedly for the "end;" token is very inefficient. This is better done with a state machine (the states being 'e'->'n'->'d'->';') so that you only look at each incoming character once.
And seriously, you should consider finding a library to do all this for you. It's not easy getting it right.
One of recent the TFS Rocks pocasts mentioned such an organisation, may have been number 16.
Use String#trim()
method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.
For left trim:
String leftRemoved = myString.replaceAll("^\\s+", "");
For right trim:
String rightRemoved = myString.replaceAll("\\s+$", "");
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeAnother option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents
(or .Clear
). The reason you might want to use this method instead of .Delete
is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF
. This method will preserve formula references to the cleared cells.
Initializing a vector having struct, class or Union can be done this way
std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.
If you are coming here because you are using Apache commons logging with log4j and log4j isn't working as you expect then check that you actually have a log4j.jar in your run-time classpath. That one had me puzzled for a little while. I have now configured the runner in my dev environment to include -Dlog4j.debug in the Java command line so I can always see that Log4j is being initialized correctly
Try setting the width on the table itself:
<table id="ratesandcharges1" class="grid" style="width: 650px;">
You'll have to adjust the 650 by a couple pixels to account for whatever padding, margins, and borders you have.
You'll probably still have some issues though. I don't see enough horizontal space for all those columns without mangling the headers, reducing the font sizes, or some other bit of ugliness.
Depends on what you're doing.
For instance:
//bankers' rounding - midpoint goes to nearest even
GetIntPart(2.5) >> 2
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -6
or
//arithmetic rounding - midpoint goes away from zero
GetIntPart(2.5) >> 3
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -7
The default is always the former, which can be a surprise but makes very good sense.
Your explicit cast will do:
int intPart = (int)343564564.5
// intPart will be 343564564
int intPart = (int)343564565.5
// intPart will be 343564566
From the way you've worded the question it sounds like this isn't what you want - you want to floor it every time.
I would do:
Math.Floor(Math.Abs(number));
Also check the size of your decimal
- they can be quite big, so you may need to use a long
.
If you want the exact number, you can't from just the Timespan, since you need to know which months you're dealing, and whether you're dealing with a leap year, like you said.
Either go for an approximate number, or do some fidgetting with the original DateTimes
Try this one:
wget -nd -r -P /save/location/ -A jpeg,jpg,bmp,gif,png http://www.domain.com
and wait until it deletes all extra information
If you have troubles with hotkeys, try to open Key Binding Resolver Window
with Cmd + .. It will show you keys you're pressing in the realtime.
For example, Cmd + Shift + ' is actually Cmd + "
Just stumbled upon the same problem, I believe the final solution used by the author consisted in using a custom ContainerFactory:
public static Values parseJSONToMap(String msgData) {
JSONParser parser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){
@Override
public Map createObjectContainer() {
return new LinkedHashMap();
}
@Override
public List creatArrayContainer() {
return null;
}
};
try {
return (Map<String,Object>)parser.parse(msgData, containerFactory);
} catch (ParseException e) {
log.warn("Exception parsing JSON string {}", msgData, e);
}
return null;
}
Use the aggregate MAX(signin)
grouped by id. This will list the most recent signin
for each id
.
SELECT
id,
MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id
To get the whole single record, perform an INNER JOIN
against a subquery which returns only the MAX(signin)
per id.
SELECT
tbl.id,
signin,
signout
FROM tbl
INNER JOIN (
SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id
) ms ON tbl.id = ms.id AND signin = maxsign
WHERE tbl.id=1
My understanding is that adding r+
opens for both read and write (just like w+
, though as pointed out in the comment, will truncate the file). The b
just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).
You can use them jointly
Example :
public class A implements Runnable{
@Override
public void run() {
while(true){
System.out.println("Class A is running");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
}
public class Test {
public static void main(String[] args) {
Thread myThread =new Thread(new A());// 1
myThread.start();
System.out.println(" executed after thread A");//will never be reached
}
}
In java 8 you can also use a reducer, something like:
public static String join(List<String> strings, String joinStr) {
return strings.stream().reduce("", (prev, cur) -> prev += (cur + joinStr));
}
@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document
?
.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
var dumb = function (id) {
var queryResult = $document[0].getElementById(id)
var wrappedID = angular.element(queryResult);
return wrappedID;
};
Simple php script worked for me.
Export:
// add all job codes in the array
$jobs = array("job1", "job2", "job3");
foreach ($jobs as $value)
{
fwrite(STDOUT, $value. " \n") or die("Unable to open file!");
$path = "http://server1:8080/jenkins/job/".$value."/config.xml";
$myfile = fopen($value.".xml", "w");
fwrite($myfile, file_get_contents($path));
fclose($myfile);
}
Import:
<?php
// add all job codes in the array
$jobs = array("job1", "job2", "job3");
foreach ($arr as $value)
{
fwrite(STDOUT, $value. " \n") or die("Unable to open file!");
$cmd = "java -jar jenkins-cli.jar -s http://server2:8080/jenkins/ create-job ".$value." < ".$value.".xml";
echo exec($cmd);
}
You can use Split():
import java.io.*;
public class Splitting
{
public static void main(String args[])
{
String Str = new String("004-034556");
String[] SplittoArray = Str.split("-");
String string1 = SplittoArray[0];
String string2 = SplittoArray[1];
}
}
Else, you can use StringTokenizer:
import java.util.*;
public class Splitting
{
public static void main(String[] args)
{
StringTokenizer Str = new StringTokenizer("004-034556");
String string1 = Str.nextToken("-");
String string2 = Str.nextToken("-");
}
}
It's not possible using the iPhone SDK from an official standpoint. You might be able to do it using private methods, but that will be a barrier to getting onto the app store.
The only other safe solution is to create yout own page control which shpuldnt be too difficult given that the page control simply displays what page is currently shown in a scroll view.
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
You could use getopt.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int bflag = 0;
int sflag = 0;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "bs")) != -1)
switch (c)
{
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("bflag = %d, sflag = %d\n", bflag, sflag);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Replace '_' || '/' to your own need
If all you want is some very basic error checking, you could just check the length of the string.
string guidStr = "";
if( guidStr.Length == Guid.Empty.ToString().Length )
Guid g = new Guid( guidStr );
Dynamic programming problems can be solved using either bottom-up or top-down approaches.
Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.
But you can also have bottom-up and top-down approaches using recursion as shown below.
Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.
int n = 5;
fibBottomUp(1, 1, 2, n);
private int fibBottomUp(int i, int j, int count, int n) {
if (count > n) return 1;
if (count == n) return i + j;
return fibBottomUp(j, i + j, count + 1, n);
}
Top-Down: Start with the final condition and recursively get the result of its sub-problems.
int n = 5;
fibTopDown(n);
private int fibTopDown(int n) {
if (n <= 1) return 1;
return fibTopDown(n - 1) + fibTopDown(n - 2);
}
Control-C works, although depending on what the process is doing it might not take right away.
If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.
Today I came across this same issue, whilst working on rails 4, I was able to get it working by structuring my fields_for as:
<%= f.select :tag_ids, Tag.all.collect {|t| [t.name, t.id]}, {}, :multiple => true %>
Then in my controller I have my strong params as:
private
def post_params
params.require(:post).permit(:id, :title, :content, :publish, tag_ids: [])
end
All works!
I would like to add another solution to this that does not require a dummy constructor. Since dummy constructors are a bit messy and subsequently confusing. We can provide a safe constructor and by annotating the constructor arguments we allow jackson to determine the mapping between constructor parameter and field.
so the following will also work. Note the string inside the annotation must match the field name.
import com.fasterxml.jackson.annotation.JsonProperty;
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom){
//constructor Code
}
public ApplesDO(@JsonProperty("apple")String apple) {
}
}
Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:
domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ include:/\n/g' | \
tail -n+2)
for domain in $domainsToDig ; do
dig @8.8.8.8 $domain TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ ip.:/\n/g' | \
tail -n+2
done
PictureBox.Image is a property, not a method. You can set it like this:
PictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
The code by "tvanfosson" was giving me "Error executing Child Request".. I have changed the OnAuthorization like this:
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!_isAuthorized)
{
filterContext.Result = new HttpUnauthorizedResult();
}
else if (filterContext.HttpContext.User.IsInRole("Administrator") || filterContext.HttpContext.User.IsInRole("User") || filterContext.HttpContext.User.IsInRole("Manager"))
{
// is authenticated and is in one of the roles
SetCachePolicy(filterContext);
}
else
{
filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");
filterContext.Result = new RedirectResult("~/Error");
}
}
This works well and I show the TempData on error page. Thanks to "tvanfosson" for the code snippet. I am using windows authentication and _isAuthorized is nothing but HttpContext.User.Identity.IsAuthenticated...
I know that this is already answered, but for the record and for anyone with the same requeriments as me I decided to post this related answer. The code is flooded with comments to explain the code.
Save the file as getopt.sh
:
#!/bin/bash
function get_variable_name_for_option {
local OPT_DESC=${1}
local OPTION=${2}
local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*/\1/g" -e "s/.*\[\?-\(${OPTION}\).*/\1FLAG/g")
if [[ "${VAR}" == "${1}" ]]; then
echo ""
else
echo ${VAR}
fi
}
function parse_options {
local OPT_DESC=${1}
local INPUT=$(get_input_for_getopts "${OPT_DESC}")
shift
while getopts ${INPUT} OPTION ${@};
do
[ ${OPTION} == "?" ] && usage
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
done
check_for_required "${OPT_DESC}"
}
function check_for_required {
local OPT_DESC=${1}
local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
while test -n "${REQUIRED}"; do
OPTION=${REQUIRED:0:1}
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
REQUIRED=${REQUIRED:1}
done
}
function get_input_for_getopts {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_optional {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*/\1/g" -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_required {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}
function usage {
printf "Usage:\n\t%s\n" "${0} ${OPT_DESC}"
exit 10
}
Then you can use it like this:
#!/bin/bash
#
# [ and ] defines optional arguments
#
# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}
echo ${USER}
echo ${START_DATE_TIME}
I recently needed to use a generic approach. I came across with this solution:
#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
# OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
# ~$ echo get_options ${OPT_DESC}
# a:b:c
# ~$
#
# Required options
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"
# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"
function usage {
IFS="|"
printf "%s" ${0}
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "-${i:0:1} $VARNAME"
done
for i in ${OPTIONAL_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "[-${i:0:1} $VARNAME]"
done
printf "\n"
unset IFS
exit
}
# Auxiliary function that returns options characters to be passed
# into 'getopts' from a option description.
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# OPTIONS=$(get_options ${OPT_DESC})
# echo "${OPTIONS}"
#
# Output:
# "h:f:PW"
function get_options {
echo ${1} | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?/\1/g"
}
# Auxiliary function that returns all variable names separated by '|'
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# VARNAMES=$(get_values ${OPT_DESC})
# echo "${VARNAMES}"
#
# Output:
# "H_VAR|F_VAR|P_VAR|W_VAR"
function get_variables {
echo ${1} | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)/\1/g"
}
# Auxiliary function that returns the variable name based on the
# option passed by.
# Arguments:
# $1: The options description (SEE TOP)
# $2: The option which the variable name wants to be retrieved
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# H_VAR=$(get_variable_name ${OPT_DESC} "h")
# echo "${H_VAR}"
#
# Output:
# "H_VAR"
function get_variable_name {
VAR=$(echo ${1} | sed -e "s/.*${2}\:\?=>\([^|]*\).*/\1/g")
if [[ ${VAR} == ${1} ]]; then
echo ""
else
echo ${VAR}
fi
}
# Gets the required options from the required description
REQUIRED=$(get_options ${REQUIRED_DESC})
# Gets the optional options (duh) from the optional description
OPTIONAL=$(get_options ${OPTIONAL_DESC})
# or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}")
# The colon at starts instructs getopts to remain silent
while getopts ":${REQUIRED}${OPTIONAL}" OPTION
do
[[ ${OPTION} == ":" ]] && usage
VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION})
[[ -n ${VAR} ]] && eval "$VAR=${OPTARG}"
done
shift $(($OPTIND - 1))
# Checks for required options. Report an error and exits if
# required options are missing.
# Using function version ...
VARS=$(get_variables ${REQUIRED_DESC})
IFS="|"
for VARNAME in $VARS;
do
[[ -v ${VARNAME} ]] || usage
done
unset IFS
# ... or using IFS Version (no function)
OLDIFS=${IFS}
IFS="|"
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
[[ -v ${VARNAME} ]] || usage
printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}"
done
IFS=${OLDIFS}
I didn't test this roughly, so I could have some bugs in there.
It is not an issue it is because of caching...
To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products')
.
After timestamp it should be axios.get(/api/products?${Date.now()}
.
It will resolve your 304 status code.
PHP will copy the array by default. References in PHP have to be explicit.
$a = array(1,2);
$b = $a; // $b will be a different array
$c = &$a; // $c will be a reference to $a
Have a look at the android SDK system requirements Here
I'm guessing some extra RAM would help your developing experience...Also the emulator does take some time to start on even the speediest systems.
Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:
Javascript:
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";
The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):
>>> import requests
>>> response = requests.get(
... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})
If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):
>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})
Use my tool git_remote_branch (you need Ruby installed on your machine). It's built specifically to make remote branch manipulations dead easy.
Each time it does an operation on your behalf, it prints it in red at the console. Over time, they finally stick into your brain :-)
If you don't want grb to run commands on your behalf, just use the 'explain' feature. The commands will be printed to your console instead of executed for you.
Finally, all commands have aliases, to make memorization easier.
Note that this is alpha software ;-)
Here's the help when you run grb help:
git_remote_branch version 0.2.6 Usage: grb create branch_name [origin_server] grb publish branch_name [origin_server] grb rename branch_name [origin_server] grb delete branch_name [origin_server] grb track branch_name [origin_server] Notes: - If origin_server is not specified, the name 'origin' is assumed (git's default) - The rename functionality renames the current branch The explain meta-command: you can also prepend any command with the keyword 'explain'. Instead of executing the command, git_remote_branch will simply output the list of commands you need to run to accomplish that goal. Example: grb explain create grb explain create my_branch github All commands also have aliases: create: create, new delete: delete, destroy, kill, remove, rm publish: publish, remotize rename: rename, rn, mv, move track: track, follow, grab, fetch
This is a summary of the main solutions with easy-to-reproduce code:
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json") // or "text/plain"
xhr.send(JSON.stringify(data));
PHP side, you can get the data with:
print_r(json_decode(file_get_contents('php://input'), true));
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + encodeURIComponent(JSON.stringify(data)));
Note: encodeURIComponent(...)
is needed for example if the JSON contains &
character.
PHP side, you can get the data with:
print_r(json_decode($_POST['json'], true));
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString());
PHP side, you can get the data with:
print_r($_POST);
The enumerate()
function adds a counter to an iterable.
So for each element in cursor
, a tuple is produced with (counter, element)
; the for
loop binds that to row_number
and row
, respectively.
Demo:
>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
... print elem
...
foo
bar
baz
>>> for count, elem in enumerate(elements):
... print count, elem
...
0 foo
1 bar
2 baz
By default, enumerate()
starts counting at 0
but if you give it a second integer argument, it'll start from that number instead:
>>> for count, elem in enumerate(elements, 42):
... print count, elem
...
42 foo
43 bar
44 baz
If you were to re-implement enumerate()
in Python, here are two ways of achieving that; one using itertools.count()
to do the counting, the other manually counting in a generator function:
from itertools import count
def enumerate(it, start=0):
# return an iterator that adds a counter to each element of it
return zip(count(start), it)
and
def enumerate(it, start=0):
count = start
for elem in it:
yield (count, elem)
count += 1
The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ...
unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).
This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.
When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).
Consider the following code:
$dom = new DOMDocument(); //create a document
$dom->preserveWhiteSpace = false; //disable whitespace preservation
$dom->formatOutput = true; //pretty print output
$documentElement = $dom->createElement("Entry"); //create a node
$dom->appendChild ($documentElement); //append it
$message = new DOMDocument(); //create another document
$message->loadXML($messageXMLtext); //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node); //append the new node to the document Element
$dom->saveXML($dom->documentElement); //print the original document
In this context, the $dom->saveXML();
statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.
In order to achieve pretty printing for the entire $dom document, the line:
$message->preserveWhiteSpace = false;
must be included after the $message = new DOMDocument();
line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
The other answers talked about direct binding in render hence I want to add few points regarding that.
You are not recommended to bind the function directly in render or anywhere else in the component except in constructor. Because for every function binding a new function/object will be created in webpack bundle js file hence the bundle size will grow. Your component will re-render for many reasons like when you do setState, new props received, when you do this.forceUpdate()
etc. So if you directly bind your function in render it will always create a new function. Instead do function binding always in constructor and call the reference wherever required. In this way it creates new function only once because constructor gets called only once per component.
How you should do is something like below
constructor(props){
super(props);
this.state = {
value: 'random text'
}
this.handleChange = this.handleChange.bind(this);
}
handleChange (e) {
console.log('handle change called');
this.setState({value: e.target.value});
}
<input value={this.state.value} onChange={this.handleChange}/>
You can also use arrow functions but arrow functions also does create new function every time the component re-renders in certain cases. You should know about when to use arrow function and when are not suppose to. For detailed explation about when to use arrow functions check the accepted answer here
With the help of user=User.query.filter_by(username=form.username.data).first()
statement you will get the specified user in user
variable.
Now you can change the value of the new object variable like user.no_of_logins += 1
and save the changes with the session
's commit method.
Maybe you installed a pod file and you are still trying to build from the .xcodeproj
file instead of .xcworkspace
\s
matches any white-space character\S
matches any non-white-space character[^ ]
matches anything but a space character.Pick whichever is most appropriate.
Java includes a scripting language extension package starting with version 6.
See the Rhino project documentation for embedding a JavaScript interpreter in Java.
[Edit]
Here is a small example of how you can expose Java objects to your interpreted script:
public class JS {
public static void main(String args[]) throws Exception {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("stdout", System.out);
js.eval("stdout.println(Math.cos(Math.PI));");
// Prints "-1.0" to the standard output stream.
}
}
Stan Lippman talked about this here. I thought it was interesting.
Summary: Stroustrup originally used class
to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword typename
to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, class
kept its overloaded meaning.
There is a new spec called the Native File System API that allows you to do this properly like this:
const result = await window.chooseFileSystemEntries({ type: "save-file" });
There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.
Here's some more benchmarks for Docker based memcached server
versus host native memcached server
using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate
Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.
Twemperf Docker Memcached
Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0
Twemperf Centmin Mod Memcached
Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0
Here's bencmarks using memtier benchmark tool
memtier_benchmark docker Memcached
4 Threads
50 Connections per thread
10000 Requests per thread
Type Ops/sec Hits/sec Misses/sec Latency KB/sec
------------------------------------------------------------------------
Sets 16821.99 --- --- 1.12600 2271.79
Gets 168035.07 159636.00 8399.07 1.12000 23884.00
Totals 184857.06 159636.00 8399.07 1.12100 26155.79
memtier_benchmark Centmin Mod Memcached
4 Threads
50 Connections per thread
10000 Requests per thread
Type Ops/sec Hits/sec Misses/sec Latency KB/sec
------------------------------------------------------------------------
Sets 28468.13 --- --- 0.62300 3844.59
Gets 284368.51 266547.14 17821.36 0.62200 39964.31
Totals 312836.64 266547.14 17821.36 0.62200 43808.90
Here's a complete example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__APPLE__)
# define COMMON_DIGEST_FOR_OPENSSL
# include <CommonCrypto/CommonDigest.h>
# define SHA1 CC_SHA1
#else
# include <openssl/md5.h>
#endif
char *str2md5(const char *str, int length) {
int n;
MD5_CTX c;
unsigned char digest[16];
char *out = (char*)malloc(33);
MD5_Init(&c);
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
for (n = 0; n < 16; ++n) {
snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
}
return out;
}
int main(int argc, char **argv) {
char *output = str2md5("hello", strlen("hello"));
printf("%s\n", output);
free(output);
return 0;
}
the nuget package Selenium.Support
already contains an extension method to help with this. Once it is included, one liner to executer script
Driver.ExecuteJavaScript("console.clear()");
or
string result = Driver.ExecuteJavaScript<string>("console.clear()");
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
feof()
indicates if one has tried to read past the end of file. That means it has little predictive effect: if it is true, you are sure that the next input operation will fail (you aren't sure the previous one failed BTW), but if it is false, you aren't sure the next input operation will succeed. More over, input operations may fail for other reasons than the end of file (a format error for formatted input, a pure IO failure -- disk failure, network timeout -- for all input kinds), so even if you could be predictive about the end of file (and anybody who has tried to implement Ada one, which is predictive, will tell you it can complex if you need to skip spaces, and that it has undesirable effects on interactive devices -- sometimes forcing the input of the next line before starting the handling of the previous one), you would have to be able to handle a failure.
So the correct idiom in C is to loop with the IO operation success as loop condition, and then test the cause of the failure. For instance:
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence allow to handle lines longer that sizeof(line), not showed here */
...
}
if (ferror(file)) {
/* IO failure */
} else if (feof(file)) {
/* format error (not possible with fgets, but would be with fscanf) or end of file */
} else {
/* format error (not possible with fgets, but would be with fscanf) */
}
It depends on the specific use case.
If your table is static and only has a short list of values (and there is just a small chance that this would change during a lifetime of DB), I would recommend this construction:
CREATE TABLE Foo
(
FooCode VARCHAR(16), -- short code or shortcut, but with some meaning.
Name NVARCHAR(128), -- full name of entity, can be used as fallback in case when your localization for some language doesn't exist
LocalizationCode AS ('Foo.' + FooCode) -- This could be a code for your localization table...
)
Of course, when your table is not static at all, using INT as primary key is the best solution.
Use Column or Row in a Button child, Row for horizontal button, Column for vertical, and dont forget to contain it with the size you need:
Container(
width: 120.0,
height: 30.0,
child: RaisedButton(
color: Color(0XFFFF0000),
child: Row(
children: <Widget>[
Text('Play this song', style: TextStyle(color: Colors.white),),
Icon(Icons.play_arrow, color: Colors.white,),
],
),
),
),
checkout stetho and https://github.com/uPhyca/stetho-realm Video tutorial here: https://www.youtube.com/watch?v=9pFJz5VexRw
Either:
debugPrint("Path to realm file: " + realm.configuration.fileURL!.absoluteString)
Step 1: Have a constant called dev somewhere. Let's say Constant file
public class Constants {
public static var dev: Bool = true
}
Step 2: Create another class called RealmFunctions.swift
import RealmSwift
func realmAndPath() -> Realm {
if Constants.dev {
// location of my desktop
let testRealmURL = NSURL(fileURLWithPath: "/Users/#####/Desktop/TestRealm.realm")
return try! Realm(fileURL: testRealmURL)
} else {
return try! Realm()
}
}
Step 3: finally in your view controller:
let realm = realmAndPath()
thanks to Stewart Lynch for the original answer
You can get the version of the jquery by simply printing object.jquery
, the object
can be any object created by you using $
.
For example: if you have created a <div>
element as following
var divObj = $("div");
then by printing divObj.jquery
will show you the version like 1.7.1
Basically divObj
inherits all the property of $()
or jQuery()
i.e if you try to print jQuery.fn.jquery
will also print the same version like 1.7.1
You code is correct. replace items with .items as below
<script>
var n = $(".items").css("left");
if(n == -900){
$(".items span").fadeOut("slow");
}
</script>
If you do not want to destroy .idea, you can try :
Among other things, it can be used for security. If you have a "customer" table, you might want to give all of your sales people access to the name, address, zipcode, etc. fields, but not credit_card_number. You can create a view that only includes the columns they need access to and then grant them access on the view.
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
If anyone else is running into this still - I was able to track down the root cause in my application.
If you are running API-Gateway with custom Authorizers - API-Gateway will send a 401 or 403 back before it actually hits your server. By default - API-Gateway is NOT configured for CORS when returning 4xx from a custom authorizer.
Also - if you happen to be getting a status code of 0
or 1
from a request running through API Gateway, this is probably your issue.
To fix - in the API Gateway configuration - go to "Gateway Responses", expand "Default 4XX" and add a CORS configuration header there. i.e.
Access-Control-Allow-Origin: '*'
Make sure to re-deploy your gateway - and voila!
Try something like:
.create
{
margin: 0px;
padding-left: 20px;
background-image: url('yourpic.gif');
background-repeat: no-repeat;
}
logger
logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:
local7.* -/var/log/mycustomlog
and restart syslog. Then you can log like this:
logger -p local7.info "information message"
logger -p local7.err "error message"
and the messages will appear in the desired logfile with the correct log level.
Without making changes to the syslog configuration you could use logger
like this:
logger -s "foo bar" >> /var/log/mycustomlog
That would instruct logger
to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice
).
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
The correct result for me with SQL Server 2017:
USE <DATABASE>;
EXEC sp_configure 'clr enabled' ,1
GO
RECONFIGURE
GO
EXEC sp_configure 'clr enabled' -- make sure it took
GO
USE <DATABASE>
GO
EXEC sp_changedbowner 'sa'
USE <DATABASE>
GO
ALTER DATABASE <DATABASE> SET TRUSTWORTHY ON;
From An error occurred in the Microsoft .NET Framework while trying to load assembly id 65675
Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.
from numpy.polynomial import Polynomial
p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())
p
uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with
pnormal = p.convert(domain=(-1, 1))
It’s a holdover from the Netscape days:
Missing digits are treated as 0[...]. An incorrect digit is simply interpreted as 0. For example the values #F0F0F0, F0F0F0, F0F0F, #FxFxFx and FxFxFx are all the same.
It is from the blog post A little rant about Microsoft Internet Explorer's color parsing which covers it in great detail, including varying lengths of color values, etc.
If we apply the rules in turn from the blog post, we get the following:
Replace all nonvalid hexadecimal characters with 0’s:
chucknorris becomes c00c0000000
Pad out to the next total number of characters divisible by 3 (11 ? 12):
c00c 0000 0000
Split into three equal groups, with each component representing the corresponding colour component of an RGB colour:
RGB (c00c, 0000, 0000)
Truncate each of the arguments from the right down to two characters.
Which, finally, gives the following result:
RGB (c0, 00, 00) = #C00000 or RGB(192, 0, 0)
Here’s an example demonstrating the bgcolor
attribute in action, to produce this “amazing” colour swatch:
<table>
<tr>
<td bgcolor="chucknorris" cellpadding="8" width="100" align="center">chuck norris</td>
<td bgcolor="mrt" cellpadding="8" width="100" align="center" style="color:#ffffff">Mr T</td>
<td bgcolor="ninjaturtle" cellpadding="8" width="100" align="center" style="color:#ffffff">ninjaturtle</td>
</tr>
<tr>
<td bgcolor="sick" cellpadding="8" width="100" align="center">sick</td>
<td bgcolor="crap" cellpadding="8" width="100" align="center">crap</td>
<td bgcolor="grass" cellpadding="8" width="100" align="center">grass</td>
</tr>
</table>
_x000D_
This also answers the other part of the question: Why does bgcolor="chucknorr"
produce a yellow colour? Well, if we apply the rules, the string is:
c00c00000 => c00 c00 000 => c0 c0 00 [RGB(192, 192, 0)]
Which gives a light yellow gold colour. As the string starts off as 9 characters, we keep the second ‘C’ this time around, hence it ends up in the final colour value.
I originally encountered this when someone pointed out that you could do color="crap"
and, well, it comes out brown.
If ruby was installed in the following way:
./configure --prefix=/usr/local
make
sudo make install
You can uninstall it in the following way:
Check installed ruby version; lets assume 2.1.2
wget http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.bz2
bunzip ...
tar xfv ...
cd ruby-2.1.2
./configure --prefix=/usr/local
make
sudo checkinstall
# will build deb or rpm package and try to install it
After installation, you can now remove the package and it will remove the directories/files/etc.
sudo rpm -e ruby # or dpkg -P ruby (for Debian-like systems)
There might be some artifacts left:
Removing ruby ...
warning: while removing ruby, directory '/usr/local/lib/ruby/gems/2.1.0/gems' not empty so not removed.
...
Remove them manually.
I finally got this bunch of codes to work in NetBeans using Swing GUI Forms in order to center main jFrame:
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
CenteredFrame(this); // <--- Here ya go.
}
// ...
// void main() and other public method declarations here...
/// modular approach
public void CenteredFrame(javax.swing.JFrame objFrame){
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
objFrame.setLocation(iCoordX, iCoordY);
}
}
OR
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
//------>> Insert your code here to center main jFrame.
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - this.getWidth()) / 2;
int iCoordY = (objDimension.height - this.getHeight()) / 2;
this.setLocation(iCoordX, iCoordY);
//------>>
}
// ...
// void main() and other public method declarations here...
}
OR
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
this.setLocationRelativeTo(null); // <<--- plain and simple
}
// ...
// void main() and other public method declarations here...
}
/etc/my.cnf
or /etc/mysql/my.cnf
, depending on your distro.skip-grant-tables
under [mysqld]
mysql -u root -p
mysql> flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
mysql -u root -p
Action is null means that no Action in given SOAP Message (Request XML). You must set Action before SOAP call:
java.net.URL endpoint = new URL("<URL>"); //sets URL
MimeHeaders headers = message.getMimeHeaders(); // getting MIME Header
headers.addHeader("SOAPAction", "<SOAP Action>"); //add Action To Header
SOAPMessage response = soapConnection.call(<SOAPMessage>, endpoint); //then Call
soapConnection.close(); // then Close the connection
you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:
{{ users|join(', ') }}
You could alternatively use jstack (Included with JDK) to take a thread dump and write the output wherever you want. Is that not available in a unix environment?
jstack PID > outfile
I try this clipboard 0.0.4 and it works well.
https://pypi.python.org/pypi/clipboard/0.0.4
import clipboard
clipboard.copy("abc") # now the clipboard content will be string "abc"
text = clipboard.paste() # text will have the content of clipboard
Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:
package main
import (
"fmt"
"strconv"
)
func main() {
floats := []float64{1.9999, 2.0001, 2.0}
for _, f := range floats {
t := int(f)
s := fmt.Sprintf("%.0f", f)
if i, err := strconv.Atoi(s); err == nil {
fmt.Println(f, t, i)
} else {
fmt.Println(f, t, err)
}
}
}
Code on Go Playground
This may work:
expect($("#message_div").css("display")).toBe("none");
... or if you really want to use NOT IN
you can use
SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)
Just in case you want to use any of mentioned codes, be aware that array_search
returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
The above example will output:
Array
(
[0] => one
[1] => two
[2] => three
)
And that's good!
No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.
XML has only one definition for a comment:
'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
XML forbids --
in comments to maintain compatibility with SGML.
@Provider
public class BadURIExceptionMapper implements ExceptionMapper<NotFoundException> {
public Response toResponse(NotFoundException exception){
return Response.status(Response.Status.NOT_FOUND).
entity(new ErrorResponse(exception.getClass().toString(),
exception.getMessage()) ).
build();
}
}
Create above class. This will handle 404 (NotFoundException) and here in toResponse method you can give your custom response. Similarly there are ParamException etc. which you would need to map to provide customized responses.
The template it is referring to is the Html helper DisplayFor
.
DisplayFor expects to be given an expression that conforms to the rules as specified in the error message.
You are trying to pass in a method chain to be executed and it doesn't like it.
This is a perfect example of where the MVVM (Model-View-ViewModel) pattern comes in handy.
You could wrap up your Trainer
model class in another class called TrainerViewModel
that could work something like this:
class TrainerViewModel
{
private Trainer _trainer;
public string ShortDescription
{
get
{
return _trainer.Description.ToString().Substring(0, 100);
}
}
public TrainerViewModel(Trainer trainer)
{
_trainer = trainer;
}
}
You would modify your view model class to contain all the properties needed to display that data in the view, hence the name ViewModel.
Then you would modify your controller to return a TrainerViewModel
object rather than a Trainer
object and change your model type declaration in your view file to TrainerViewModel
too.
Suppose your table-size (or the number for modulo) is T = (B*C). Now if hash for your input is like (N*A*B) where N can be any integer, then your output won't be well distributed. Because every time n becomes C, 2C, 3C etc., your output will start repeating. i.e. your output will be distributed only in C positions. Note that C here is (T / HCF(table-size, hash)).
This problem can be eliminated by making HCF 1. Prime numbers are very good for that.
Another interesting thing is when T is 2^N. These will give output exactly same as all the lower N bits of input-hash. As every number can be represented powers of 2, when we will take modulo of any number with T, we will subtract all powers of 2 form number, which are >= N, hence always giving off number of specific pattern, dependent on the input. This is also a bad choice.
Similarly, T as 10^N is bad as well because of similar reasons (pattern in decimal notation of numbers instead of binary).
So, prime numbers tend to give a better distributed results, hence are good choice for table size.
(Repeating here my answer elsewhere.)
In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.
It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.
In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
To do it the GUI way, you need to go edit your login. One of its properties is the default database used for that login. You can find the list of logins under the Logins node under the Security node. Then select your login and right-click and pick Properties. Change the default database and your life will be better!
Note that someone with sysadmin privs needs to be able to login to do this or to run the query from the previous post.
rsync
include exclude pattern examples:
"*" means everything
"dir1" transfers empty directory [dir1]
"dir*" transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*" transfers files whose names start with [file]
"dir**" transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***" same as above
"dir1/*" does nothing
"dir1/**" does nothing
"dir1/***" transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...
And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir"
(its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.
If the above response by @Ilya Dyoshin didn't still retrieve, try to get the response into a String Object.
(For my self thought the error got solved by the code snippet by Ilya, the response retrieved was a failure(error) from the server.)
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
ResponseEntity<String> st = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
And Cast to the ResponseObject DTO (Json)
Gson g = new Gson();
DTO dto = g.fromJson(st.getBody(), DTO.class);
Like this:
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add("SubItem");
listView1.Items.Add(lvi);
Referring to the official Boostrap3 sticky footer example,
there is no need to add <div id="push"></div>
, and the CSS is simpler.
The CSS used in the official example is:
/* Sticky footer styles
-------------------------------------------------- */
html,
body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
/* Wrapper for page content to push down footer */
#wrap {
min-height: 100%;
height: auto;
/* Negative indent footer by its height */
margin: 0 auto -60px;
/* Pad bottom by footer height */
padding: 0 0 60px;
}
/* Set the fixed height of the footer here */
#footer {
height: 60px;
background-color: #f5f5f5;
}
and the essential HTML:
<body>
<!-- Wrap all page content here -->
<div id="wrap">
<!-- Begin page content -->
<div class="container">
</div>
</div>
<div id="footer">
<div class="container">
</div>
</div>
</body>
You can find the link for this css in the sticky-footer example's source code.
<!-- Custom styles for this template -->
<link href="sticky-footer.css" rel="stylesheet">
Full URL : http://getbootstrap.com/examples/sticky-footer/sticky-footer.css
I wanted to have tooltip only for a particular field as added below in code but you want to have tooltip on multiplent you can have an array valdidate using:
Multiple Elements haveing custom data-tooltip attribute:
1: ['key1ToHaveTooltip', `key2ToHaveTooltip'].includes(key)
2: ['key1ToHaveTooltip', 'key2ToHaveTooltip'].indexOf(key) > -1
to have tooltip attribute on more than 1 element.
<div *ngFor="let key of Keys"
[attr.data-tooltip]="key === 'IwantOnlyThisKeyToHaveTooltipAttribute'
? 'Hey! I am a tooltip on key matched'
: null">
</div>
See: How to: Attach a Database File to SQL Server Express
Login to the database via sqlcmd:
sqlcmd -S Server\Instance
And then issue the commands:
USE [master]
GO
CREATE DATABASE [database_name] ON
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.ldf' )
FOR ATTACH ;
GO
Point 1: Add require()
function calling line of code only in the app.js
file or main.js
file.
Point 2: Make sure the required package is installed by checking the pacakage.json
file. If not updated, run "npm i".
do this
sudo apt-get install php-curl
and restart server
sudo service apache2 restart
The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:
'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/save-json/',
'defaults' => array(
'controller' => 'CDB\Controller\Index',
'action' => 'save-json',
),
),
),
and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend
$this->params()->fromPost('paramname');
didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':
$content = file_get_contents('php://input');
print_r(json_decode($content));
I got my json array in the end. Hope this helps.
You can use xxd
to show a hex dump of the file, and hunt through for "0d0a" or "0a" chars.
You can use cat -v <filename>
as @warriorpostman suggests.
The answer from Randal Schwartz almost helped me all the way. I have a different username on the server, so I had to add the User keyword to my file:
Host friendly-name
HostName long.and.cumbersome.server.name
IdentityFile ~/.ssh/private_ssh_file
User username-on-remote-machine
Now you can connect using the friendly-name:
ssh friendly-name
More keywords can be found on the OpenSSH man page. NOTE: Some of the keywords listed might already be present in your /etc/ssh/ssh_config file.
WinSCp now supports S3 protocol
First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.
Make sure New site node is selected.
On the New site node, select Amazon S3 protocol.
Enter your AWS user Access key ID and Secret access key
Save your site settings using the Save button.
Login using the Login button.
Here is a quick and easy solution:
CREATE FUNCTION dbo.vaValidEmail(@EMAIL varchar(100))
RETURNS bit as
BEGIN
DECLARE @bitRetVal as Bit
IF (@EMAIL <> '' AND @EMAIL NOT LIKE '_%@__%.__%')
SET @bitRetVal = 0 -- Invalid
ELSE
SET @bitRetVal = 1 -- Valid
RETURN @bitRetVal
END
Then you can find all rows by using the function:
SELECT * FROM users WHERE dbo.vaValidEmail(email) = 0
If you are not happy with creating a function in your database, you can use the LIKE-clause directly in your query:
SELECT * FROM users WHERE email NOT LIKE '_%@__%.__%'
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
exec sp_helptext 'your_sp_name' -- don't forget the quotes
In management studio by default results come in grid view. If you would like to see it in text view go to:
Query --> Results to --> Results to Text
or CTRL + T and then Execute.
Most of these answers are either far too complicated or don't seem to work for me (e.g. System.Windows.Input doesn't seem to exist). Then I found some sample code which works fine: http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state
In case the page disappears in the future I am posting the relevant source code below:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MouseKeyboardStateTest
{
public abstract class Keyboard
{
[Flags]
private enum KeyStates
{
None = 0,
Down = 1,
Toggled = 2
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern short GetKeyState(int keyCode);
private static KeyStates GetKeyState(Keys key)
{
KeyStates state = KeyStates.None;
short retVal = GetKeyState((int)key);
//If the high-order bit is 1, the key is down
//otherwise, it is up.
if ((retVal & 0x8000) == 0x8000)
state |= KeyStates.Down;
//If the low-order bit is 1, the key is toggled.
if ((retVal & 1) == 1)
state |= KeyStates.Toggled;
return state;
}
public static bool IsKeyDown(Keys key)
{
return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
}
public static bool IsKeyToggled(Keys key)
{
return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
}
}
}
Incase their is local uncommitted changes and avoid merge conflict while pulling.
git stash save
git pull
git stash pop
This worked for me
#Mount as ReadOnly
su -c "mount -o rw,remount /system"
# Change Permission for file
su -c "chmod 777 /system/build.prop"
#Edit the file to add the property
su -c "busybox vi /system/build.prop"
# Add now
service.adb.tcp.port=5678
# Reset old permissions
su -c "chmod 644 /system/build.prop"
# Mount as readonly again once done
su -c "mount -o ro,remount /system"
Given answers are enough to deal with the problem but I want to share another way which may be introduced the new version of Spark (I am not sure about it) so given answer didn't catch it.
We can reach the column in spark statement with col("colum_name")
keyword:
from pyspark.sql.functions import col , column
changedTypedf = joindf.withColumn("show", col("show").cast("double"))
Just a few comments:
Don't set PYTHONPATH
if all you want is to get Python on the PATH
. The PYTHONPATH
environment variable tells Python where to look for modules to import. Setting it to C:\Python27\
will not accomplish anything useful, although it's probably harmless.
Modifying environment variables (including PATH
) from the "Edit System Variables" has no effect on already running processes. This means you have to re-launch cmd.exe
for the changes to work. A reboot, however, is not required.
When modifying the PATH, also add the Scripts subdirectory. Or, to put it in other words (and using the previous example): add ;C:\Python27;C:\Python27\Scripts
. This will allow you to run scripts like easy_install
, pip
, virtualenv
or sphinx
from the command line - once you install those, that is. This is about as UNIX-y as it gets for Windows. (N.B. The Scripts
subdirectory is not present after a clean install of Python, but will be created when needed.)
Don't put any additional Lib
or DLL
directory on the PATH
. There's no need, and it might do harm.
If you have installed multiple versions of Python (which isn't all that uncommon) you might be better off not putting any of them on the PATH
but instead create different shortcuts to cmd.exe
for the different versions which set the PATH
for each version. You might also be interested in PEP-397.
int scrWidth = getWindowManager().getDefaultDisplay().getWidth();
int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
You could use LINQ, but I would go with RemoveAll
method. I think that is the one that better expresses your intent.
var integers = new List<int> { 1, 2, 3, 4, 5 };
var remove = new List<int> { 1, 3, 5 };
integers.RemoveAll(i => remove.Contains(i));
There is no updated
dynamic table. There is just inserted
and deleted
. On an UPDATE
command, the old data is stored in the deleted
dynamic table, and the new values are stored in the inserted
dynamic table.
Think of an UPDATE
as a DELETE/INSERT
combination.
Your web form shouldn't have all of that markup (like the <html>
tag). Since it has a master page, you just start with the content tag. Your aspx page should look like this:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebUI._Default" MasterPageFile="~/Site1.Master" %>
<asp:content id="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
This is the body!
</asp:content>
When you're adding a new aspx page make sure to check "select master page" in the "add new item" dialog.
Specifying android:onClick
attribute results in Button
instance calling setOnClickListener
internally. Hence there is absolutely no difference.
To have clear understanding, let us see how XML onClick
attribute is handled by the framework.
When a layout file is inflated, all Views specified in it are instantiated. In this specific case, the Button
instance is created using public Button (Context context, AttributeSet attrs, int defStyle)
constructor. All of the attributes in the XML tag are read from the resource bundle and passed as AttributeSet
to the constructor.
Button
class is inherited from View
class which results in View
constructor being called, which takes care of setting the click call back handler via setOnClickListener
.
The onClick attribute defined in attrs.xml, is referred in View.java as R.styleable.View_onClick
.
Here is the code of View.java
that does most of the work for you by calling setOnClickListener
by itself.
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
As you can see, setOnClickListener
is called to register the callback, as we do in our code. Only difference is it uses Java Reflection
to invoke the callback method defined in our Activity.
Here are the reason for issues mentioned in other answers:
Java Class getMethod
is used, only functions with public access specifier are searched for. Otherwise be ready to handle IllegalAccessException
exception.getContext().getClass().getMethod()
call restricts the method search to the current context, which is Activity in case of Fragment. Hence method is searched within Activity class and not Fragment class.Java Class getMethod
searches for method which accepts View.class
as parameter.bit rate : no of bits(0 or 1 for binary signal) transmitted per second.
baud rate : no of symbols per second.
A symbol consists of 'n' number of bits.
Baud rate = (bit rate)/n
So baud rate is always less than or equal to bit rate.It is equal when signal is binary.
A fast shortcut for restarting service on Windows:
1) Press Windows Key + R
2) Type "services.msc"
3) Order by name
4) Find "PostgreSQL" service and restart it.
This works on both MacOSX and Linux:
#!/bin/bash
ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offline
Thought I'd give a full answer combining some of the possible intricacies required for completeness.
w3wp.exe
. If it's showing as w3wp*32.exe
then it's 32-bit.And if you wanted to join the table with itself (which won't happen too often):
update t1 -- just reference table alias here
set t1.somevalue = t2.somevalue
from table1 t1 -- these rows will be the targets
inner join table1 t2 -- these rows will be used as source
on .................. -- the join clause is whatever suits you
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
If you want the time as well, just go with
datetime.datetime.now().__str__()
Prints 2019-07-11 19:36:31.118766
in console for me
Just use for x in f: ...
, this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip
call because the trailing newline is already stipped.
The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline
will return an empty string, not None
. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue
makes the code ignore blank lines, which is propably a good thing anyway.
to make it work in intelliJ, you can also add
<generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>
to maven-compiler-plugin
2 + 2 = 5(*)
(for some floating-precision values of 2)
This problem frequently arises when we think of"floating point" as a way to increase precision. Then we run afoul of the "floating" part, which means there is no guarantee of which numbers can be represented.
So while we might easily be able to represent "1.0, -1.0, 0.1, -0.1" as we get to larger numbers we start to see approximations - or we should, except we often hide them by truncating the numbers for display.
As a result, we might think the computer is storing "0.003" but it may instead be storing "0.0033333333334".
What happens if you perform "0.0003 - 0.0002"? We expect .0001, but the actual values being stored might be more like "0.00033" - "0.00029" which yields "0.000004", or the closest representable value, which might be 0, or it might be "0.000006".
With current floating point math operations, it is not guaranteed that (a / b) * b == a.
#include <stdio.h>
// defeat inline optimizations of 'a / b * b' to 'a'
extern double bodge(int base, int divisor) {
return static_cast<double>(base) / static_cast<double>(divisor);
}
int main() {
int errors = 0;
for (int b = 1; b < 100; ++b) {
for (int d = 1; d < 100; ++d) {
// b / d * d ... should == b
double res = bodge(b, d) * static_cast<double>(d);
// but it doesn't always
if (res != static_cast<double>(b))
++errors;
}
}
printf("errors: %d\n", errors);
}
ideone reports 599 instances where (b * d) / d != b using just the 10,000 combinations of 1 <= b <= 100 and 1 <= d <= 100 .
The solution described in the FAQ is essentially to apply a granularity constraint - to test if (a == b +/- epsilon)
.
An alternative approach is to avoid the problem entirely by using fixed point precision or by using your desired granularity as the base unit for your storage. E.g. if you want times stored with nanosecond precision, use nanoseconds as your unit of storage.
C++11 introduced std::ratio as the basis for fixed-point conversions between different time units.
I had lot of problem with the same issue. I solved this one by
Intro *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"introVC"];
[self.tabBarController presentModalViewController : vc animated:YES];
I have the viewcontroller in my storyboard, for some reason using only [[introvc alloc] init];
did not work for me.
Instead of changing the plugin source code you can include an additional js file in the format like those in the downloads localization folder and include that one after loading the validation.js
jQuery.extend(jQuery.validator.messages, {
required: ...,
maxlength: jQuery.validator.format(...),
...
});
UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id
That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read
As for running slow, how large are the tables? You should have indexes on tobeupdated.value
and original.value
EDIT: we can also simplify the query
UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id
USING
is shorthand when both tables of a join have an identical named key
such as id
. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join
I'm doing angular 2 and typescript and I didn't realize I had a space in my arrow notation
I had .map(key = >
instead of .map(key =>
Definitely keep your eyes open for stupid syntax errors
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila. Very "fancy", three word JavaScript!
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
You might need to add -lc++
to the LDFlags
for Golang/CGo to recognize the need for the standard library.
I set up a default project and found out the following:
The problem is the combination of smartNavigation and maintainScrollPositionOnPostBack. The error only occurs when both are set to true.
In my case, the error was produced by:
<pages smartNavigation="true" maintainScrollPositionOnPostBack="true" />
Any other combination works fine.
Can anybody confirm this?
Try this:
^(.+)\/([^\/]+)$
EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex
You can push multiple elements into an array in the following way
var a = [];_x000D_
_x000D_
a.push(1, 2, 3);_x000D_
_x000D_
console.log(a);
_x000D_
The good part is we can make basic maths directly:
let nuts = 7_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h2>You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it, get ${nuts + nuts} nuts!!_x000D_
_x000D_
`
_x000D_
<div id="more"></div>
_x000D_
It became really useful in a factory function:
function nuts(it){_x000D_
return `_x000D_
You have ${it} nuts! <br>_x000D_
Cosinus of your nuts: ${Math.cos(it)} <br>_x000D_
Triple nuts: ${3 * it} <br>_x000D_
Your nuts encoded in BASE64:<br> ${btoa(it)}_x000D_
`_x000D_
}_x000D_
_x000D_
nut.oninput = (function(){_x000D_
out.innerHTML = nuts(nut.value)_x000D_
})
_x000D_
<h3>NUTS CALCULATOR_x000D_
<input type="number" id="nut">_x000D_
_x000D_
<div id="out"></div>
_x000D_