The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.
dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is
P(dBm) = 10 · log10( P(W) / 1mW )
where
P(dBm) = Power expressed in dBm P(W) = the absolute power measured in Watts mW = milliWatts log10 = log to base 10
From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.
There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.
Your actual question was "does the - sign count?"
The answer is yes, it does.
-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.
Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.
How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.
Another option is to use HttpStatus
class from the Apache commons-httpclient which provides you the various Http statuses as constants.
You can redirect stdout to nul
to hide it.
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >nul
Just add >nul
to the commands you want to hide the output from.
Here you can see all the different ways of redirecting the std streams.
To update database type following codes in PowerShell...
Update-Database -context EnrollmentAppContext
*if more than one databases exist only use this codes,otherwise not necessary..
Declarative programming is the picture, where imperative programming is instructions for painting that picture.
You're writing in a declarative style if you're "Telling it what it is", rather than describing the steps the computer should take to get to where you want it.
When you use XML to mark-up data, you're using declarative programming because you're saying "This is a person, that is a birthday, and over there is a street address".
Some examples of where declarative and imperative programming get combined for greater effect:
Windows Presentation Foundation uses declarative XML syntax to describe what a user interface looks like, and what the relationships (bindings) are between controls and underlying data structures.
Structured configuration files use declarative syntax (as simple as "key=value" pairs) to identify what a string or value of data means.
HTML marks up text with tags that describe what role each piece of text has in relation to the whole document.
${#str_var}
where str_var
is your string.
For a very specific reason Type Nullable<int>
put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):
public struct Nullable<T> where T : struct
{
...
}
Since u have the same class name against all check box, thus
$(".ads_Checkbox")
will give u all the checkboxes, and then you can iterate them using each loop like
$(".ads_Checkbox:checked").each(function(){
alert($(this).val());
});
Alternatively you can register a call back delegate which ignores the certification error:
...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...
static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}
Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.
<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
if ($matches[2] == 'M') {
$memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
} else if ($matches[2] == 'K') {
$memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
}
}
$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?
echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';
Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.
from foo import *
adds all the names without leading underscores (or only the names defined in the modules __all__
attribute) in foo
into your current module.
In the above code with from socket import *
you just want to catch timeout
as you've pulled timeout
into your current namespace.
from socket import *
pulls in the definitions of everything inside of socket
but doesn't add socket
itself.
try:
# socketstuff
except timeout:
print 'caught a timeout'
Many people consider import *
problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.
For example, consider the following three python files:
# a.py
def foo():
print "this is a's foo function"
# b.py
def foo():
print "this is b's foo function"
# yourcode.py
from a import *
from b import *
foo()
If you run yourcode.py
you'll see just the output "this is b's foo function".
For this reason I'd suggest either importing the module and using it or importing specific names from the module:
For example, your code would look like this with explicit imports:
import socket
from socket import AF_INET, SOCK_DGRAM
def main():
client_socket = socket.socket(AF_INET, SOCK_DGRAM)
client_socket.settimeout(1)
server_host = 'localhost'
server_port = 1234
while(True):
client_socket.sendto('Message', (server_host, server_port))
try:
reply, server_address_info = client_socket.recvfrom(1024)
print reply
except socket.timeout:
#more code
Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.
This route I take is one where I create functions outside the class and assign the function to my private method.
export class MyClass {
private _myPrivateFunction = someFunctionThatCanBeTested;
}
function someFunctionThatCanBeTested() {
//This Is Testable
}
Now I don't know what type of OOP rules I am breaking, but to answer the question, this is how I test private methods. I welcome anyone to advise on Pros & Cons of this.
TryGetValue is slightly faster, because FindEntry will only be called once.
How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
FYI: It's not actually catching an error.
It's calling:
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
ContainsKey is this:
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
Before using reset think about using revert so you can always go back.
https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert
On request
Source: https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert
git reset vs git revert sonic0002 2019-02-02 08:26:39
When maintaining code using version control systems such as git, it is unavoidable that we need to rollback some wrong commits either due to bugs or temp code revert. In this case, rookie developers would be very nervous because they may get lost on what they should do to rollback their changes without affecting others, but to veteran developers, this is their routine work and they can show you different ways of doing that. In this post, we will introduce two major ones used frequently by developers.
What are their differences and corresponding use cases? We will discuss them in detail below. git reset Assuming we have below few commits.
Commit A and B are working commits, but commit C and D are bad commits. Now we want to rollback to commit B and drop commit C and D. Currently HEAD is pointing to commit D 5lk4er, we just need to point HEAD to commit B a0fvf8 to achieve what we want. It's easy to use git reset command.
git reset --hard a0fvf8
After executing above command, the HEAD will point to commit B.
But now the remote origin still has HEAD point to commit D, if we directly use git push to push the changes, it will not update the remote repo, we need to add a -f option to force pushing the changes.
git push -f
The drawback of this method is that all the commits after HEAD will be gone once the reset is done. In case one day we found that some of the commits ate good ones and want to keep them, it is too late. Because of this, many companies forbid to use this method to rollback changes.
git revert The use of git revert is to create a new commit which reverts a previous commit. The HEAD will point to the new reverting commit. For the example of git reset above, what we need to do is just reverting commit D and then reverting commit C.
git revert 5lk4er
git revert 76sdeb
Now it creates two new commit D' and C',
In above example, we have only two commits to revert, so we can revert one by one. But what if there are lots of commits to revert? We can revert a range indeed.
git revert OLDER_COMMIT^..NEWER_COMMIT
This method would not have the disadvantage of git reset, it would point HEAD to newly created reverting commit and it is ok to directly push the changes to remote without using the -f option. Now let's take a look at a more difficult example. Assuming we have three commits but the bad commit is the second commit.
It's not a good idea to use git reset to rollback the commit B since we need to keep commit C as it is a good commit. Now we can revert commit C and B and then use cherry-pick to commit C again.
From above explanation, we can find out that the biggest difference between git reset and git revert is that git reset will reset the state of the branch to a previous state by dropping all the changes post the desired commit while git revert will reset to a previous state by creating new reverting commits and keep the original commits. It's recommended to use git revert instead of git reset in enterprise environment. Reference: https://kknews.cc/news/4najez2.html
Apple's Technical Q&A QA1509 shows the following simple approach:
CFDataRef CopyImagePixels(CGImageRef inImage)
{
return CGDataProviderCopyData(CGImageGetDataProvider(inImage));
}
Use CFDataGetBytePtr
to get to the actual bytes (and various CGImageGet*
methods to understand how to interpret them).
I got pretty close to what I wanted by doing something like this
cat my.json | jq '.my.prefix[] | .primary_key + ":", (.sub.prefix[] | " - " + .sub_key)' | tr -d '"'
The output of which is close enough to yaml for me to usually import it into other tools without much problem. (I am still looking for a way to basicallt export a subset of the input json)
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
There are some light and useful python packages for this purpose:
1. tabulate: https://pypi.python.org/pypi/tabulate
from tabulate import tabulate
print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Name Age
------ -----
Alice 24
Bob 19
tabulate has many options to specify headers and table format.
print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'], tablefmt='orgtbl'))
| Name | Age |
|--------+-------|
| Alice | 24 |
| Bob | 19 |
2. PrettyTable: https://pypi.python.org/pypi/PrettyTable
from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Alice', 24])
t.add_row(['Bob', 19])
print(t)
+-------+-----+
| Name | Age |
+-------+-----+
| Alice | 24 |
| Bob | 19 |
+-------+-----+
PrettyTable has options to read data from csv, html, sql database. Also you are able to select subset of data, sort table and change table styles.
3. texttable: https://pypi.python.org/pypi/texttable
from texttable import Texttable
t = Texttable()
t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
print(t.draw())
+-------+-----+
| Name | Age |
+=======+=====+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
with texttable you can control horizontal/vertical align, border style and data types.
4. termtables: https://github.com/nschloe/termtables
import termtables as tt
string = tt.to_string(
[["Alice", 24], ["Bob", 19]],
header=["Name", "Age"],
style=tt.styles.ascii_thin_double,
# alignment="ll",
# padding=(0, 1),
)
print(string)
+-------+-----+
| Name | Age |
+=======+=====+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
with texttable you can control horizontal/vertical align, border style and data types.
Other options:
df = df_try
for i in range(4):
df = df.append(df_try)
# Here, we have df_try times 5
df = df.append(df)
# Here, we have df_try times 10
You want to run:
php -m
on the command line,
or if you have access to the server configuration file open
/etc/php5/apache2/php.ini
and look at all the the extensions,
you can even enable or disable them by switching between On and Off like this
<Extension_name> = <[On | Off]>
Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:
echo CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT
I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.
It looks that in awk, string can be concatenated by printing variable next to each other:
echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal
Here is a javascript code to add users.
Start mongod
with --auth = true
Access admin database from mongo shell and pass the javascript file.
mongo admin "Filename.js"
"Filename.js"
// Adding admin user
db.addUser("admin_username", " admin_password");
// Authenticate admin user
db.auth("admin_username ", " admin_password ");
// use database code from java script
db = db.getSiblingDB("newDatabase");
// Adding newDatabase database user
db.addUser("database_username ", " database_ password ");
Now user addition is complete, we can verify accessing the database from mongo shell
Solution without need of regular expression:
string ExtractString(string s, string tag) {
// You should check for errors in real-world code, omitted for brevity
var startTag = "<" + tag + ">";
int startIndex = s.IndexOf(startTag) + startTag.Length;
int endIndex = s.IndexOf("</" + tag + ">", startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}
For Spring Boot I found this RegexCorsConfiguration
which extends the official CorsConfiguration
: https://github.com/looorent/spring-security-jwt/blob/master/src/main/java/be/looorent/security/jwt/RegexCorsConfiguration.java
BigDecimal is Oracle's arbitrary-precision numerical library. BigDecimal is part of the Java language and is useful for a variety of applications ranging from the financial to the scientific (that's where sort of am).
There's nothing wrong with using doubles for certain calculations. Suppose, however, you wanted to calculate Math.Pi * Math.Pi / 6, that is, the value of the Riemann Zeta Function for a real argument of two (a project I'm currently working on). Floating-point division presents you with a painful problem of rounding error.
BigDecimal, on the other hand, includes many options for calculating expressions to arbitrary precision. The add, multiply, and divide methods as described in the Oracle documentation below "take the place" of +, *, and / in BigDecimal Java World:
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
The compareTo method is especially useful in while and for loops.
Be careful, however, in your use of constructors for BigDecimal. The string constructor is very useful in many cases. For instance, the code
BigDecimal onethird = new BigDecimal("0.33333333333");
utilizes a string representation of 1/3 to represent that infinitely-repeating number to a specified degree of accuracy. The round-off error is most likely somewhere so deep inside the JVM that the round-off errors won't disturb most of your practical calculations. I have, from personal experience, seen round-off creep up, however. The setScale method is important in these regards, as can be seen from the Oracle documentation.
I had such problem. I reviewed Homestead.yaml file and all files and all of the settings were correct. My problem removed after the following steps.
1-If you are in
vagrant@homestead:~$
command line, type exit
command.
2- Now you must be inside Homestead folder. run this command
vagrant reload --provision
3- run vagrant ssh
Now if you type the related address in your browser it should show the Laravel page.
Try to add this at Header of your request: Accept=application/json
postman or insomnia add header
Try
link.href = 'https://...'
link.href = 'https://stackoverflow.com'
_x000D_
<a id="link" href="#">Click me</a>
_x000D_
Stop MySQL sudo service mysql stop
Make MySQL service directory. sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory. sudo chown mysql: /var/run/mysqld
Start MySQL manually, without permission checks or networking. sudo mysqld_safe --skip-grant-tables --skip-networking &
5.Log in without a password. mysql -uroot mysql
6.Update the password for the root user.
UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%'; EXIT;
Turn off MySQL. sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
Start the MySQL service normally. sudo service mysql start
For SQL Server 2005 and above use Coalesce for nulls
and I am using Cast or Convert if there are numeric values
-
declare @CodeNameString nvarchar(max)
select @CodeNameString = COALESCE(@CodeNameString + ',', '') + Cast(CodeName as varchar) from AccountCodes ORDER BY Sort
select @CodeNameString
<input type="text" name="time" data-provide="timepicker" id="time" class="form-control" placeholder="Start Time" value="" />
$('#time').timepicker({
timeFormat: 'H:i',
'scrollDefaultNow' : 'true',
'closeOnWindowScroll' : 'true',
'showDuration' : false,
'ignoreReadonly' : true,
})
work for me.
Python 3 handles strings a bit different. Originally there was just one type for
strings: str
. When unicode gained traction in the '90s the new unicode
type
was added to handle Unicode without breaking pre-existing code1. This is
effectively the same as str
but with multibyte support.
In Python 3 there are two different types:
bytes
type. This is just a sequence of bytes, Python doesn't know
anything about how to interpret this as characters.str
type. This is also a sequence of bytes, but Python knows how to
interpret those bytes as characters.unicode
type was dropped. str
now supports unicode.In Python 2 implicitly assuming an encoding could cause a lot of problems; you
could end up using the wrong encoding, or the data may not have an encoding at
all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to
guess) is often a lot better and much more in line with the "Python philosophy"
of "explicit is better than implicit".
This change is incompatible with Python 2 as many return values have changed,
leading to subtle problems like this one; it's probably the main reason why
Python 3 adoption has been so slow. Since Python doesn't have static typing2
it's impossible to change this automatically with a script (such as the bundled
2to3
).
str
to bytes
with bytes('h€llo', 'utf-8')
; this should
produce b'H\xe2\x82\xacllo'
. Note how one character was converted to three
bytes.bytes
to str
with b'H\xe2\x82\xacllo'.decode('utf-8')
.Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.
In your specific piece of code, nextline
is of type bytes
, not str
,
reading stdout
and stdin
from subprocess
changed in Python 3 from str
to
bytes
. This is because Python can't be sure which encoding this uses. It
probably uses the same as sys.stdin.encoding
(the encoding of your system),
but it can't be sure.
You need to replace:
sys.stdout.write(nextline)
with:
sys.stdout.write(nextline.decode('utf-8'))
or maybe:
sys.stdout.write(nextline.decode(sys.stdout.encoding))
You will also need to modify if nextline == ''
to if nextline == b''
since:
>>> '' == b''
False
Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.
1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A'
) and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')
). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.
2 Yes, you can use function annotations, but it's a comparatively new feature and little used.
In Java, you can verify using Object utils.
import static java.util.Objects.isNull;
if(IsNull(yourObject)){
//your block here
}
Since 2009, a lot happened. Rust delivered many CLI utilities, among them ripgrep. It is advertised as a recursively searches directories for a regex pattern, supports Windows, MacOSX and Linux.
It is fast. Look at this performance comparison with similar tools. It also has many explanations on the design of the tool. Quite informative and geeky. =)
Supports a wide range of features that the POSIX grep tools support. Look at the comparison by ack author here.
If you have Scoop, you can install it with scoop install ripgrep
. Else head over to the installation section of the doc.
No, it is not possible. You can use a custom javascript alert box.
Found a nice one using jQuery
jQuery Alert Dialogs (Alert, Confirm, & Prompt Replacements)
For me, who is running with a monorepo, there was a hidden react-native version inside yarn.lock. It was not present in any package.json, but was never deleted.
I removed that particular react-native version from yarn.lock, and did a
yarn install
This cleaned out alot of old stuff and made sure that things was working fine.
Actually VBA can be used to compile DLLs. The Office 2000 and Office XP Developer editions included a VBA editor that could be used for making DLLs for use as COM Addins.
This functionality was removed in later versions (2003 and 2007) with the advent of the VSTO (VS Tools for Office) software, although obviously you could still create COM addins in a similar fashion without the use of VSTO (or VS.Net) by using VB6 IDE.
This seems to work for me:
>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
For non-static variables, I sorted it out via Application class dictionary as below:
At Global.asax.ac:
namespace MvcWebApplication
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
private string _licensefile; // the global private variable
internal string LicenseFile // the global controlled variable
{
get
{
if (String.IsNullOrEmpty(_licensefile))
{
string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l");
if (!File.Exists(tempMylFile))
File.Copy(Server.MapPath("~/Content/license/License.l"),
tempMylFile,
true);
_licensefile = tempMylFile;
}
return _licensefile;
}
}
protected void Application_Start()
{
Application["LicenseFile"] = LicenseFile;// the global variable's bed
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
And in Controller:
namespace MvcWebApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(HttpContext.Application["LicenseFile"] as string);
}
}
}
In this way we can have global variables in ASP.NET MVC :)
NOTE: If your object is not string simply write:
return View(HttpContext.Application["X"] as yourType);
Check your .git/config
in the destination project:
$ cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[receive]
denyCurrentBranch = updateInstead
If the core. bare
is false, you can set it to true:
$ git config core.bare true
and then in your local push to remote:
git push remote_repo // suppose the destination repo is remote_repo
it will success, in the remote_repo you can check git version.
$ git log -1
commit 0623b1b900ef7331b9184722a5381bbdd2d935ba
Author: aircraft < [email protected]>
Date: Thu May 17 21:54:37 2018 +0800
and now you can not use git in your "workspace":
$ git status
fatal: This operation must be run in a work tree
you should set bare.bare
back to false.
$ git config core.bare false
<script>
function checkusers()
{
var shouldEnable = document.getElementById('checkbox').value == 0;
document.getElementById('add_button').disabled = shouldEnable;
}
</script>
This isn't a direct answer to the question (loading images >2048), but a possible solution for anyone experiencing the error.
In my case, the image was smaller than 2048 in both dimensions (1280x727 to be exact) and the issue was specifically experienced on a Galaxy Nexus. The image was in the drawable
folder and none of the qualified folders. Android assumes drawables without a density qualifier are mdpi and scales them up or down for other densities, in this case scaled up 2x for xhdpi. Moving the culprit image to drawable-nodpi
to prevent scaling solved the problem.
You can use SQLite's function creation routines (PHP manual):
$db_obj->sqliteCreateFunction('Encrypt', 'MyEncryptFunction', 2);
$db_obj->sqliteCreateFunction('Decrypt', 'MyDecryptFunction', 2);
When inserting data, you can use the encryption function directly and INSERT the encrypted data or you can use the custom function and pass unencrypted data:
$insert_obj = $db_obj->prepare('INSERT INTO table (Clear, Encrypted) ' .
'VALUES (:clear, Encrypt(:data, "' . $passwordhash_str . '"))');
When retrieving data, you can also use SQL search functionality:
$select_obj = $db_obj->prepare('SELECT Clear, ' .
'Decrypt(Encrypted, "' . $passwordhash_str . '") AS PlainText FROM table ' .
'WHERE PlainText LIKE :searchterm');
ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.
entry = prompt("Enter your name");
var count = [...entry];
console.log(count);
i fixed this by modifying php.ini
file at C:\wamp\bin\apache\apache2.4.9\bin\
curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"
first i was trying by modifying php.ini
file at C:\wamp\bin\php\php5.5.12\
and it didn't work.
hope this helps someone who is searching for the right php.ini
to modify
Do you want to find elements that contain "match", or that equal "match"?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2
):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2
):
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2
and random3
):
//*[contains(text(),'match')]
This XPATH 2.0 solution uses the matches()
function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^
) or a word boundary (i.e. \W
) and terminated by the end of the string (i.e. $
) or a word boundary. The third parameter i
evaluates the regex pattern case-insensitive. (matches random2
)
//*[matches(text(),'(^|\W)match($|\W)','i')]
math.log
is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a str
twice which is unnecessary
I implemented the following and it works well. Basically, I set the body dimensions according to the size of the iFrame content. It does mean that our non-iFrame menu can be scrolled off the screen, but otherwise, this makes our sites functional with iPad and iPhone. "workbox" is the ID of our iFrame.
// Configure for scrolling peculiarities of iPad and iPhone
if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
{
document.body.style.width = "100%";
document.body.style.height = "100%";
$("#workbox").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
iframeWidth = $("#workbox").contents().width();
if (iframeWidth > 400)
document.body.style.width = (iframeWidth + 182) + 'px';
iframeHeight = $("#workbox").contents().height();
if (iframeHeight>200)
document.body.style.height = iframeHeight + 'px';
});
}
Similar to 1000Bugy's answer but simpler because you don't have to make an anchor on the fly and dispatch a click event manually (plus an IE fix).
If you make your download button an anchor you can highjack it right before the default anchor functionality is run.
So onAnchorClick
you can set the anchor href to the canvas base64 image and the anchor download attribute to whatever you want to name your image.
This does not work in (the current) IE because it doesn't implement the download attribute and prevents download of data uris. But this can be fixed by using window.navigator.msSaveBlob
instead.
So your anchor click event handler would be as followed (where anchor
, canvas
and fileName
are scope lookups):
function onClickAnchor(e) {
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(canvas.msToBlob(), fileName);
e.preventDefault();
} else {
anchor.setAttribute('download', fileName);
anchor.setAttribute('href', canvas.toDataURL());
}
}
Here's a fiddle
Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/
I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?
The other responders are correct that split() takes a regex as the argument, so you'll have to fix that first. The other problem is that you're assuming that the line break characters are the same as the system default. Depending on where the data is coming from, and where the program is running, this assumption may not be correct.
Just use has_one
instead of belongs_to
in your :through
, like this:
class Choice
belongs_to :user
belongs_to :answer
has_one :question, :through => :answer
end
Unrelated, but I'd be hesitant to use validates_uniqueness_of instead of using a proper unique constraint in your database. When you do this in ruby you have race conditions.
For Fedora 29 workstation (Gnome 3.30.2) and Ubuntu users.
Unbind unnecessary left/right workspace keyboard combinations, list them by terminal
$ gsettings list-recursively | grep -E "org.gnome.desktop.wm.keybindings move-to-workspace-|org.gnome.desktop.wm.keybindings switch-to-workspace-"
Unbind them
$ gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "[]"
$ gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "[]"
$ gsettings set org.gnome.desktop.wm.keybindings move-to-workspace-left "[]"
$ gsettings set org.gnome.desktop.wm.keybindings move-to-workspace-right "[]"
Reset duplicate shortcuts
They can be easily reset to work with only one shortcut in Settings>Devices>Keyboard
Only type again Super+PgUp for "Move to workspace above" as an example.
Now with less duplicate shortcuts in fedora29 all vscode shortcuts for linux must work fine
TreeMap
sorts by the key natural ordering. The keys should implement Comparable
or be compatible with a Comparator
(if you passed one instance to constructor). In you case, Float
already implements Comparable
so you don't have to do anything special.
You can call keySet
to retrieve all the keys in ascending order.
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
Update for Docker: use the install-plugins.sh script. It takes a list of plugin names minus the '-plugin' extension. See the description here.
install-plugins.sh replaces the deprecated plugins.sh which now warns :
WARN: plugins.sh is deprecated, please switch to install-plugins.sh
To use a plugins.txt as per plugins.sh see this issue and this workaround:
RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/plugins.txt | tr '\n' ' ')
1) No, a NumberFormatException is an unchecked Exception. Even though you caught it (you aren't required to) because it's unchecked. This is because it is a subclass of IllegalArgumentException
which is a subclass of RuntimeException
.
2) RuntimeException
is the root of all unchecked Exceptions. Every subclass of RuntimeException
is unchecked. All other Exceptions and Throwable
are checked except for Errors ( Which comes under Throwable
).
3/4) You could alert the user that they picked a non-existent file and ask for a new one. Or just quit informing the user that they entered something invalid.
5) Throwing and catching 'Exception'
is bad practice. But more generally, you might throw other exceptions so the caller can decide how to deal with it. For example, if you wrote a library to handle reading some file input and your method was passed a non-existent file, you have no idea how to handle that. Does the caller want to ask again or quit? So you throw the Exception up the chain back to the caller.
In many cases, an unchecked Exception
occurs because the programmer did not verify inputs (in the case of NumberFormatException
in your first question). That's why its optional to catch them, because there are more elegant ways to avoid generating those exceptions.
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
jsonConfig.setRootClass( Integer.TYPE );
int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
I might argue that the answer here generally is "don't". Unless you absolutely need all the data at once, consider using a Stream
-based API (or some variant of reader / iterator). That is especially important when you have multiple parallel operations (as suggested by the question) to minimise system load and maximise throughput.
For example, if you are streaming data to a caller:
Stream dest = ...
using(Stream source = File.OpenRead(path)) {
byte[] buffer = new byte[2048];
int bytesRead;
while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
dest.Write(buffer, 0, bytesRead);
}
}
pip install -r requirements.txt
for python 2.x
pip3 install -r requirements.txt
for python 3.x
(in case multiple versions are installed)
If you need to work with games. As explained in this post https://www.learncodebygaming.com/blog/pyautogui-not-working-use-directinput, some games like Minecraft or Fortnite have their own way of registering mouse / keyboard events. The way to control mouse and keyboard events is by using the brand new PyDirectInput library. Their github repository is https://github.com/learncodebygaming/pydirectinput, and has a lot of great information.
Here's a quick code that does a mouse loop, and clicks:
import pydirectinput # pip install pydirectinput
pydirectinput.moveTo(0, 500)
pydirectinput.click()
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
You can use the following code:
(myvar instanceof Date) // returns true or false
The cleaner way to do this would be to inherit RouteAware
and implement the onNavigationEnd()
method.
It's part of a library called @bespunky/angular-zen.
npm install @bespunky/angular-zen
Make your AppComponent
extend RouteAware
and add an onNavigationEnd()
method.
import { Component } from '@angular/core';
import { NavigationEnd } from '@angular/router';
import { RouteAware } from '@bespunky/angular-zen/router-x';
@Component({
selector : 'app-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent extends RouteAware
{
protected onNavigationEnd(event: NavigationEnd): void
{
// Handle authentication...
}
}
RouteAware
has other benefits such as:
? Any router event can have a handler method (Angular's supported router events).
? Usethis.router
to access the router
? Usethis.route
to access the activated route
? Usethis.componentBus
to access the RouterOutletComponentBus service
An enhanced for
loop is just limiting the number of parameters inside the parenthesis.
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Can be written as:
for (int myValue : myArray) {
System.out.println(myValue);
}
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
get
the value/array of the JsonNode
put
on the parent.Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
This one worked for me:
def list = [1,2,3,4]
for(item in list){
println item
}
Source: Wikia.
You could write a JavaScript wto find the window height and width and make it to half to find the centre point.
Add you stuff inside a tag, and set the div top and left from the javascript to the centre coordinates you have found using Javascript.
Let me know if you need the code.
Another useful tool for this from the command line interface, is the pager command.
eg
pager grep -v Sleep | more; show full processlist;
Then you can page through the results.
You can also look for certain users, IPs or queries with grep or sed in this way.
The pager command is persistent per session.
You have to overwrite the file. In C++:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
There is a get method in HashMap:
for (String keys : objectSet.keySet())
{
System.out.println(keys + ":"+ objectSet.get(keys));
}
You can specify the remote’s URL by applying the UNC path to the file protocol. This requires you to use four slashes:
git clone file:////<host>/<share>/<path>
For example, if your main machine has the IP 192.168.10.51 and the computer name main
, and it has a share named code
which itself is a git repository, then both of the following commands should work equally:
git clone file:////main/code
git clone file:////192.168.10.51/code
If the Git repository is in a subdirectory, simply append the path:
git clone file:////main/code/project-repository
git clone file:////192.168.10.51/code/project-repository
To fix a problem, in my case: I checked Git folder under c:\program files\Git. I didn't find git.exe, so delete the Git folder and install it again. Declare them in the environment variables as shown above. the problem will be solved.
Quick answer: replace it.
In the code below I use the replaceWith
jQuery method to replace the control with a clone of itself. In the event you have any handlers bound to events on this control, we'll want to preserve those as well. To do this we pass in true
as the first parameter of the clone
method.
<input type="file" id="control"/>
<button id="clear">Clear</button>
var control = $("#control");
$("#clear").on("click", function () {
control.replaceWith( control = control.clone( true ) );
});
Fiddle: http://jsfiddle.net/jonathansampson/dAQVM/
If cloning, while preserving event handlers, presents any issues you could consider using event delegation to handle clicks on this control from a parent element:
$("form").on("focus", "#control", doStuff);
This prevents the need for any handlers to be cloned along with the element when the control is being refreshed.
import time
mintt=input("How many seconds you want to time?:")
timer=int(mintt)
while (timer != 0 ):
timer=timer-1
time.sleep(1)
print(timer)
This work very good to time seconds.
SOAP
Simple Object Access Protocol (SOAP) is a standard, an XML language, defining a message architecture and message formats. It is used by Web services. It contains a description of the operations.
WSDL is an XML-based language for describing Web services and how to access them. It will run on SMTP, HTTP, FTP, etc. It requires middleware support and well-defined mechanism to define services like WSDL+XSD and WS-Policy. SOAP will return XML based data
REST
Representational State Transfer (RESTful) web services. They are second-generation Web services.
RESTful web services communicate via HTTP rather than SOAP-based services and do not require XML messages or WSDL service-API definitions. For REST middleware is not required, only HTTP support is needed. It is a WADL standard, REST can return XML, plain text, JSON, HTML, etc.
myApp.directive("clickme",function(){
return function(scope,element,attrs){
element.bind("mousedown",function(){
<<call the Controller function>>
scope.loadEditfrm(attrs.edtbtn);
});
};
});
this will act as onclick events on the attribute clickme
Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.
Step 2: Let's say you're using Java. You would use JSONArray like this:
JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
JSONArray myInteriorArray=myArray.getJSONArray(i);
if (i==0) {
//this is the first one and is special because it holds the name of the query.
}else{
//do your stuff
String stateCode=myInteriorArray.getString(0);
String stateName=myInteriorArray.getString(1);
}
}
Do you just mean spaces or all whitespace?
For just spaces, use str_replace:
$string = str_replace(' ', '', $string);
For all whitespace (including tabs and line ends), use preg_replace:
$string = preg_replace('/\s+/', '', $string);
(From here).
To create database dump
cd /var/lib/pgsql/
pg_dump database_name> database_name.out
To resote database dump
psql -d template1
CREATE DATABASE database_name WITH ENCODING 'UTF8' LC_CTYPE 'en_US.UTF-8' LC_COLLATE 'en_US.UTF-8' TEMPLATE template0;
CREATE USER role_name WITH PASSWORD 'password';
ALTER DATABASE database_name OWNER TO role_name;
ALTER USER role_name CREATEDB;
GRANT ALL PRIVILEGES ON DATABASE database_name to role_name;
CTR+D(logout from pgsql console)
cd /var/lib/pgsql/
psql -d database_name -f database_name.out
X <- c(1:3)*0
Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c()
function, which is very frequently cited in tutorials as a usual way to declare a vector.
As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.
If you have gem installed and ruby and not able to install rails, then install ruby dev lib.
sudo apt-get install ruby-dev
It works for me. I have tried the different solution.
I had the same problem. I was using a join table and all I had with a row id field and two foreign keys. I don't know the exact caused but I did the following
Make sure I had hashcode and equals methods
@Entity
@Table(name = "USERGROUP")
public class UserGroupBean implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "USERGROUP_ID")
private Long usergroup_id;
@Column(name = "USER_ID")
private Long user_id;
@Column(name = "GROUP_ID")
private Long group_id;
Probably your code works but it is rebound somewhere after you clear it. Make sure that this it not the case. It will be more helpful if you provide some code. Where are you setting your data source? Where are you data binding? Where are you clearing the list?
Use csv.writer
:
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1
writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
if counter[row[0]] >= 4:
writer.writerow(row)
HTML
<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>
JavaScript
jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
Since you don't care, I chose the max ID for each number.
select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id
Query Explanation
select
tbl.* -- give me all the data from the base table (tbl)
from
tbl
inner join ( -- only return rows in tbl which match this subquery
select
max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
from
tbl
group by
NUMBER -- how to group rows for the MAX aggregation
) maxID
on maxID.maxID = tbl.id -- join condition ie only return rows in tbl
-- whose ID is also a MAX ID for a given NUMBER
No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:
(!isset($action)) || ($action !="add" && $action !="delete"))
If you want to convert an Instant
to a Date
:
Date myDate = Date.from(instant);
And then you can use SimpleDateFormat
for the formatting part of your question:
SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);
This is what the equals method does:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
As you can see, there's no hash code calculation, but there are a few other operations taking place there. Although x.intValue() == y.intValue()
might be slightly faster, you're getting into micro-optimization territory there. Plus the compiler might optimize the equals()
call anyway, though I don't know that for certain.
I generally would use the primitive int
, but if I had to use Integer
, I would stick with equals()
.
for me problem was solved by,
sudo apt-get remove node
sudo apt-get remove nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
alias node=nodejs
rm -r /usr/local/lib/python2.7/dist-packages/localstack/node_modules
npm install -g npm@latest || sudo npm install -g npm@latest
Swift4:
let key = "ccC2H19lDDbQDfakxcrtNMQdd0FloLGG" // length == 32
let iv = "ggGGHUiDD0Qjhuvv" // length == 16
func encryptFile(_ path: URL) -> Bool{
do{
let data = try Data.init(contentsOf: path)
let encodedData = try data.aesEncrypt(key: key, iv: iv)
try encodedData.write(to: path)
return true
}catch{
return false
}
}
func decryptFile(_ path: URL) -> Bool{
do{
let data = try Data.init(contentsOf: path)
let decodedData = try data.aesDecrypt(key: key, iv: iv)
try decodedData.write(to: path)
return true
}catch{
return false
}
}
Install CryptoSwift
import CryptoSwift
extension Data {
func aesEncrypt(key: String, iv: String) throws -> Data{
let encypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).encrypt(self.bytes)
return Data(bytes: encypted)
}
func aesDecrypt(key: String, iv: String) throws -> Data {
let decrypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).decrypt(self.bytes)
return Data(bytes: decrypted)
}
}
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
If the two
controller is nested in One
controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod
function starting with current scope and up until it will reach the rootScope
.
Configuration files are application-scoped and not assembly-scoped. So you'll need to put your library's configuration sections in every application's configuration file that is using your library.
That said, it is not a good practice to get configuration from the application's configuration file, specially the appSettings
section, in a class library. If your library needs parameters, they should probably be passed as method arguments in constructors, factory methods, etc. by whoever is calling your library. This prevents calling applications from accidentally reusing configuration entries that were expected by the class library.
That said, XML configuration files are extremely handy, so the best compromise that I've found is using custom configuration sections. You get to put your library's configuration in an XML file that is automatically read and parsed by the framework and you avoid potential accidents.
You can learn more about custom configuration sections on MSDN and also Phil Haack has a nice article on them.
You can use RegularExpressionValidator for this. below is the sample code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="TextBox1" runat="server"
ErrorMessage="Only Numbers allowed"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>
above TextBox only allowed integer to be entered because in RegularExpressionValidator has field called ValidationExpression, which validate the TextBox. However, you can modify as per your requirement.
You can see more example in MVC and Jquery here.
If you have already a file path as input, this is the code you need:
long length = new System.IO.FileInfo(path).Length;
Very Easy, Had this same problem then what i did was to download and install an app that would help in displaying then fixed the error.
Download this app xming:
http://sourceforge.net/project/downloading.php?
Install, then use settings on this link:
http://www.geo.mtu.edu/geoschem/docs/putty_install.html or follow this steps:
Installing/Configuring PuTTy and Xming
Once PuTTy and Xming have been downloaded to the PC, install according to their respective instructions.
Configuring Xming
Once Xming is installed, run the application called 'XLaunch' and verify that the settings are as shown:
Configuring PuTTy
After installing PuTTy, double-click on the PuTTy icon on the desktop and configure as shown:
This shows creating a login profile then saving it.
save profile then connect remotely to server to test.
Cheers!!!
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
Here's a tricky way to do this - select the cells that you want to replace and in Excel 2010 select F5 to bring up the "goto" box. Hit the "special" button. Select "blanks" - this should select all the cells that are blank. Enter NULL or whatever you want in the formula box and hit ctrl + enter to apply to all selected cells. Easy!
Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.
The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.
[UPDATE] This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors
Click on the link "whitespace characters" to fine tune what should be shown.
Kudos go to John Isaacks
i found my solution by creating the .cs file from visual studio itself instead of unity editor
What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer
and java.util.Observable
You can use EzPopup (https://github.com/huynguyencong/EzPopup), it is a Swift pod and very easy to use:
// init YourViewController
let contentVC = ...
// Init popup view controller with content is your content view controller
let popupVC = PopupViewController(contentController: contentVC, popupWidth: 100, popupHeight: 200)
// show it by call present(_ , animated:) method from a current UIViewController
present(popupVC, animated: true)
You can use setCustomValidity
function when oninvalid
event occurs.
Like below:-
<input class="form-control" type="email" required=""
placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>
To clear the message once you start entering use oninput="setCustomValidity('')
attribute to clear the message.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
Add the function:
function scrollToForm() {
document.querySelector('#form').scrollIntoView({behavior: 'smooth'});
}
Trigger the function:
<a href="javascript: scrollToForm();">Jump to form</a>
I tried to add to @user686605's work:
1) changed the cursor to col-resize at the th border
2) fixed the highlight text issue when resizing
I partially succeeded at both. Maybe someone who is better at CSS can help move this forward?
http://jsfiddle.net/telefonica/L2f7F/4/
HTML
<!--Click on th and drag...-->
<table>
<thead>
<tr>
<th><div class="noCrsr">th 1</div></th>
<th><div class="noCrsr">th 2</div></th>
</tr>
</thead>
<tbody>
<tr>
<td>td 1</td>
<td>td 2</td>
</tr>
</tbody>
</table>
JS
$(function() {
var pressed = false;
var start = undefined;
var startX, startWidth;
$("table th").mousedown(function(e) {
start = $(this);
pressed = true;
startX = e.pageX;
startWidth = $(this).width();
$(start).addClass("resizing");
$(start).addClass("noSelect");
});
$(document).mousemove(function(e) {
if(pressed) {
$(start).width(startWidth+(e.pageX-startX));
}
});
$(document).mouseup(function() {
if(pressed) {
$(start).removeClass("resizing");
$(start).removeClass("noSelect");
pressed = false;
}
});
});
CSS
table {
border-width: 1px;
border-style: solid;
border-color: black;
border-collapse: collapse;
}
table td {
border-width: 1px;
border-style: solid;
border-color: black;
}
table th {
border: 1px;
border-style: solid;
border-color: black;
background-color: green;
cursor: col-resize;
}
table th.resizing {
cursor: col-resize;
}
.noCrsr {
cursor: default;
margin-right: +5px;
}
.noSelect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
"Then" is a command in bash, thus it needs a ";" or a newline before it.
#!/bin/bash
echo "start\n"
for f in *.jpg
do
fname=$(basename "$f")
echo "fname is $fname\n"
fname="${filename%.*}"
echo "fname is $fname\n"
if [$[fname%2] -eq 1 ]
then
echo "removing $fname\n"
rm $f
fi
done
**/*Css Class*/**
.upCase
{
text-transform: uppercase;
}
<asp:TextBox ID="TextBox1" runat="server" Text="abc" Cssclass="upCase"></asp:TextBox>
Be careful when dealing with timestamps stored in the FAT32 filesystem - it is always persisted in local time coordinates (which include DST - see msdn article). Got burned on that one.
Typescript is (a superset of) javascript, so you just use JSON.parse
as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);
The checkbox is in a td
, so need to get the parent first:
$("input:checkbox").on("change", function() {
$(this).parent().next().find("label").text("TESTTTT");
});
Alternatively, find a label which has a for
with the same id
(perhaps more performant than reverse traversal) :
$("input:checkbox").on("change", function() {
$("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});
Or, to be more succinct just this.id
:
$("input:checkbox").on("change", function() {
$("label[for='" + this.id + "']").text("TESTTTT");
});
grep -r "yourstring" *
Will find "yourstring" in any files and folders Now if you want to look for two different strings at the same time you can always use option E and add words for the search. example after the break
grep -rE "yourstring|yourotherstring|$" *
will search for list locations where yourstring
or yourotherstring
matchessed cannot match \n because the trailing newline is removed before the line is put into the pattern space but can match \r, so you can convert \r\n (dos) to \n (unix) by removing \r
sed -i 's/\r//g' file
Warning: this will change the original file
However, you cannot change from unix EOL to dos or old mac (\r) by this. More readings here:
var a = b = " /var/www/site/Brand new document.docx ";_x000D_
_x000D_
console.log( a.split(' ').join('') );_x000D_
console.log( b.replace( /\s/g, '') );
_x000D_
Two ways of doing this!
static linking gives you only a single exe, inorder to make a change you need to recompile your whole program. Whereas in dynamic linking you need to make change only to the dll and when you run your exe, the changes would be picked up at runtime.Its easier to provide updates and bug fixes by dynamic linking (eg: windows).
You can set an background image without any code!
Just press the button you want an image to in Main.storyboard, then, in the utilities bar to the right, press the attributes inspector and set the background to the image you want! Make sure you have the picture you want in the supporting files to the left.
Replace
<a href="http://www.foracure.org.au" target="_blank"></a>
with
<a href="#" onclick='window.open("http://www.foracure.org.au");return false;'></a>
in your code and will work in Chrome and other browsers.
Thanks Anurag
if(TextUtils.isEmpty(textA.getText())){
showToast(it's Null");
}
you can use TextUtils.isEmpty like my Example ! Good luck
I know for there's Fluid and Prism (there are others, that's the one I used to use) that let you load a website into what looks like a standalone app.
In Chrome, you can create desktop shortcuts for websites. (you do that from within Chrome, you can't/shouldn't package that with your app) Chrome Frame is different:
Google Chrome Frame is a plug-in designed for Internet Explorer based on the open-source Chromium project; it brings Google Chrome's open web technologies to Internet Explorer.
You'd need to have some sort of wrapper like that for your webapp, and then the rest is the web technologies you're used to. You can use HTML5 local storage to store data while the app is offline. I think you might even be able to work with SQLite.
I don't know how you would go about accessing OS specific features, though. What I described above has the same limitations as any "regular" website. Hopefully this gives you some sort of guidance on where to start.
Other answers mainly get all name of object, to get value of property, you can use yourObj[name]
, for example:
var propNames = Object.getOwnPropertyNames(yourObj);
propNames.forEach(
function(propName) {
console.log(
'name: ' + propName
+ ' value: ' + yourObj[propName]);
}
);
Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs
base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action
type is your ticket.
1. Create your event on your class right after your class
declaration.
public event Action<string,string,string,string>MyEvent;
2. Create your event handler class method in your class.
private void MyEventHandler(string s1,string s2,string s3,string s4)
{
Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}
3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the +=
operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.
class Example
{
public Example() // I'm a C# style class constructor
{
MyEvent += new Action<string,string,string,string>(MyEventHandler);
}
}
4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:
MyEvent("wow","this","is","cool");
The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.
In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...>
out and pass nothing to your event handler.
And, again, if you had multiple custom event handlers, and subscribed them all to your event with the +=
operator, then your event trigger would have called them all in sequence.
But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:
Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.
Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:
private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;
Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:
string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];
You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -=
operator like so:
MyEvent -= MyEventHandler;
A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)
Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:
MyEvent = null;
The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
You'll want to use the specified market
protocol:
final String appPackageName = "com.example"; // Can also use getPackageName(), as below
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}
While using getPackageName()
from Context
or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.
I hate to admit how little I've done an iPhone app for, but I can tell you I won't be doing that again. The guy who said that "simple, one function apps can be done .. [by solo developers]... for $5K" is correct; however, that is still lowball, and presumes almost no project design, graphic design or network backend work.
you can check ZBarSDK to reads QR Code and ECN/ISBN codes it's simple to integrate try the following code.
- (void)scanBarcodeWithZBarScanner
{
// ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
//Get the return value from controller
[reader setReturnBlock:^(BOOL value) {
}
and in didFinishPickingMediaWithInfo we get bar code value.
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
barcodeValue = symbol.data;
// EXAMPLE: do something useful with the barcode image
barcodeImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[_barcodeIV setImage:barcodeImage];
//set the values for to TextFields
[self setBarcodeValue:YES];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
[reader dismissViewControllerAnimated:YES completion:nil];
}
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
I had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed
For those try to remove nvm from brew
it may not be enough to just brew uninstall nvm
if you see npm prefix is still /usr/local, run this command
sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
A small addition to Riley Avron answer to account locale changes:
extension UIButton {
func centerTextAndImage(spacing: CGFloat) {
let insetAmount = spacing / 2
let writingDirection = UIApplication.sharedApplication().userInterfaceLayoutDirection
let factor: CGFloat = writingDirection == .LeftToRight ? 1 : -1
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount*factor, bottom: 0, right: insetAmount*factor)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount*factor, bottom: 0, right: -insetAmount*factor)
self.contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
}
}
It looks like you forgot the prefix on the color attribute. Try
<stroke android:width="2dp" android:color="#ff00ffff"/>
The Python itertools
page has exactly a powerset
recipe for this:
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Output:
>>> list(powerset("abcd"))
[(), ('a',), ('b',), ('c',), ('d',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd')]
If you don't like that empty tuple at the beginning, you can just change the range
statement to range(1, len(s)+1)
to avoid a 0-length combination.
With Django version 1.3, the class based approach is:
from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)
This example lives in in urls.py
Recommendation:
when you have more than one condition with and
and or
is better separate with ()
to avoid verification problems
<c:if test="${(not validID) and (addressIso == 'US' or addressIso == 'BR')}">
If the file is the too big to use as a list, and you simply want to reverse the file, you can initially write the file in reversed order and then read one line at the time from the file's end (and write it to another file) with file-read-backwards module
Simple Solution:
import pandas as pd
df = pd.read_csv('file_name.csv', engine='python')
const absolutePath = path.join(__dirname, some, dir);
vs.
const absolutePath = path.resolve(__dirname, some, dir);
path.join
will concatenate __dirname
which is the directory name of the current file concatenated with values of some
and dir
with platform-specific separator.
Whereas
path.resolve
will process __dirname
, some
and dir
i.e. from right to left prepending it by processing it.
If any of the values of some
or dir
corresponds to a root path then the previous path will be omitted and process rest by considering it as root
In order to better understand the concept let me explain both a little bit more detail as follows:-
The path.join
and path.resolve
are two different methods or functions of the path module provided by nodejs.
Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.
path.join
concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
When no arguments supplied
The following example will help you to clearly understand both concepts:-
My filename is index.js
and the current working directory is E:\MyFolder\Pjtz\node
const path = require('path');
console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname
Result
? node index.js
path.join() : .
path.resolve() : E:\MyFolder\Pjtz\node
path.resolve()
method will output the absolute path whereas the path.join()
returns . representing the current working directory if nothing is provided
When some root path is passed as arguments
const path=require('path');
console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));
Result i
? node index.js
path.join() : abc\bcd
path.resolve() : E:\bcd
path.join()
only concatenates the input list with platform-specific separator while the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
convert the string to HashMap using Object Mapper ...
new ObjectMapper().readValue(string, Map.class);
Internally Map will behave as JSON Object
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:
External
option in Unity ? Preferences ? Packages ? Repository
Hidden Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
File
menuNote that the only folders you need to keep under source control are Assets
and ProjectSettigns
.
More information about keeping Unity Project under source control you can find in this post.
Javascript's logical OR operator is short-circuiting and can replace your "Elvis" operator:
var displayName = user.name || "Anonymous";
However, to my knowledge there's no equivalent to your ?.
operator.
They are equivalent in effect, pointing to different shortcuts:
border: 0;
//short for..
border-width: 0;
And the other..
border: none;
//short for...
border-style: none;
Both work, just pick one and go with it :)
I'd start by the distinction that exists in Scala between def, val and var.
def - defines an immutable label for the right side content which is lazily evaluated - evaluate by name.
val - defines an immutable label for the right side content which is eagerly/immediately evaluated - evaluated by value.
var - defines a mutable variable, initially set to the evaluated right side content.
Example, def
scala> def something = 2 + 3 * 4
something: Int
scala> something // now it's evaluated, lazily upon usage
res30: Int = 14
Example, val
scala> val somethingelse = 2 + 3 * 5 // it's evaluated, eagerly upon definition
somethingelse: Int = 17
Example, var
scala> var aVariable = 2 * 3
aVariable: Int = 6
scala> aVariable = 5
aVariable: Int = 5
According to above, labels from def and val cannot be reassigned, and in case of any attempt an error like the below one will be raised:
scala> something = 5 * 6
<console>:8: error: value something_= is not a member of object $iw
something = 5 * 6
^
When the class is defined like:
scala> class Person(val name: String, var age: Int)
defined class Person
and then instantiated with:
scala> def personA = new Person("Tim", 25)
personA: Person
an immutable label is created for that specific instance of Person (i.e. 'personA'). Whenever the mutable field 'age' needs to be modified, such attempt fails:
scala> personA.age = 44
personA.age: Int = 25
as expected, 'age' is part of a non-mutable label. The correct way to work on this consists in using a mutable variable, like in the following example:
scala> var personB = new Person("Matt", 36)
personB: Person = Person@59cd11fe
scala> personB.age = 44
personB.age: Int = 44 // value re-assigned, as expected
as clear, from the mutable variable reference (i.e. 'personB') it is possible to modify the class mutable field 'age'.
I would still stress the fact that everything comes from the above stated difference, that has to be clear in mind of any Scala programmer.
Hope you have key field is two tables.
UPDATE tblindiantime t
SET CountryName = (SELECT c.BusinessCountry
FROM contacts c WHERE c.Key = t.Key
)
If you want to reset the window layout. Then
go to "WINDOW" -> "RESET WINDOW LAYOUT"
I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.
HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:
<div id="wrapper">
<div id="scroller">
... my scrollable content
</div>
</div>
CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).
.touch #wrapper {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: hidden;
}
.touch #scroller {
position: absolute;
z-index: 1;
width: 100%;
}
JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.
# coffeescript
if Modernizr.touch
myScroller = new IScroll('#wrapper', probeType: 3)
myScroller.on 'scroll', updatePosition
myScroller.on 'scrollEnd', updatePosition
You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)
function getScroll(elem, iscroll) {
var x, y;
if (Modernizr.touch && iscroll) {
x = iscroll.x * -1;
y = iscroll.y * -1;
} else {
x = elem.scrollTop;
y = elem.scrollLeft;
}
return {x: x, y: y};
}
The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.
EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.
The "JavaScript" way:
var lang = navigator.language || navigator.userLanguage; //no ?s necessary
Really you should be doing language detection on the server, but if it's absolutely necessary to know/use via JavaScript, it can be gotten.
Creating a single combined plot with your current data set up would look something like this
p <- ggplot() +
# blue plot
geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
colour="darkblue", size=1) +
# red plot
geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
colour="red", size=1)
however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner
visual1$group <- 1
visual2$group <- 2
visual12 <- rbind(visual1, visual2)
p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
geom_point() +
geom_smooth(size=1)
In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.
Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.
Possibly every remotely modern compiler implements #pragma pack
which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)
From C99 §6.7.2.1:
12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.
13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
For 2005 up, you can use
SELECT
[name]
,create_date
,modify_date
FROM
sys.tables
I think for 2000, you need to have enabled auditing.
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
Everything is here : http://blog.progs.be/542/date-to-java-time
The answer with "round-tripping" is not exact : when you do
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
if your system timezone is not UTC/GMT, you change the time !
My error was on a variable declaration line with a multi-line extension. I have a trailing space after the "\" which made that an invalid line continuation.
MY_VAR = \
val1 \ <-- 0x20 there caused the error.
val2
I would suggest to read up a bit on the syntax. See here.
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
You define your struct as xyx
, however in your main, you use struct xyz a;
, which only creates a forward declaration of a differently named struct.
Try using xyx a;
instead of that line.
Short answer: No. Use WebM or Ogg instead.
This article covers just about everything you need to know about the <video>
element, including which browsers support which container formats and codecs.
This is because require()
does not exist in the browser/client-side JavaScript.
Now you're going to have to make some choices about your client-side JavaScript script management.
You have three options:
<script>
tag.CommonJS client side-implementations include (most of them require a build step before you deploy):
You can read more about my comparison of Browserify vs (deprecated) Component.
AMD implementations include:
Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.
You can do this using OPENROWSET as suggested in this answer. Reposting Slogmeister Extrarodinare answer:
Use T-SQL
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName
But, there are couple of caveats:
You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.
The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.
For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).
For example:
Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">
Incorrect: div ng-include src=" 'add-more.html' ">
Probably the most elegant way of doing this is to do it in one step. See val()
.
$("#text").val(function(i, val) {
return val.replace('.', ':');
});
compared to:
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));
From the docs:
.val( function(index, value) )
function(index, value)A function returning the value to set.
This method is typically used to set the values of form fields. For
<select multiple="multiple">
elements, multiple s can be selected by passing in an array.The
.val()
method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:$('input:text.items').val(function(index, value) { return value + ' ' + this.className; });
This example appends the string " items" to the text inputs' values.
This requires jQuery 1.4+.
Typescript projects (I have typescript in SFC vue components), need to set resolveJsonModule
compiler option to true
.
In tsconfig.json:
{
"compilerOptions": {
...
"resolveJsonModule": true,
...
},
...
}
Happy coding :)
(Source https://www.typescriptlang.org/docs/handbook/compiler-options.html)
In MongoDB To insert Json array data from file(from particular location from a system / pc) using mongo shell command. While executing below command, command should be in single line.
var file = cat('I:/data/db/card_type_authorization.json'); var o = JSON.parse(file); db.CARD_TYPE_AUTHORIZATION.insert(o);
JSON File: card_type_authorization.json
[{
"code": "visa",
"position": 1,
"description": "Visa",
"isVertualCard": false,
"comments": ""
},{
"code": "mastercard",
"position": 2,
"description": "Mastercard",
"isVertualCard": false,
"comments": ""
}]
If you use Jquery you can add this to your javascript:
$('.smooth-goto').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
return false;
});
Also, don't forget to add this class to your a tag too like this:
<a href="#id-of-element" class="smooth-goto">Text</a>
After chown
and chgrp
'ing /var/lib/mysql
per the answer by @Bad Programmer, you may also have to execute the following command:
sudo mysql_install_db --user=mysql --ldata=/var/lib/mysql
Then restart your mysqld
.
I was really surprised that Scribe logging framework that I use at work isn't even mentioned here. What is more, it doesn't even appear on the first page in Google after searching "scala logging". But this page appears when googling it! So let me leave that here.
Main advantages of Scribe:
In case you haven't come to a conclusion... I took Henrique's answer and gave a better logic solution. This is completely compatible with PHPSpreadSheet in case someone is using PHPSpreadSheet or PHPExcel.
$spreadOrPhpExcel = new SpreadSheet(); // or new PHPExcel();
print_in_sheet($spreadOrPhpExcel);
function print_in_sheet($spread)
{
$sheet = 0;
foreach( getData() as $report => $value ){
# If number of sheet is 0 then no new worksheets are created
if( $sheet > 0 ){
$spread->createSheet();
}
# Index for the worksheet is setted and a title is assigned
$wSheet = $spread->setActiveSheetIndex($sheet)->setTitle($report);
# Printing data
$wSheet->setCellValue("A1", "Hello World!");
# Index number is incremented for the next worksheet
$sheet++;
}
return $spread;
}
There are two stages to processing Unicode text. The first is "how can I input it and output it without losing information". The second is "how do I treat text according to local language conventions".
tchrist's post covers both, but the second part is where 99% of the text in his post comes from. Most programs don't even handle I/O correctly, so it's important to understand that before you even begin to worry about normalization and collation.
This post aims to solve that first problem
When you read data into Perl, it doesn't care what encoding it is. It allocates some memory and stashes the bytes away there. If you say print $str
, it just blits those bytes out to your terminal, which is probably set to assume everything that is written to it is UTF-8, and your text shows up.
Marvelous.
Except, it's not. If you try to treat the data as text, you'll see that Something Bad is happening. You need go no further than length
to see that what Perl thinks about your string and what you think about your string disagree. Write a one-liner like: perl -E 'while(<>){ chomp; say length }'
and type in ????
and you get 12... not the correct answer, 4.
That's because Perl assumes your string is not text. You have to tell it that it's text before it will give you the right answer.
That's easy enough; the Encode module has the functions to do that. The generic entry point is Encode::decode
(or use Encode qw(decode)
, of course). That function takes some string from the outside world (what we'll call "octets", a fancy of way of saying "8-bit bytes"), and turns it into some text that Perl will understand. The first argument is a character encoding name, like "UTF-8" or "ASCII" or "EUC-JP". The second argument is the string. The return value is the Perl scalar containing the text.
(There is also Encode::decode_utf8
, which assumes UTF-8 for the encoding.)
If we rewrite our one-liner:
perl -MEncode=decode -E 'while(<>){ chomp; say length decode("UTF-8", $_) }'
We type in ???? and get "4" as the result. Success.
That, right there, is the solution to 99% of Unicode problems in Perl.
The key is, whenever any text comes into your program, you must decode it. The Internet cannot transmit characters. Files cannot store characters. There are no characters in your database. There are only octets, and you can't treat octets as characters in Perl. You must decode the encoded octets into Perl characters with the Encode module.
The other half of the problem is getting data out of your program. That's easy to; you just say use Encode qw(encode)
, decide what the encoding your data will be in (UTF-8 to terminals that understand UTF-8, UTF-16 for files on Windows, etc.), and then output the result of encode($encoding, $data)
instead of just outputting $data
.
This operation converts Perl's characters, which is what your program operates on, to octets that can be used by the outside world. It would be a lot easier if we could just send characters over the Internet or to our terminals, but we can't: octets only. So we have to convert characters to octets, otherwise the results are undefined.
To summarize: encode all outputs and decode all inputs.
Now we'll talk about three issues that make this a little challenging. The first is libraries. Do they handle text correctly? The answer is... they try. If you download a web page, LWP will give you your result back as text. If you call the right method on the result, that is (and that happens to be decoded_content
, not content
, which is just the octet stream that it got from the server.) Database drivers can be flaky; if you use DBD::SQLite with just Perl, it will work out, but if some other tool has put text stored as some encoding other than UTF-8 in your database... well... it's not going to be handled correctly until you write code to handle it correctly.
Outputting data is usually easier, but if you see "wide character in print", then you know you're messing up the encoding somewhere. That warning means "hey, you're trying to leak Perl characters to the outside world and that doesn't make any sense". Your program appears to work (because the other end usually handles the raw Perl characters correctly), but it is very broken and could stop working at any moment. Fix it with an explicit Encode::encode
!
The second problem is UTF-8 encoded source code. Unless you say use utf8
at the top of each file, Perl will not assume that your source code is UTF-8. This means that each time you say something like my $var = '??'
, you're injecting garbage into your program that will totally break everything horribly. You don't have to "use utf8", but if you don't, you must not use any non-ASCII characters in your program.
The third problem is how Perl handles The Past. A long time ago, there was no such thing as Unicode, and Perl assumed that everything was Latin-1 text or binary. So when data comes into your program and you start treating it as text, Perl treats each octet as a Latin-1 character. That's why, when we asked for the length of "????", we got 12. Perl assumed that we were operating on the Latin-1 string "æååã" (which is 12 characters, some of which are non-printing).
This is called an "implicit upgrade", and it's a perfectly reasonable thing to do, but it's not what you want if your text is not Latin-1. That's why it's critical to explicitly decode input: if you don't do it, Perl will, and it might do it wrong.
People run into trouble where half their data is a proper character string, and some is still binary. Perl will interpret the part that's still binary as though it's Latin-1 text and then combine it with the correct character data. This will make it look like handling your characters correctly broke your program, but in reality, you just haven't fixed it enough.
Here's an example: you have a program that reads a UTF-8-encoded text file, you tack on a Unicode PILE OF POO
to each line, and you print it out. You write it like:
while(<>){
chomp;
say "$_ ";
}
And then run on some UTF-8 encoded data, like:
perl poo.pl input-data.txt
It prints the UTF-8 data with a poo at the end of each line. Perfect, my program works!
But nope, you're just doing binary concatenation. You're reading octets from the file, removing a \n
with chomp, and then tacking on the bytes in the UTF-8 representation of the PILE OF POO
character. When you revise your program to decode the data from the file and encode the output, you'll notice that you get garbage ("ð©") instead of the poo. This will lead you to believe that decoding the input file is the wrong thing to do. It's not.
The problem is that the poo is being implicitly upgraded as latin-1. If you use utf8
to make the literal text instead of binary, then it will work again!
(That's the number one problem I see when helping people with Unicode. They did part right and that broke their program. That's what's sad about undefined results: you can have a working program for a long time, but when you start to repair it, it breaks. Don't worry; if you are adding encode/decode statements to your program and it breaks, it just means you have more work to do. Next time, when you design with Unicode in mind from the beginning, it will be much easier!)
That's really all you need to know about Perl and Unicode. If you tell Perl what your data is, it has the best Unicode support among all popular programming languages. If you assume it will magically know what sort of text you are feeding it, though, then you're going to trash your data irrevocably. Just because your program works today on your UTF-8 terminal doesn't mean it will work tomorrow on a UTF-16 encoded file. So make it safe now, and save yourself the headache of trashing your users' data!
The easy part of handling Unicode is encoding output and decoding input. The hard part is finding all your input and output, and determining which encoding it is. But that's why you get the big bucks :)
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
you can declare your component like this:
const MyComponent: React.FunctionComponent = (props) => {
return props.children;
}
If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:
s = "((String1))"
s = s[2...-2]
p s # => "String1"
If you want to remove all parentheses from the string you can use the delete method on the string class:
s = "((String1))"
s.delete! '()'
p s # => "String1"
Robocopy is designed for reliable copying with many copy options, file selection restart, etc.
/xf
to excludes files and /e
for subdirectories:
robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
import inspect
class X:
def xyz(self, a, b, c):
return
print(len(inspect.getfullargspec(X.xyz).args))
4
Note: If xyz wasn't inside class X and had no "self" and just "a, b, c", then it would have printed 3.
For python below 3.5, you may want to replace inspect.getfullargspec
by inspect.getargspec
in the code above.
Turns out string starting with a newline (or anything other than "<") is not considered HTML string in jQuery 1.9
http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring
Run:
rvm implode
Now you need to uninstall the RVM gem using:
gem uninstall rvm
Check if there are any remaining RVM files in your home directory, if yes remove them.
Go to the home directory and list all hidden files:
ls -a
rm .rvm
rm .rvmrc
Binding to document click through @Hostlistener is costly. It can and will have a visible performance impact if you overuse(for example, when building a custom dropdown component and you have multiple instances created in a form).
I suggest adding a @Hostlistener() to the document click event only once inside your main app component. The event should push the value of the clicked target element inside a public subject stored in a global utility service.
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {
constructor(private utilitiesService: UtilitiesService) {}
@HostListener('document:click', ['$event'])
documentClick(event: any): void {
this.utilitiesService.documentClickedTarget.next(event.target)
}
}
@Injectable({ providedIn: 'root' })
export class UtilitiesService {
documentClickedTarget: Subject<HTMLElement> = new Subject<HTMLElement>()
}
Whoever is interested for the clicked target element should subscribe to the public subject of our utilities service and unsubscribe when the component is destroyed.
export class AnotherComponent implements OnInit {
@ViewChild('somePopup', { read: ElementRef, static: false }) somePopup: ElementRef
constructor(private utilitiesService: UtilitiesService) { }
ngOnInit() {
this.utilitiesService.documentClickedTarget
.subscribe(target => this.documentClickListener(target))
}
documentClickListener(target: any): void {
if (this.somePopup.nativeElement.contains(target))
// Clicked inside
else
// Clicked outside
}
If you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
@section scripts {
<script type="text/javascript">alert('hello');</script>
}
the required indicates whether or not the view using the layout page must have a scripts section
Simply you can use this
public int getReverseInt(int value) {
int resultNumber = 0;
for (int i = value; i !=0; i /= 10) {
resultNumber = resultNumber * 10 + i % 10;
}
return resultNumber;
}
You can use this method with the given value which you want revers.
declare @DBRoleName varchar(40) = 'yourUserName'
SELECT 'GRANT ' + dbprm.permission_name + ' ON ' + OBJECT_SCHEMA_NAME(major_id) + '.' + OBJECT_NAME(major_id) + ' TO ' + dbrol.name + char(13) COLLATE Latin1_General_CI_AS
from sys.database_permissions dbprm
join sys.database_principals dbrol on
dbprm.grantee_principal_id = dbrol.principal_id
where dbrol.name = @DBRoleName
http://www.sqlserver-dba.com/2014/10/how-to-script-database-role-permissions-and-securables.html
I found this to be an excellent solution for generating a script to replicate access between environments
I am using nano editor in a Raspberry Pi with Italian OS language and Italian keyboard. Don't know the exact reason, but in this environment the shortcut is:
Ctrl+-
From Hadoop page,
start-all.sh
This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.
start-dfs.sh
This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh
to separately start the job tracker
start-all.sh/stop-all.sh
has to be run on the master node
You would use start-all.sh
on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).
In multi-node setup,
You will use start-all.sh
on the master node and would start what is necessary on the slaves as well.
Alternatively,
Use start-dfs.sh
on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.
Use start-mapred.sh
on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.
hadoop-daemon.sh
as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh
.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.
Have a look at this start-all.sh
it call config followed by dfs and mapred
get sock opt may be somewhat useful, however, another way would to have a signal handler installed for SIGPIPE. Basically whenever you the socket connection breaks, the kernel will send a SIGPIPE signal to the process and then you can do the needful. But this still does not provide the solution for knowing the status of the connection. hope this helps.
There is a well-maintained flat-file version of the ip->country database maintained by the Perl community at CPAN
Access to those files does not require a dataserver, and the data itself is roughly 515k
Higemaru has written a PHP wrapper to talk to that data: php-ip-country-fast
In Spring applications, if you enable annotation based transaction support using <tx:annotation-driven/>
and annotate any class/method with @Transactional(propagation=Propagation.REQUIRED) then Spring framework will start a transaction and executes the method and commits the transaction. If any RuntimeException occurred then the transaction will be rolled back.
Actually propagation=Propagation.REQUIRED is default propagation level, you don't need to explicitly mentioned it.
For further info : http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations
I don't know why you need that first [0-9]
.
Try:
^-?\d*(\.\d+)?$
Update
If you want to be sure that you'll have a digit on the ones place, then use
^-?\d+(\.\d+)?$
I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.
I found this to be a more elegant solution, without flex:
.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}
To run this in later versions of pip (tested on pip==10.0.1
) use the following:
from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
print(requirement)
its very simple
add two part in code :
1- add namespace:
using Microsoft.Win32;
2-add application to registery :
RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);
if you want delete app from registery:
key.DeleteValue("your_app_name",false);
First try this in your Windows cmd window:
pip3 install pyqt5
If that is successful, it will look something like this:
C:\Windows\System32>pip3 install pyqt5
Collecting pyqt5
Downloading PyQt5-5.9-5.9.1-cp35.cp36.cp37-none-win_amd64.whl (77.2MB)
100% |################################| 77.2MB 13kB/s
Collecting sip<4.20,>=4.19.3 (from pyqt5)
Downloading sip-4.19.3-cp35-none-win_amd64.whl (49kB)
100% |################################| 51kB 984kB/s
Installing collected packages: sip, pyqt5
Successfully installed pyqt5-5.9 sip-4.19.3
If that did not work, you might try this link from SourceForge.
PyQt5 .exe installers for Windows
How to find the installer that's right for you?
First, determine what version of Python you have and whether you have 32-bit or 64-bit Python. Next, open one of the directories. I'm on Python 3.5 64-bit so I'm looking for a .exe with those specs. When you open a directory on SourceForge, you will see some directories with ONLY .zip or .tar.gz. That's not what you're looking for. A good indication of which directory you should click is given by the "Downloads/Week" column. I'll open the PyQt-5.6 directory in my case.
Here we notice some .exe files:
PyQt-5.6
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x32-2.exe
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
|_PyQt5_gpl-5.6.zip
|_PyQt5_gpl-5.6.tar.gz
I know these are Python 3.5 by Py3.5
in the file name. I am also looking for the 64-bit version so I'll download PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
. Final answer!
Note: if you try to install a version that's not compatible with your system, a dialog box will appear immediately after running the .exe. That's an indication that you've chosen the wrong one. I'm not trying to sound like a dbag... I did that several times!
To test a successful install, in your Python interpreter, try to import:
from PyQt5 import QtCore, QtGui, QtWidgets
How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.
<div class="container">
<div class="row">
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col1
</div>
<div class="col-xs-4 col-sm-2" align="center">
Col2
</div>
<div class="hidden-xs col-sm-6 col-md-5" align="center">
Col3
</div>
<div class="visible-md col-md-3 " align="center">
Col4
</div>
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col5
</div>
</div>
</div>
Since the question is how to replace ALL whitespaces
UPDATE `table`
SET `col_name` = REPLACE
(REPLACE(REPLACE(`col_name`, ' ', ''), '\t', ''), '\n', '');
swift 4
I just add this line in viewDidLoad and work fine with me.
view.removeConstraints(view.constraints)
If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.
.space-between {_x000D_
border: 1px solid red;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
border: 1px solid blue;_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
<div class="child">1</div>_x000D_
<div class="default-flex">_x000D_
<div class="child">2</div>_x000D_
<div class="child">3</div>_x000D_
<div class="child">4</div>_x000D_
<div class="child">5</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
(Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.)
[Service]
Environment="HTTP_PROXY=http://proxy.server.com:80"
Environment="HTTPS_PROXY=http://proxy.server.com:80"
Environment="NO_PROXY=.proxy.server.com,*.proxy.server.com,localhost,127.0.0.1,::1"
http_proxy=http://proxy.server.com:80
https_proxy=http://proxy.server.com:80
ftp_proxy=http://proxy.server.com:80
no_proxy=127.0.0.1,10.0.0.0/8,3.0.0.0/8,localhost,*.abc.com
AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.
Just try this on the command-line:
C:\> nslookup
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>> SRV service location:
priority = 0
weight = 100
port = 389
svr hostname = <<ldap.hostname>>.<<your.AD.domain>>
(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)
Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.
Just my 2 cents as stated in the answer above : The copy() method shouldn't be used as-is for copying files without a slight adjustment:
function copy(callback) {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
// Do not callback() upon "close" event on the readStream
// readStream.on('close', function () {
// Do instead upon "close" on the writeStream
writeStream.on('close', function () {
callback();
});
readStream.pipe(writeStream);
}
The copy function wrapped in a Promise:
function copy(oldPath, newPath) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(oldPath);
const writeStream = fs.createWriteStream(newPath);
readStream.on('error', err => reject(err));
writeStream.on('error', err => reject(err));
writeStream.on('close', function() {
resolve();
});
readStream.pipe(writeStream);
})
However, keep in mind that the filesystem might crash if the target folder doesn't exist.