@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S
My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.
In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...
It also wraps shutil.rmtree
:
$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib
# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)
# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)
you can find it on github or PyPi
Disclaimer: I'm the author of the pathlib3x library.
For hidden files I had to use the following:
DEL /S /Q /A:H Thumbs.db
BSD's find
implementation on macOS is different from GNU find - this is compatible with both BSD and GNU find. Start with a globbing implementation, using -name
and the -o
for or - Put this function in your .bashrc
file:
pyclean () {
find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
}
Then cd
to the directory you want to recursively clean, and type pyclean
.
This is a GNU find, only (i.e. Linux) solution, but I feel it's a little nicer with the regex:
pyclean () {
find . -regex '^.*\(__pycache__\|\.py[co]\)$' -delete
}
On Windows, you probably don't even have find
. You do, however, probably have Python 3, which starting in 3.4 has the convenient pathlib
module:
python3 -Bc "import pathlib; [p.unlink() for p in pathlib.Path('.').rglob('*.py[co]')]"
python3 -Bc "import pathlib; [p.rmdir() for p in pathlib.Path('.').rglob('__pycache__')]"
The -B
flag tells Python not to write .pyc
files. (See also the PYTHONDONTWRITEBYTECODE
environment variable.)
The above abuses list comprehensions for looping, but when using python -c
, style is rather a secondary concern. Alternatively we could abuse (for example) __import__
:
python3 -Bc "for p in __import__('pathlib').Path('.').rglob('*.py[co]'): p.unlink()"
python3 -Bc "for p in __import__('pathlib').Path('.').rglob('__pycache__'): p.rmdir()"
The top answer used to say:
find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
This would seem to be less efficient because it uses three processes. find
takes a regular expression, so we don't need a separate invocation of grep
. Similarly, it has -delete
, so we don't need a separate invocation of rm
—and contrary to a comment here, it will delete non-empty directories so long as they get emptied by virtue of the regular expression match.
From the xargs
man page:
find /tmp -depth -name core -type f -delete
Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process).
You can delete the folder locally and then push, as follow:
git rm -r folder_name
git commit -m "your commit"
git push origin master
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
I suspect that the problem is that the path is incorrect. Try this:
UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
file.delete();
} else {
System.err.println(
"I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}
An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be
With New FileSystemObject
If .FileExists(yourFilePath) Then
.DeleteFile yourFilepath
End If
End With
Same effect but fewer (well, none at all) variable declarations.
The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).
This works for plain BSD so it should be universally compatible with all flavors. Below.e.g in pwd
( .
)
find . -size 0 | xargs rm
I tested this code on Nougat emulator and it worked:
In manifest add:
<application...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
Create empty xml folder in res folder and past in the provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Then put the next snippet into your code (for instance fragment):
File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(),
getActivity().getApplicationContext().getPackageName() +
".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
Created an overall rehauled and fail-safe implementation from all comments and suggestions:
# collect stats about the dir
- name: check directory exists
stat:
path: '{{ directory_path }}'
register: dir_to_delete
# delete directory if condition is true
- name: purge {{directory_path}}
file:
state: absent
path: '{{ directory_path }}'
when: dir_to_delete.stat.exists and dir_to_delete.stat.isdir
# create directory if deleted (or if it didn't exist at all)
- name: create directory again
file:
state: directory
path: '{{ directory_path }}'
when: dir_to_delete is defined or dir_to_delete.stat.exist == False
From the man file:
When
--cached
is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index.
So, for a single file:
git rm --cached mylogfile.log
and for a single directory:
git rm --cached -r mydirectory
Basically, there isn't one. Embedded refers to the hosting computer / microcontroller, not the language. The embeddded system might have fewer resources and interfaces for the programmer to play with, and hence C will be used differently, but it is still the same ISO defined language.
You can move Application.java
to a folder under the java.
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
Do keep in mind that the file.getContentType
could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.
For me maven was downloading the dependency but was unable to add it to the classpath. I saw my .classpath of the project,it didnt have any maven-related entry. When I added
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
the issue got resolved for me.
If this error occurred in SpringBoot when you are trying to use log4j2 then do these steps:
This error occurred because logback override the log4j2 changes. SO if you want to use log4j2 then you have to remove logback library and dependencies.
Hope this will help someone.
In your comparison between IEnumerable<int>
and IEnumerable<double>
you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var
is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var
is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var
anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;
In case you want to return a custom defined status code, you can use the ResponseEntity as here:
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
int customHttpStatusValue = 499;
Foo foo = bar();
return ResponseEntity.status(customHttpStatusValue).body(foo);
}
The CustomHttpStatusValue could be any integer within or outside of standard HTTP Status Codes.
I use the InvokeOnClick()
method. It takes two arguments: Control and EventArgs. If you need the EventArgs, then create an instance of it and pass it in, else use InvokeOnClick(controlToClick, null);
. You can use a variety of Mouse event related arguments that derive from EventArgs such as MouseEventArgs.
If you need the path
and thedomain
for each cookie, which get_dict()
is not exposes, you can parse the cookies manually, for instance:
[
{'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
for c in session.cookies
]
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
I've created SQLite databases up to 3.5GB in size with no noticeable performance issues. If I remember correctly, I think SQLite2 might have had some lower limits, but I don't think SQLite3 has any such issues.
According to the SQLite Limits page, the maximum size of each database page is 32K. And the maximum pages in a database is 1024^3. So by my math that comes out to 32 terabytes as the maximum size. I think you'll hit your file system's limits before hitting SQLite's!
Here is a method that will add a sticky footer that doesn't require any additional CSS or Javascript other than what's already in Bootstrap and won't interfere with your current footer.
Example here: Easy Sticky Footer
Just copy and paste this directly into your code. No fuss no muss.
<div class="navbar navbar-default navbar-fixed-bottom">
<div class="container">
<p class="navbar-text pull-left">© 2014 - Site Built By Mr. M.
<a href="http://tinyurl.com/tbvalid" target="_blank" >HTML 5 Validation</a>
</p>
<a href="http://youtu.be/zJahlKPCL9g" class="navbar-btn btn-danger btn pull-right">
<span class="glyphicon glyphicon-star"></span> Subscribe on YouTube</a>
</div>
</div>
Try adding this:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
By looking at your debug logs, you can notice that the failing PhpMailer log shows this:
(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)
While your successful PEAR log shows this:
DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead
My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.
You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.
I found this solution when I faced the same situation. Hope this helps you too.
WORKING:
$("#ContentPlaceHolder1_txtNombre").keyup(function () {
var txt = $(this).val();
$('.column').each(function () {
$(this).show();
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
$(this).hide();
}
});
//}
});
This worked for me:
sheet.Cells[currentRow, ++currentColumn] = "'" + theDate.ToString("MM/dd/yy");
Note the tick mark added before the date.
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
Here my working code using in React with Bootstrap
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<style>
@media (min-width: 768px) and (max-width: 1000px) {
.navbar-collapse.collapse {
display: none !important;
}
.navbar-toggle{
display: block !important;
}
.navbar-header{
float: none;
}
}
</style>
I was having the same problem. I ended up going into the subdirectory that was "not staged for commit" and adding, committing and pushing from there. after that, went up one level to master directory and was able to push correctly.
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
The posted answers are very good when working with data.frame
s. However, these tasks can be pretty inefficient from a memory perspective. With large data, removing a column can take an unusually long amount of time and/or fail due to out of memory
errors. Package data.table
helps address this problem with the :=
operator:
library(data.table)
> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
b c
[1,] 1 1
I should put together a bigger example to show the differences. I'll update this answer at some point with that.
If you want to check if the string contains several specifics words, you can do:
$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat");
$string = "a string with the word ivoire";
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches);
if ($matchFound) {
echo "a bad word has been found";
}
else {
echo "your string is okay";
}
This is useful to avoid spam when sending emails for example.
If you have a file of your font, then you will need to add more formats of that font for other browsers.
For this purpose I use font generator like Fontsquirrel it provides all the font formats & its @font-face CSS, you will only need to just drag & drop it into your CSS file.
Context
provides information about the Actvity
or Application
to newly created components.
Relevant Context
should be provided to newly created components (whether application context or activity context)
Since Activity
is a subclass of Context
, one can use this
to get that activity's context
You may have to concatenate the % signs with your parameter, e.g.:
LIKE '%' || @query || '%'
Edit: Actually, that may not make any sense at all. I think I may have misunderstood your problem.
If you only want to upgrade one specific package called somepackage
, the command you should use in recent versions of pip is
pip install --upgrade --upgrade-strategy only-if-needed somepackage
This is very useful when you develop an application in Django that currently will only work with a specific version of Django (say Django=1.9.x) and want to upgrade some dependent package with a bug-fix/new feature and the upgraded package depends on Django (but it works with, say, any version of Django after 1.5).
The default behavior of pip install --upgrade django-some-package
would be to upgrade Django to the latest version available which could otherwise break your application, though with the --upgrade-strategy only-if-needed
dependent packages will now only be upgraded as necessary.
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
The original, and standard, implementation of Python is usually called CPython
when
you want to contrast it with the other options (and just plain “Python” otherwise). This
name comes from the fact that it is coded in portable ANSI C language code
. This is
the Python that you fetch from http://www.python.org, get with the ActivePython and
Enthought distributions, and have automatically on most Linux and Mac OS X machines.
If you’ve found a preinstalled version of Python on your machine, it’s probably
CPython
, unless your company or organization is using Python in more specialized
ways.
Unless you want to script
Java
or.NET
applications with Python or find the benefits ofStackless
orPyPy
compelling, you probably want to use the standardCPython
system. Because it is the reference implementation of the language, it tends to run the fastest, be the most complete, and be more up-to-date and robust than the alternative systems.
When to use Maps instead of plain JavaScript Objects ?
The plain JavaScript Object { key: 'value' } holds structured data. But plain JS object has its limitations :
Only strings and symbols can be used as keys of Objects. If we use any other things say, numbers as keys of an object then during accessing those keys we will see those keys will be converted into strings implicitly causing us to lose consistency of types. const names= {1: 'one', 2: 'two'}; Object.keys(names); // ['1', '2']
There are chances of accidentally overwriting inherited properties from prototypes by writing JS identifiers as key names of an object (e.g. toString, constructor etc.)
Another object cannot be used as key of an object, so no extra information can be written for an object by writing that object as key of another object and value of that another object will contain the extra information
Objects are not iterators
The size of an object cannot be determined directly
These limitations of Objects are solved by Maps but we must consider Maps as complement for Objects instead of replacement. Basically Map is just array of arrays but we must pass that array of arrays to the Map object as argument with new keyword otherwise only for array of arrays the useful properties and methods of Map aren't available. And remember key-value pairs inside the array of arrays or the Map must be separated by commas only, no colons like in plain objects.
3 tips to decide whether to use a Map or an Object :
Use maps over objects when keys are unknown until run time because keys formed by user input or unknowingly can break the code which uses the object if those keys overwrite the inherited properties of the object, so map is safer in those cases. Also use maps when all keys are the same type and all maps are the same type.
Use maps if there is a need to store primitive values as keys.
Use objects if we need to operate on individual elements.
Benefits of using Maps are :
1. Map accepts any key type and preserves the type of key :
We know that if the object's key is not a string or symbol then JS implicitly transforms it into a string. On the contrary, Map accepts any type of keys : string, number, boolean, symbol etc. and Map preserves the original key type. Here we will use number as key inside a Map and it will remain a number :
const numbersMap= new Map();
numbersMap.set(1, 'one');
numbersMap.set(2, 'two');
const keysOfMap= [...numbersMap.keys()];
console.log(keysOfMap); // [1, 2]
Inside a Map we can even use an entire object as a key. There may be times when we want to store some object related data, without attaching this data inside the object itself so that we can work with lean objects but want to store some information about the object. In those cases we need to use Map so that we can make Object as key and related data of the object as value.
const foo= {name: foo};
const bar= {name: bar};
const kindOfMap= [[foo, 'Foo related data'], [bar, 'Bar related data']];
But the downside of this approach is the complexity of accessing the value by key, as we have to loop through the entire array to get the desired value.
function getBy Key(kindOfMap, key) {
for (const [k, v] of kindOfMap) {
if(key === k) {
return v;
}
}
return undefined;
}
getByKey(kindOfMap, foo); // 'Foo related data'
We can solve this problem of not getting direct access to the value by using a proper Map.
const foo= {name: 'foo'};
const bar= {name: 'bar'};
const myMap= new Map();
myMap.set(foo, 'Foo related data');
myMap.set(bar, 'Bar related data');
console.log(myMap.get(foo)); // 'Foo related data'
We could have done this using WeakMap, just have to write, const myMap= new WeakMap( ). The differences between Map and WeakMap are that WeakMap allows for garbage collection of keys (here objects) so it prevents memory leaks, WeakMap accepts only objects as keys, and WeakMap has reduced set of methods.
2. Map has no restriction over key names :
For plain JS objects we can accidentally overwrite property inherited from the prototype and it can be dangerous. Here we will overwrite the toString( ) property of the actor object :
const actor= {
name: 'Harrison Ford',
toString: 'Actor: Harrison Ford'
};
Now let's define a fn isPlainObject( ) to determine if the supplied argument is a plain object and this fn uses toString( ) method to check it :
function isPlainObject(value) {
return value.toString() === '[object Object]';
}
isPlainObject(actor); // TypeError : value.toString is not a function
// this is because inside actor object toString property is a string instead of inherited method from prototype
The Map does not have any restrictions on the key names, we can use key names like toString, constructor etc. Here although actorMap object has a property named toString but the method toString( ) inherited from prototype of actorMap object works perfectly.
const actorMap= new Map();
actorMap.set('name', 'Harrison Ford');
actorMap.set('toString', 'Actor: Harrison Ford');
function isMap(value) {
return value.toString() === '[object Map]';
}
console.log(isMap(actorMap)); // true
If we have a situation where user input creates keys then we must take those keys inside a Map instead of a plain object. This is because user may choose a custom field name like, toString, constructor etc. then such key names in a plain object can potentially break the code that later uses this object. So the right solution is to bind the user interface state to a map, there is no way to break the Map :
const userCustomFieldsMap= new Map([['color', 'blue'], ['size', 'medium'], ['toString', 'A blue box']]);
3. Map is iterable :
To iterate a plain object's properties we need Object.entries( ) or Object.keys( ). The Object.entries(plainObject) returns an array of key value pairs extracted from the object, we can then destructure those keys and values and can get normal keys and values output.
const colorHex= {
'white': '#FFFFFF',
'black': '#000000'
}
for(const [color, hex] of Object.entries(colorHex)) {
console.log(color, hex);
}
//
'white' '#FFFFFF'
'black' '#000000'
As Maps are iterable that's why we do not need entries( ) methods to iterate over a Map and destructuring of key, value array can be done directly on the Map as inside a Map each element lives as an array of key value pairs separated by commas.
const colorHexMap= new Map();
colorHexMap.set('white', '#FFFFFF');
colorHexMap.set('black', '#000000');
for(const [color, hex] of colorHexMap) {
console.log(color, hex);
}
//'white' '#FFFFFF' 'black' '#000000'
Also map.keys( ) returns an iterator over keys and map.values( ) returns an iterator over values.
4. We can easily know the size of a Map
We cannot directly determine the number of properties in a plain object. We need a helper fn like, Object.keys( ) which returns an array with keys of the object then using length property we can get the number of keys or the size of the plain object.
const exams= {'John Rambo': '80%', 'James Bond': '60%'};
const sizeOfObj= Object.keys(exams).length;
console.log(sizeOfObj); // 2
But in the case of Maps we can have direct access to the size of the Map using map.size property.
const examsMap= new Map([['John Rambo', '80%'], ['James Bond', '60%']]);
console.log(examsMap.size);
Try this:
$Wsdl = 'http://xxxx.xxx.xx/webservice3.asmx?WSDL';
libxml_disable_entity_loader(false); //adding this worked for me
$Client = new SoapClient($Wsdl);
//Code...
You are correct - here is a fully working example - you'll see that var result
is implicitly a string because the return type is specified on the greet()
function. Change the type to number
and you'll get warnings.
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() : string {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("Hi");
var result = greeter.greet();
Here is the number example - you'll see red squiggles in the playground editor if you try this:
greet() : number {
return "Hello, " + this.greeting;
}
Function
CREATE FUNCTION dbo.SplitToRows (@column varchar(100), @separator varchar(10))
RETURNS @rtnTable TABLE
(
ID int identity(1,1),
ColumnA varchar(max)
)
AS
BEGIN
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)
set @column = ltrim(rtrim(@column))
WHILE @position<=len(@column)
BEGIN
set @endAt = CHARINDEX(@separator,@column,@position)
if(@endAt=0)
begin
Insert into @rtnTable(ColumnA) Select substring(@column,@position,len(@column)-@position)
break;
end
set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)
Insert into @rtnTable(ColumnA) select @tempString
set @position=@endAt+1;
END
return
END
Use case
select * from dbo.SplitToRows('T14; p226.0001; eee; 3554;', ';')
Or just a select with multiple result set
DECLARE @column varchar(max)= '1234; 4748;abcde; 324432'
DECLARE @separator varchar(10) = ';'
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)
set @column = ltrim(rtrim(@column))
WHILE @position<=len(@column)
BEGIN
set @endAt = CHARINDEX(@separator,@column,@position)
if(@endAt=0)
begin
Select substring(@column,@position,len(@column)-@position)
break;
end
set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)
select @tempString
set @position=@endAt+1;
END
You can use:
MYSTRING="abc123"
MYLENGTH=$(printf "%s" "$MYSTRING" | wc -c)
wc -c
or wc --bytes
for byte counts = Unicode characters are counted with 2, 3 or more bytes.wc -m
or wc --chars
for character counts = Unicode characters are counted single until they use more bytes.Objects, {}
in JavaScript does not have the method .map()
. It's only for Arrays, []
.
So in order for your code to work change data.map()
to data.products.map()
since products
is an array which you can iterate upon.
For anyone who may arrive here at a later time....Nothing worked for me. All my assemblies were fine. I had an app config in one of my Visual Studio Projects that shouldn't have been there. So make sure your app config file is needed.
I deleted the extra app config and it worked.
StartDate = moment(StartDate).format('MM-YYYY');
...and MySQL date format:
StartDate = moment(StartDate).format('YYYY-MM-DD');
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
In case you're interested in bundling automatically your scripts separately from vendors ones:
var webpack = require('webpack'),
pkg = require('./package.json'), //loads npm config file
html = require('html-webpack-plugin');
module.exports = {
context : __dirname + '/app',
entry : {
app : __dirname + '/app/index.js',
vendor : Object.keys(pkg.dependencies) //get npm vendors deps from config
},
output : {
path : __dirname + '/dist',
filename : 'app.min-[hash:6].js'
},
plugins: [
//Finally add this line to bundle the vendor code separately
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
new html({template : __dirname + '/app/index.html'})
]
};
You can read more about this feature in official documentation.
You can make a pretty nice X with CSS gradients:
demo: https://codepen.io/JasonWoof/pen/rZyRKR
code:
<span class="close-x"></span>
<style>
.close-x {
display: inline-block;
width: 20px;
height: 20px;
border: 7px solid #f56b00;
background:
linear-gradient(45deg, rgba(0,0,0,0) 0%,rgba(0,0,0,0) 43%,#fff 45%,#fff 55%,rgba(0,0,0,0) 57%,rgba(0,0,0,0) 100%),
linear-gradient(135deg, #f56b00 0%,#f56b00 43%,#fff 45%,#fff 55%,#f56b00 57%,#f56b00 100%);
}
</style>
For some odd reason this part
$el.empty(); // remove old options
from CMS solution didn't work for me, so instead of that I've simply used this
el.html(' ');
And it's works. So my working code now looks like that:
var newOptions = {
"Option 1":"option-1",
"Option 2":"option-2"
};
var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
wait - wait method tells the current thread to give up monitor and go to sleep.
notify - Wakes up a single thread that is waiting on this object's monitor.
So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.
Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class. To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
python -V
http://docs.python.org/using/cmdline.html#generic-options
--version
may also work (introduced in version 2.5)
String active_network = ((ConnectivityManager)
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo().getSubtypeName();
should get you the network name
You can decode it to str with receive.decode('utf_8')
.
One way to do this is to insert a dummy column with the sums in order to sort:
In [10]: sum_B_over_A = df.groupby('A').sum().B
In [11]: sum_B_over_A
Out[11]:
A
bar 0.253652
baz -2.829711
foo 0.551376
Name: B
in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)
In [13]: df
Out[13]:
A B C sum_B_over_A
0 foo 1.624345 False 0.551376
1 bar -0.611756 True 0.253652
2 baz -0.528172 False -2.829711
3 foo -1.072969 True 0.551376
4 bar 0.865408 False 0.253652
5 baz -2.301539 True -2.829711
In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]:
A B C sum_B_over_A
5 baz -2.301539 True -2.829711
2 baz -0.528172 False -2.829711
1 bar -0.611756 True 0.253652
4 bar 0.865408 False 0.253652
3 foo -1.072969 True 0.551376
0 foo 1.624345 False 0.551376
and maybe you would drop the dummy row:
In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
The RemoveAll()
methods accept a Predicate<T>
delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll
will remove from the collection all the T
instances that return True with the predicate applied.
C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll
method (and not only this one…). You can use:
Lambda expressions
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
Anonymous methods
vehicles.RemoveAll(delegate(Vehicle v) {
return v.EnquiryID == 123;
});
Normal methods
vehicles.RemoveAll(VehicleCustomPredicate);
private static bool
VehicleCustomPredicate (Vehicle v) {
return v.EnquiryID == 123;
}
I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..
public string DataTableToCSV(DataTable dt)
{
StringBuilder sb = new StringBuilder();
if (dt == null)
return "";
try {
// Create the header row
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
// Append column name in quotes
sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
// Add carriage return and linefeed if last column, else add comma
sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in dt.Rows) {
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
// Append value in quotes
//sb.Append("""" & row.Item(i) & """")
// OR only quote items that that are equivilant to strings
sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);
// Append CR+LF if last field, else add Comma
sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
}
return sb.ToString;
} catch (Exception ex) {
// Handle the exception however you want
return "";
}
}
Single line comments start with a hash symbol, everything to the right of the #
will be ignored:
# Comment Here
In PowerShell 2.0 and above multi-line block comments can be used:
<#
Multi
Line
#>
You could use block comments to embed comment text within a command:
Get-Content -Path <# configuration file #> C:\config.ini
Note: Because PowerShell supports Tab Completion you need to be careful about copying and pasting Space + TAB
before comments.
Straight after the $wpdb->insert()
that does the insert, do this:
$lastid = $wpdb->insert_id;
More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
The new version of Qt Creator also has a "profile" build option between debug and release. Here's how I'm detecting that:
CONFIG(debug, debug|release) { DEFINES += DEBUG_MODE }
else:CONFIG(force_debug_info) { DEFINES += PROFILE_MODE }
else { DEFINES += RELEASE_MODE }
You use std::find
from <algorithm>
, which works equally well for std::list
and std::vector
. std::vector
does not have its own search/find function.
#include <list>
#include <algorithm>
int main()
{
std::list<int> ilist;
ilist.push_back(1);
ilist.push_back(2);
ilist.push_back(3);
std::list<int>::iterator findIter = std::find(ilist.begin(), ilist.end(), 1);
}
Note that this works for built-in types like int
as well as standard library types like std::string
by default because they have operator==
provided for them. If you are using using std::find
on a container of a user-defined type, you should overload operator==
to allow std::find
to work properly: EqualityComparable
concept
One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.
In [28]: im = Image.new(mode='RGB',size=(240,240))
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10))
In [35]: draw.textsize(t1, font), draw.textsize(t2, font) # handles multi-lined text
Out[35]: ((52, 10), (27, 24))
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
Did you check your Project Properties -> Project Facets
panel? (From that post)
A WTP project is composed of multiple units of functionality (known as facets).
The Java facet version needs to always match the java compiler compliance level.
The best way to change java level is to use the Project Facets properties panel as that will update both places at the same time.
The "
Project->Preferences->Project Facets
" stores its configuration in this file, "org.eclipse.wst.common.project.facet.core.xml
", under the ".settings
" directory.The content might look like this
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="WebSphere Application Server v6.1"/>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.java" version="5.0"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jsf.ibm" version="7.0"/>
<installed facet="jsf.base" version="7.0"/>
<installed facet="web.jstl" version="1.1"/>
</faceted-project>
Check also your Java compliance level:
You can probably start a Service
here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
UDPATE
You can use START_STICKY
to make your Service running continuously.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
SELECT * INTO newtable
from Oldtable
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
http://localhost
The above host is already occupied by the emulator in which you are running the code. If you want to access the local host of your computer than use the IP Address as http://10.0.2.2:8080/
.
For more details, please refer this link.
I ran into the same situation where commands such as git diff origin
or git diff origin master
produced the error reported in the question, namely Fatal: ambiguous argument...
To resolve the situation, I ran the command
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
to set refs/remotes/origin/HEAD to point to the origin/master branch.
Before running this command, the output of git branch -a
was:
* master
remotes/origin/master
After running the command, the error no longer happened and the output of git branch -a
was:
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
(Other answers have already identified that the source of the error is HEAD not being set for origin. But I thought it helpful to provide a command which may be used to fix the error in question, although it may be obvious to some users.)
Additional information:
For anybody inclined to experiment and go back and forth between setting and unsetting refs/remotes/origin/HEAD, here are some examples.
To unset:
git remote set-head origin --delete
To set:
(additional ways, besides the way shown at the start of this answer)
git remote set-head origin master
to set origin/head explicitly
OR
git remote set-head origin --auto
to query the remote and automatically set origin/HEAD to the remote's current branch.
References:
git remote --help
see set-head descriptiongit symbolic-ref --help
you can also refactor your solution removing the first loop:
Set<Integer> set = new HashSet<Integer>();
Collection<Integer> removeCandidates = new LinkedList<Integer>(set);
for(Integer element : set)
if(element % 2 == 0)
removeCandidates.add(element);
set.removeAll(removeCandidates);
Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.
Option 1: Create a new thread rather than trying to restart.
Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.
Edit based on comment:
To "kill" the thread you can do something like the following.
yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop
As per matplotlib's suggestion for image grids:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for ax, im in zip(grid, image_data):
# Iterating over the grid returns the Axes.
ax.imshow(im)
plt.show()
import urllib2
Traceback (most recent call last):
File "", line 1, in
import urllib2
ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.
Here is the PEP link (Python Enhancement Proposals )
http://www.python.org/dev/peps/pep-3108/#urllib-package
so instead of urllib2 you can now import urllib.request and then use it like this:
>>>import urllib.request
>>>urllib.request.urlopen('http://www.placementyogi.com')
Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x
reCAPTCHA is a free antibot service that helps digitize books
It has been aquired by Google (in 2009):
Also see
Use Expanded to fit the listview in the column
Column(
children: <Widget>[
Text('Data'),
Expanded(
child: ListView()
)
],
)
You can use these 2 methods to get device token with firebase but the second one method is more efficient way..
FirebaseInstallations.getInstance().getToken(false).addOnCompleteListener(new OnCompleteListener<InstallationTokenResult>() {
@Override
public void onComplete(@NonNull Task<InstallationTokenResult> task) {
if(!task.isSuccessful()){
return;
}
// Get new Instance ID token
DeviceToken = task.getResult().getToken();
}
});
Second method : you can also use this one
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
DeviceToken= task.getResult();
}
});
As other answers point out, there are many and good reasons why this class
was made generic. However there are plenty of times that you don't have any way of knowing the generic type to use with Class<T>
. In these cases, you can simply ignore the yellow eclipse warnings or you can use Class<?>
... That's how I do it ;)
Thank for the question. But I have found my own solution to this problem. At first, I created a method
public T GetSettingsWithDictionary<T>() where T:new()
{
IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
.AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();
var instance = new T();
foreach (var property in typeof(T).GetProperties())
{
if (property.PropertyType == typeof(Dictionary<string, string>))
{
property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
break;
}
}
return instance;
}
Then I used this method to produce an instance of a class
var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();
I have the next declaration of class
public class AuthMongoConnectionStrings
{
public Dictionary<string, string> ConnectionStrings { get; set; }
}
and I store my setting in App.config
<configuration>
<AuthMongoConnectionStrings
First="first"
Second="second"
Third="33" />
</configuration>
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
function_that_needs_strings(*my_list) # works!
The compiler wants you to write this:
private static List<String> list = new ArrayList<String>();
because otherwise, you could add any type you like into list
, making the instantiation as new ArrayList<String>()
pointless. Java generics are a compile-time feature only, so an object created with new ArrayList<String>()
will happily accept Integer
or JFrame
elements if assigned to a reference of the "raw type" List
- the object itself knows nothing about what types it's supposed to contain, only the compiler does.
If you use kotlin, it's really simple.
In your RecyclerAdapter class
userV.invalidateRecycler()
holder.card_User.setCardBackgroundColor(Color.parseColor("#3eb1ae").withAlpha(60))
In your fragment or Activity
override fun invalidateRecycler() {
if (v1.recyclerCompanies.childCount > 0) {
v1.recyclerCompanies.childrenRecursiveSequence().iterator().forEach { card ->
if (card is CardView) {
card.setCardBackgroundColor(Color.WHITE)
}
}
}
}
I had this problem and couldn't solve it in Java code. The problem was with my xml.
I was trying to add a textView to a container, but had wrapped the textView inside a LinearLayout.
This was the original xml file:
<?xml version="1.0" encoding="utf-8"?>_x000D_
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:orientation="vertical"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent">_x000D_
_x000D_
<TextView xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:id="@android:id/text1"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceListItemSmall"_x000D_
android:gravity="center_vertical"_x000D_
android:paddingLeft="16dp"_x000D_
android:paddingRight="16dp"_x000D_
android:textColor="#fff"_x000D_
android:background="?android:attr/activatedBackgroundIndicator"_x000D_
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>_x000D_
_x000D_
</LinearLayout>
_x000D_
Now with the LinearLayout removed:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:id="@android:id/text1"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceListItemSmall"_x000D_
android:gravity="center_vertical"_x000D_
android:paddingLeft="16dp"_x000D_
android:paddingRight="16dp"_x000D_
android:textColor="#fff"_x000D_
android:background="?android:attr/activatedBackgroundIndicator"_x000D_
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
_x000D_
This didn't seem like much to me but it did the trick, and I didn't change my Java code at all. It was all in the xml.
Yes, it's possible, the syntax is curl [protocol://]<host>[:port]
, for example:
curl example.com:1234
If you're using Bash, you can also use pseudo-device /dev
files to open a TCP connection, e.g.:
exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.
See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).
with many functions in matlab, you don't need to iterate at all.
for example, to multiply by it's position in the list:
m = [1:numel(list)]';
elm = list.*m;
vectorized algorithms in matlab are in general much faster.
In ES6, it is also possible to iterate over the values of an object using the for..of
loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:
for..of
loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.Here is an example:
const obj1 = {
a: 5,
b: "hello",
[Symbol.iterator]: function() {
const thisObj = this;
let index = 0;
return {
next() {
let keys = Object.keys(thisObj);
return {
value: thisObj[keys[index++]],
done: (index > keys.length)
};
}
};
}
};
Now we can use the for..of
loop:
for (val of obj1) {
console.log(val);
} // 5 hello
First of all, it is a bad design, if you need something like that, it is good idea to refactor, e.g. by renaming the method. Java allows calling of overriden method using the "super" keyword, but only one level up in the hierarchy, I am not sure, maybe Scala and some other JVM languages support it for any level.
Just Cast Column As Varchar(Size)
If both Column are numeric then use code below.
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
What will be the size of col3
it will be 40 or something else
My answer is just a flavor of the same. But I tested it with serializing a zipped content and it worked. So I can trust this solution unlike the one offered first (that use readLine) because it will ignore line breaks and corrupt the input.
/*********************************************************************************************
* From CLOB to String
* @return string representation of clob
*********************************************************************************************/
private String clobToString(java.sql.Clob data)
{
final StringBuilder sb = new StringBuilder();
try
{
final Reader reader = data.getCharacterStream();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
sb.append((char)b);
}
br.close();
}
catch (SQLException e)
{
log.error("SQL. Could not convert CLOB to string",e);
return e.toString();
}
catch (IOException e)
{
log.error("IO. Could not convert CLOB to string",e);
return e.toString();
}
return sb.toString();
}
The latest version of Notepad++ x64 v7.6.2 on Windows 10 already moved the plugin manager to 'Plugins Admin'.
Old versions of Notepad++ and plugin manager won't work.
double x;
char *s;
s = " -2309.12E-15";
x = atof(s); /* x = -2309.12E-15 */
printf("x = %4.4f\n",x);
No, but you can write your own:
public static bool Between(this int num, int lower, int upper, bool inclusive = false)
{
return inclusive
? lower <= num && num <= upper
: lower < num && num < upper;
}
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.
I like assylias' answer, however I would refactor it as follows:
Sub test()
Dim origNum As String
Dim creditOrDebit As String
origNum = "30062600006"
creditOrDebit = "D"
If creditOrDebit = "D" Then
If origNum = "006260006" Then
MsgBox "OK"
ElseIf origNum = "30062600006" Then
MsgBox "OK"
End If
End If
End Sub
This might save you some CPU cycles since if creditOrDebit
is <> "D"
there is no point in checking the value of origNum
.
I used the following procedure to test my theory that my procedure is faster:
Public Declare Function timeGetTime Lib "winmm.dll" () As Long
Sub DoTests2()
Dim startTime1 As Long
Dim endTime1 As Long
Dim startTime2 As Long
Dim endTime2 As Long
Dim i As Long
Dim msg As String
Const numberOfLoops As Long = 10000
Const origNum As String = "006260006"
Const creditOrDebit As String = "D"
startTime1 = timeGetTime
For i = 1 To numberOfLoops
If creditOrDebit = "D" Then
If origNum = "006260006" Then
' do something here
Debug.Print "OK"
ElseIf origNum = "30062600006" Then
' do something here
Debug.Print "OK"
End If
End If
Next i
endTime1 = timeGetTime
startTime2 = timeGetTime
For i = 1 To numberOfLoops
If (origNum = "006260006" Or origNum = "30062600006") And _
creditOrDebit = "D" Then
' do something here
Debug.Print "OK"
End If
Next i
endTime2 = timeGetTime
msg = "number of iterations: " & numberOfLoops & vbNewLine
msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
" ms" & vbNewLine
msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
" ms"
MsgBox msg
End Sub
I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)
After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit
is <>"D"
, my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.
And that is why I refactored it - to short-circuit the logic so that origNum
doesn't need to be evaluated when creditOrDebit <> "D"
.
At this point, the rest depends on the OP's spreadsheet. If creditOrDebit
is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit
has a wide range of possible values, and D
is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.
If you have both date and time information in the numeric value, then use as.POSIXct
. Data.table package IDateTime format is such a case. If you use fwrite
to save a file, the package automatically converts date-times to idatetime format which is unix time. To convert back to normal format following can be done.
Example: Let's say you have a unix time stamp with date and time info: 1442866615
> as.POSIXct(1442866615,origin="1970-01-01")
[1] "2015-09-21 16:16:54 EDT"
Yes; all primitive numeric types default to 0
.
However, calculations involving floating-point types (double
and float
) can be imprecise, so it's usually better to check whether it's close to 0
:
if (Math.abs(foo.x) < 2 * Double.MIN_VALUE)
You need to pick a margin of error, which is not simple.
I started using maven on my machine first time in while. Got this error: Could not transfer artifact from/to central (https://repo.maven.apache.org/maven2) No such file or directory
Cleaned up ~/.m2/repository directory. Don't experience this problem again
The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.
It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.
As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.
.bar {
background - color: blue;
height: 40 px;
width: 40 px;
border - style: solid;
border - right - width: 1300 px;
border - radius: 40 px;
animation - name: Load;
animation - duration: 11 s;
position: relative;
animation - iteration - count: 1;
animation - fill - mode: forwards;
}
@keyframes Load {
100 % {
width: 1300 px;border - right - width: 5;
}
first convert your array too JSON
while($query->fetch()){
$col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
then vonvert back it to array
foreach($col as &$array){
$array = json_decode($array,true);
}
good luck
Here is the simplest example that has the key lines of code:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
plt.imshow(H, interpolation='none')
plt.show()
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
This can be done in one line, there's no need for a loop, be it a for-loop or an apply. Use unlist() instead :
# testdata
Df <- data.frame(
x = as.factor(sample(1:5,30,r=TRUE)),
y = as.factor(sample(1:5,30,r=TRUE)),
z = as.factor(sample(1:5,30,r=TRUE)),
w = as.factor(sample(1:5,30,r=TRUE))
)
##
Df[,c("y","w")] <- as.numeric(as.character(unlist(Df[,c("y","w")])))
str(Df)
Edit : for your code, this becomes :
id <- c(1,3:ncol(stats)))
stats[,id] <- as.numeric(as.character(unlist(stats[,id])))
Obviously, if you have a one-column data frame and you don't want the automatic dimension reduction of R to convert it to a vector, you'll have to add the drop=FALSE
argument.
Update 10/11/2020 to reflect the latest brew changes.
Brew
already provide a command to uninstall itself (this will remove everything you installed with Homebrew):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
If you failed to run this command due to permission (like run as second user), run again with sudo
Then you can install again:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
A more to-the-point CHANGELOG.
git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B
I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.
my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
:type=> 'n:n', :msgheader => from}, :body=>[]}
my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }
my_hash_full = my_hash_static[:body].push my_hash_dynamic
Here is my version, which parses sections and populates a global associative array g_iniProperties with it. Note that this works only with bash v4.2 and higher.
function parseIniFile() { #accepts the name of the file to parse as argument ($1)
#declare syntax below (-gA) only works with bash 4.2 and higher
unset g_iniProperties
declare -gA g_iniProperties
currentSection=""
while read -r line
do
if [[ $line = [* ]] ; then
if [[ $line = [* ]] ; then
currentSection=$(echo $line | sed -e 's/\r//g' | tr -d "[]")
fi
else
if [[ $line = *=* ]] ; then
cleanLine=$(echo $line | sed -e 's/\r//g')
key=$currentSection.$(echo $cleanLine | awk -F: '{ st = index($0,"=");print substr($0,0,st-1)}')
value=$(echo $cleanLine | awk -F: '{ st = index($0,"=");print substr($0,st+1)}')
g_iniProperties[$key]=$value
fi
fi;
done < $1
}
And here is a sample code using the function above:
parseIniFile "/path/to/myFile.ini"
for key in "${!g_iniProperties[@]}"; do
echo "Found key/value $key = ${g_iniProperties[$key]}"
done
Unless this is a one-off data conversion, chances are you will benefit from using a calendar table.
Having such a table makes it really easy to filter or aggregate data for non-standard periods in addition to regular ISO weeks. Weeks usually behave a bit differently across companies and the departments within them. As soon as you leave "ISO-land" the built-in date functions can't help you.
create table calender(
day date not null -- Truncated date
,iso_year_week number(6) not null -- ISO Year week (IYYYIW)
,retail_week number(6) not null -- Monday to Sunday (YYYYWW)
,purchase_week number(6) not null -- Sunday to Saturday (YYYYWW)
,primary key(day)
);
You can either create additional tables for "purchase_weeks" or "retail_weeks", or simply aggregate on the fly:
select a.colA
,a.colB
,b.first_day
,b.last_day
from your_table_with_weeks a
join (select iso_year_week
,min(day) as first_day
,max(day) as last_day
from calendar
group
by iso_year_week
) b on(a.iso_year_week = b.iso_year_week)
If you process a large number of records, aggregating on the fly won't make a noticable difference, but if you are performing single-row you would benefit from creating tables for the weeks as well.
Using calendar tables provides a subtle performance benefit in that the optimizer can provide better estimates on static columns than on nested add_months(to_date(to_char()))
function calls.
I have not tried in Selenium, but for Galen test this is working,
var list = driver.findElementByID("periodID"); // this will return web element
list.click(); // this will open the dropdown list.
list.typeText("14w"); // this will select option "14w".
You can try this in selenium, the galen and selenium working are similar.
As a JavaScript/HTML/CSS obfuscator/compressor you can also try Patu Digua.
Though $toInt
is really useful, it was added on mongoDB 4.0, I've run into this same situation in a database running 3.2 which upgrading to use $toInt
was not an option due to some other application incompatibilities, so i had to come up with something else, and actually was surprisingly simple.
If you $project
and $add
zero to your string, it will turn into a number
{
$project : {
'convertedField' : { $add : ["$stringField",0] },
//more fields here...
}
}
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
<td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
refer this https://gist.github.com/ebellinger/4399082
Isn't it this simple?
var result = _(data)
.groupBy(x => x.color)
.map((value, key) => ({color: key, users: value}))
.value();
XML - You can use android:scrollHorizontally
Attribute
Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally).
May be a boolean value, such as "true" or "false".
Prigramacaly - setHorizontallyScrolling(boolean)
Based on this code (which you provided in response to Alex's answer):
Editable newTxt=(Editable)userName1.getText();
String newString = newTxt.toString();
It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:
String newString = userName1.getText().toString();
Use npm outdated to discover dependencies that are out of date.
Use npm update to perform safe dependency upgrades.
Use npm install @latest to upgrade to the latest major version of a package.
Use npx npm-check-updates -u and npm install to upgrade all dependencies to their latest major versions.
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
Integrated Security
and User ID
\ Password
authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID
and Password
from your connection string:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
To connect with specific credentials, remove Integrated Security
:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
Follow the steps via terminal:
after then:
then;
At last type via terminal :
Then follow the commands and you're ready to go.
import csv
def read_cell(x, y):
with open('file.csv', 'r') as f:
reader = csv.reader(f)
y_count = 0
for n in reader:
if y_count == y:
cell = n[x]
return cell
y_count += 1
print (read_cell(4, 8))
This example prints cell 4, 8 in Python 3.
If you are getting this error for a YouTube video, rather than using the full url use the embed url from the share options. It will look like http://www.youtube.com/embed/eCfDxZxTBW4
You may also replace watch?v=
with embed/
so http://www.youtube.com/watch?v=eCfDxZxTBW4
becomes http://www.youtube.com/embed/eCfDxZxTBW4
I don't know if you even need to wrap it. Won't this work?
SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25'
AND date_add('2009-06-25', INTERVAL 4 DAY)
AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);
If your goal is to return both result sets then you'll need to store it some place temporarily.
I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
Javascript Keycodes
Except this detail Colin & Tod's answer is working.
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
Possibly one of the better examples of 'There's More Than One Way To Do It", with or without the help of CPAN.
If you have control over what you get passed as a 'date/time', I'd suggest going the DateTime route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the datetime FAQ for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.
If you're expecting weird freeform stuff, throw it at Date::Parse's str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of Date::Manip.
The direct way as mentioned in the documentation:
composer create-project --prefer-dist laravel/laravel blog "6.*"
Its possible, but not directly.
In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.
In the search menu there is a point "delete bookmarked lines" voila.
I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?
If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake
migrations.
./manage.py migrate <name> --ignore-ghost-migrations --merge --fake
For django version < 1.7 this will create entry in south_migrationhistory
table, you need to delete that entry.
Now you'll be able to revert back the migration easily.
PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.
do like this:
departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
return;
}
I made a small library that lets you easily use a throbber without images.
It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.
// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);
// Start the throbber.
throbber.play();
// Pause the throbber.
throbber.pause();
You're asking it to parse the JSON text something
(not "something"
). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
I noticed that AS transfers too much data from/to HDD. It is very annoying, especially when starting to write a new line of code. So, I think, better will be reinstalling a hard disk with SSD. I have i5 with 6 Gb of memory, and the CPU seldom loads more than 50% even at build time. So, the most weak place is HDD.
Try the following, no extra headers
wget -qO- www.google.com
Note the trailing -
. This is part of the normal command argument for -O
to cat out to a file, but since we don't use >
to direct to a file, it goes out to the shell. You can use -qO-
or -qO -
.
Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname
to display the commit it points to.
In your case you have at least these two alternatives:
Reset the current branch to specific tag:
git reset --hard tagname
Generate revert commit on top to get you to the state of the tag:
git revert tag
This might introduce some conflicts if you have merge commits though.
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
My issue came down to a silly mistake on my part. As I had quickly one day dropped my proxies into a windows *.bat file (http_proxy, https_proxy, and ftp_proxy), I forgot to escape the special characters for the url-encoded domain\user (%5C) and password having the question mark '?' (%3F). That is to say, once you have the encoded command, don't forget to escape the '%' in the bat file command.
I changed
set http_proxy=http://domain%5Cuser:password%3F@myproxy:8080
to
set http_proxy=http://domain%%5Cuser:password%%3F@myproxy:8080
Maybe it's an edge case but hopefully it helps someone.
I got an very helpful advice from Oliver Gierke:
The last exception you get actually indicates a problem with your JPA setup. "Not a managed bean" means not a type the JPA provider is aware of. If you're setting up a Spring based JPA application I'd recommend to configure the "packagesToScan" property on the LocalContainerEntityManagerFactory you have configured to the package that contains your JPA entities. Alternatively you can list all your entity classes in persistence.xml, but that's usually more cumbersome.
The former error you got (NoClassDefFound) indicates the class mentioned is not available on the projects classpath. So you might wanna check the inter module dependencies you have. As the two relevant classes seem to be located in the same module it might also just be an issue with an incomplete deployment to Tomcat (WTP is kind of bitchy sometimes). I'd definitely recommend to run a test for verification (as you already did). As this seems to lead you to a different exception, I guess it's really some Eclipse glitch
Thanks!
For Swift 5.0 and iOS 12
extension UIImage {
func imageResized(to size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
}
use:
let image = #imageLiteral(resourceName: "ic_search")
cell!.search.image = image.imageResized(to: cell!.search.frame.size)
If you have lodash you can use its .get
method
_.get(a, 'b.c.d.e')
or give it a default value
_.get(a, 'b.c.d.e', default)
My answer is somewhat different in approach but includes many of the answers provided here. I would recommend a multipronged approach:
defined('_SOMECONSTANT') or die('Hackers! Be gone!');
HOWEVER the defined or die
approach has a number of failings. Firstly, it is a real pain in the assumptions to test and debug with. Secondly, it involves horrifyingly, mind-numbingly boring refactoring if you change your mind. "Find and replace!" you say. Yes, but how sure are you that it is written exactly the same everywhere, hmmm? Now multiply that with thousands of files... o.O
And then there's .htaccess. What happens if your code is distributed onto sites where the administrator is not so scrupulous? If you rely only on .htaccess to secure your files you're also going to need a) a backup, b) a box of tissues to dry your tears, c) a fire extinguisher to put out the flames in all the hatemail from people using your code.
So I know the question asks for the "easiest", but I think what this calls for is more "defensive coding".
What I suggest is:
require('ifyoulieyougonnadie.php');
(not include()
and as a replacement for defined or die
)In ifyoulieyougonnadie.php
, do some logic stuff - check for different constants, calling script, localhost testing and such - and then implement your die(), throw new Exception, 403
, etc.
I am creating my own framework with two possible entry points - the main index.php (Joomla framework) and ajaxrouter.php (my framework) - so depending on the point of entry, I check for different things. If the request to ifyoulieyougonnadie.php
doesn't come from one of those two files, I know shenanigans are being undertaken!
But what if I add a new entry point? No worries. I just change ifyoulieyougonnadie.php
and I'm sorted, plus no 'find and replace'. Hooray!
What if I decided to move some of my scripts to do a different framework that doesn't have the same constants defined()
? ... Hooray! ^_^
I found this strategy makes development a lot more fun and a lot less:
/**
* Hmmm... why is my netbeans debugger only showing a blank white page
* for this script (that is being tested outside the framework)?
* Later... I just don't understand why my code is not working...
* Much later... There are no error messages or anything!
* Why is it not working!?!
* I HATE PHP!!!
*
* Scroll back to the top of my 100s of lines of code...
* U_U
*
* Sorry PHP. I didn't mean what I said. I was just upset.
*/
// defined('_JEXEC') or die();
class perfectlyWorkingCode {}
perfectlyWorkingCode::nowDoingStuffBecauseIRememberedToCommentOutTheDie();
I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:
$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
$availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
$date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
Start-Sleep -s 2
}
This produces the following output:
2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)
You can hit Ctrl+C
to abort the loop.
So, you can connect to any Windows machine with this command:
Enter-PSSession -ComputerName MyServerName -Credential MyUserName
...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.
That's because itoa
isn't a standard function. Try snprintf
instead.
char str[LEN];
snprintf(str, LEN, "%d", 42);
Abolishing the need for an extra element, along with making the content fit within the document flow rather than being fixed/absolute like other solutions.
Achieved using
.content {
/* this is needed or the background will be offset by a few pixels at the top */
overflow: auto;
position: relative;
}
.content::before {
content: "";
position: fixed;
left: 0;
right: 0;
z-index: -1;
display: block;
background-image: url('https://i.imgur.com/lL6tQfy.png');
background-size:cover;
width: 100%;
height: 100%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
_x000D_
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
_x000D_
EDIT If you are interested in removing the white borders at the edges, use a width and height of 110%
and a left and top of -5%
. This will enlarge your backgrounds a tad - but there should be no solid colour bleeding in from the edges. Thanks Chad Fawcett for the suggestion.
.content {
/* this is needed or the background will be offset by a few pixels at the top */
overflow: auto;
position: relative;
}
.content::before {
content: "";
position: fixed;
top: -5%;
left: -5%;
right: -5%;
z-index: -1;
display: block;
background-image: url('https://i.imgur.com/lL6tQfy.png');
background-size:cover;
width: 110%;
height: 110%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
_x000D_
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
_x000D_
You can bind listeners to one common functions -
$(window).bind("load resize scroll",function(e){
// do stuff
});
Or another way -
$(window).bind({
load:function(){
},
resize:function(){
},
scroll:function(){
}
});
Alternatively, instead of using .bind()
you can use .on()
as bind directly maps to on()
.
And maybe .bind()
won't be there in future jquery versions.
$(window).on({
load:function(){
},
resize:function(){
},
scroll:function(){
}
});
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
strtotime
expects a standard date format, and passes back a timestamp.
You seem to be passing strtotime
a single digit to output a date format from.
You should be using mktime
which takes the date elements as parameters.
$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", mktime(null, null, null, $monthNum));
echo $monthName;
However, the mktime function does not require a leading zero to the month number, so the first line is completely unnecessary, and $result["month"]
can be passed straight into the function.
This can then all be combined into a single line, echoing the date inline.
echo date("F", mktime(null, null, null, $result["month"], 1));
...
Add the following code in build.gradle(Module:app)
android {
......
......
......
buildTypes {
release {
......
......
......
/*The is the code fot the template of release name*/
applicationVariants.all { variant ->
variant.outputs.each { output ->
def formattedDate = new Date().format('yyyy-MM-dd HH-mm')
def newName = "Your App Name " + formattedDate
output.outputFile = new File(output.outputFile.parent, newName)
}
}
}
}
}
And the release build name will be Your App Name 2018-03-31 12-34
If you are using PHP7.0 to install Magento, I suggest to install all extensions by this command
sudo apt-get install php7.0 php7.0-xml php7.0-mcrypt php7.0-curl php7.0-cli php7.0-mysql php7.0-gd libapache2-mod-php7.0 php7.0-intl php7.0-soap php7.0-zip php7.0-bcmath
I need to Google some times to meet Magento requirement.
I think you can replace the PHP version to 7.x if you use another PHP version
And restart Apache is needed to load new extensions
sudo service apache2 restart
this works for me:
cmake -D DBUILD_SHARED_LIBS=ON DBUILD_STATIC_LIBS=ON DBUILD_TESTS=ON ..
Edit: Generally try to avoid doing the below except as a last ditch effort to avoid deadlocks. Read the first comment from Stephen Cleary.
Quick fix from here. Instead of writing:
Task tsk = AsyncOperation();
tsk.Wait();
Try:
Task.Run(() => AsyncOperation()).Wait();
Or if you need a result:
var result = Task.Run(() => AsyncOperation()).Result;
From the source (edited to match the above example):
AsyncOperation will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of AsyncOperation won’t be forced back to the invoking thread.
For me this looks like a useable option since I do not have the option of making it async all the way (which I would prefer).
From the source:
Ensure that the await in the FooAsync method doesn’t find a context to marshal back to. The simplest way to do that is to invoke the asynchronous work from the ThreadPool, such as by wrapping the invocation in a Task.Run, e.g.
int Sync() { return Task.Run(() => Library.FooAsync()).Result; }
FooAsync will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of FooAsync won’t be forced back to the thread that’s invoking Sync().
thanks for answer @Cristian i was getting error
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
i solved this using
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
-----
-----
}
Here is my customized solution.
const inBrowser = typeof window !== 'undefined'
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
const isIE =
UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
const isEdge = UA && /edg/i.test(UA)
const isAndroid = UA && UA.indexOf('android') > 0
const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
const isChrome =
UA &&
/chrome|crios/i.test(UA) &&
!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
const isGoogleBot = UA && /googlebot/i.test(UA)
const isChromium = UA && /chromium/i.test(UA)
const isUcBrowser = UA && /ucbrowser/i.test(UA)
const isSafari =
UA &&
/safari/i.test(UA) &&
!/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
const isOpera = UA && /opr|opera/i.test(UA)
const isMobile =
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
const isSamsung = UA && /samsungbrowser/i.test(UA)
const isIPad = UA && /ipad/.test(UA)
const isIPhone = UA && /iphone/.test(UA)
const isIPod = UA && /ipod/.test(UA)
console.log({
UA,
isAndroid,
isChrome,
isChromium,
isEdge,
isFirefox,
isGoogleBot,
isIE,
isMobile,
isIOS,
isIPad,
isIPhone,
isIPod,
isOpera,
isSafari,
isSamsung,
isUcBrowser,
}
}
I've adopted Crazy Yoghurt's answer to swift's extensions.
extension UILabel {
func boldRange(_ range: Range<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
func boldSubstring(_ substr: String) {
if let text = self.attributedText {
var range = text.string.range(of: substr)
let attr = NSMutableAttributedString(attributedString: text)
while range != nil {
let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
var nsRange = NSMakeRange(start, length)
let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
break
}
range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
}
if let r = range {
boldRange(r)
}
}
}
}
May be there is not good conversion between Range and NSRange, but I didn't found something better.
The "Premature end of script headers" error message is probably the most loathed and common error message you'll find. What the error actually means, is that the script stopped for whatever reason before it returned any output to the web server. A common cause of this for script writers is to fail to set a content type before printing output code. In Perl for example, before printing any HTML it is necessary to tell the Perl script to set the content type to text/html, this is done by sending a header, like so:
print "Content-type: text/html\n\n";
The drop-down is platform-level element, you can't apply CSS to it.
You can overlay an image on top of it using CSS, and call the click event in the element beneath.
This works for me but did not try to handle negatives
public static int roundUp(int numToRound, int multiple) {
if (multiple == 0) {
return 0;
} else if (numToRound % multiple == 0) {
return numToRound;
}
int mod = numToRound % multiple;
int diff = multiple - mod;
return numToRound + diff;
}
In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.
HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.
I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:
I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I'm wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.
However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).
I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).
Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as ".\curl.exe -s google.com", etc.
The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.
I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.
The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.
I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.
There are always numerous ways to accomplish what you are trying to set out to do; it's just a matter of combining the right tools for the job, and many times it boils down to personal preference.
Pointers are not always the same size on the same architecture.
You can read more on the concept of "near", "far" and "huge" pointers, just as an example of a case where pointer sizes differ...
http://en.wikipedia.org/wiki/Intel_Memory_Model#Pointer_sizes
A good way to avoid loading multiple CSS files or to have inline CSS is to hand a class to the body tag depending on the version of Internet Explorer. If you only need general IE hacks, you can do something like this, but it can be extended to be version specific:
<!--[if IE ]><body class="ie"><![endif]-->
<!--[if !IE]>--><body><!--<![endif]-->
Now in your css code, you can simply do:
.ie .abc {
position:absolute;
left:30;
top:-10;
}
This also keeps your CSS files valid, as you do not have to use dirty (and invalid) CSS hacks.
The following code will set the media stream volume to max:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
panel.setStyle("-fx-background-color: #FFFFFF;");
Note that you must put this in the file ".user.ini" in Centos7 rather than "php.ini" which used to work in Centos6. You can put ".user.ini" in any subdirectory in order to affect only that directory.
.user.ini :
max_input_vars = 3000
Tested on Centos7 and PHP 5.6.33.
I run into the same problem, but in my case it was caused by missing (empty) source folder (it exists in original project, but not in GIT repository because it's empty).
After creating the missing folder everything works.
It is very simple just do the following steps:
<activity
android:name=".Test"
android:configChanges="orientation|screenSize"
android:screenOrientation="landscape" >
</activity>
This works for me :
Note: orientation depends on your requitement
I was also facing a similar issue ("no runnable methods..") on running the simplest of simple piece of code (Using @Test, @Before etc.) and found the solution nowhere. I was using Junit4 and Eclipse SDK version 4.1.2. Resolved my problem by using the latest Eclipse SDK 4.2.2. I hope this helps people who are struggling with a somewhat similar issue.
The basic setup of decorators is like this:
InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);
The key issue in this snippet is the value of encoding
. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.
For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.
Most network protocols use a header or other metadata to explicitly note the character encoding.
In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.
Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!
try like below...
CASE
WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate
clock()
returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC
, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:
clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
If you are confused by your setting for client and conn is reseted after restart mysql service. Try these steps (which worked for me):
vi /etc/my.cnf
:wq
[client]
character-sets-dir=/usr/local/mysql/share/mysql/charsets
status;
, you'll find the character-set for 'client' and 'conn' is set to 'utf8'.Check the reference for more info.
I had two methods:
in the <script>
, goes to show, that you can spend hours looking for something that was such a simple mistake.
This is my answer which solved the same problem. Fragment2.java is the fragment class which holds the layout of fragment2.xml.
public void onClick(View v) {
Fragment fragment2 = new Fragement2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
both answers are is incorrect. it should read:
x-=r;
y-=r;
drawOval(x,y,r*2,r*2);
Have you tried logging in as the jenkins user?
Try this:
sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git
Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.
If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?
I tried changing the padding
and margin
and well as the width
and height
, and then finally found that if you just increase the scale it'll work:
input[type=checkbox] {
transform: scale(1.5);
}
readFileSync()
is synchronous and blocks execution until finished. These return their results as return values.
readFile()
are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish.
let's take an example for non-blocking.
following method read a file as a non-blocking way
var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
console.log(data);
});
following is read a file as blocking or synchronous way.
var data = fs.readFileSync(filename);
LOL...If you don't want
readFileSync()
as blocking way then take reference from the following code. (Native)
var fs = require('fs');
function readFileAsSync(){
new Promise((resolve, reject)=>{
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resolve(data);
});
});
}
async function callRead(){
let data = await readFileAsSync();
console.log(data);
}
callRead();
it's mean behind scenes
readFileSync()
work same as above(promise) base.
$('input').on("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
You could use a namedtuple instead of a dict. This is a shorthand for using a data class. Instead of
person = {'name': 'John', 'age': 14}
...do:
from collections import namedtuple
Person = namedtuple('person', ['name', 'age'])
p = Person(name='John', age=14)
p.name # 'John'
This is the same as writing a class that just holds data. In general I would avoid using dicts in django templates because they are awkward.
The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).
There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".
Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".
Currently the recommended method is to use a DialogFragment :
public class MySpinnerDialog extends DialogFragment {
public MySpinnerDialog() {
// use empty constructors. If something is needed use onCreate's
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
_dialog.setMessage("Spinning.."); // set your messages if not inflated from XML
_dialog.setCancelable(false);
return _dialog;
}
}
Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:
FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");
Once your server has responded complete you will dismiss it:
myInstance.dismiss()
Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide
In your package explorer, pull down the menu and select "Filters ...". You can adjust what types of files are shown/hidden there.
Looking at my Red Hat Developer Studio (approximately Eclipse 3.2), I see that the top item in the list is ".* resources" and it is excluded by default.
if you don't want to create a UDF in VBA or you can't, this could be an alternative.
=Cell("Filename",A1)
this will give you the full file name, and from this you could get the user name with something like this:
=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)
This Formula runs only from a workbook saved earlier.
You must start from 4th position because of the first slash from the drive.
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
I recommend setting an alternative location for your npm modules.
npm config set prefix C:\Dev\npm-repository\npm --global
npm config set cache C:\Dev\npm-repository\npm-cache --global
Of course you can set the location to wherever best suits.
This has worked well for me and gets around any permissions issues that you may encounter.
After button click event complete your any task...last line copy and past it...Is's Working Fine...C# in Asp.Net
Page.Header.Controls.Add(new LiteralControl(string.Format(@" <META http-equiv='REFRESH' content=3.1;url={0}> ", Request.Url.AbsoluteUri)));
that is what i do
.navbar-inverse .navbar-inner {
background-color: #E27403; /* it's flat*/
background-image: none;
}
.navbar-inverse .navbar-inner {
background-image: -ms-linear-gradient(top, #E27403, #E49037);
background-image: -webkit-linear-gradient(top, #E27403, #E49037);
background-image: linear-gradient(to bottom, #E27403, #E49037);
}
it works well for all navigator you can see demo here http://caverne.fr on the top
If you use a Datetime format see http://php.net/manual/en/datetime.format.php
You can do this :
$date = new \DateTime();
echo date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12
echo date_format($date, 'G:ia');
#output: 05:45pm
If all login services use PAM, and all login services have session required pam_env.so
in their respective /etc/pam.d/*
configuration files, then all login sessions will have some environment variables set as specified in pam_env
's configuration file.
On most modern Linux distributions, this is all there by default -- just add your desired global environment variables to /etc/security/pam_env.conf
.
This works regardless of the user's shell, and works for graphical logins too (if xdm/kdm/gdm/entrance/… is set up like this).
If you are using mongodb 3.4.4 and above then you can use below aggregation using $objectToArray
and $group
aggregation
db.collection.aggregate([
{ "$project": {
"data": { "$objectToArray": "$$ROOT" }
}},
{ "$project": { "data": "$data.k" }},
{ "$unwind": "$data" },
{ "$group": {
"_id": null,
"keys": { "$addToSet": "$data" }
}}
])
Here is the working example
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
This could be related to one of the bugs in JDK 6 Update 14, as indicated in the release notes for JDK 6 update 15.
If this indeed turns out to be the issue, you should move to a higher version of the JDK (that's no guarantee though, since fixes have been released against 6u16, 6u18 and 7b1). The best bet is to use -XX:+UseParallelGC flag. Increasing the size of the minimum and maximum heap size, to delay the first GC, bring temporary relief.
By the way, use this bug report in Eclipse to track how others have been faring.
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
One additional reason to add final to parameter declarations is that it helps to identify variables that need to be renamed as part of a "Extract Method" refactoring. I have found that adding final to each parameter prior to starting a large method refactoring quickly tells me if there are any issues I need to address before continuing.
However, I generally remove them as superfluous at the end of the refactoring.
You can achieve a fade effect (instead of sticking with the default slide) using css only. Add these to your stylesheet
.carousel .item {
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
-ms-transition: opacity 3s;
-o-transition: opacity 3s;
transition: opacity 3s;
}
.carousel .active.left {
left:0;opacity:0;z-index:2;
}
.carousel .next {
left:0;opacity:1;z-index:1;
}
This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem
package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:
\newenvironment{myitemize}
{ \begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt} }
{ \end{itemize} }
Which should be used like this:
\begin{myitemize}
\item one
\item two
\item three
\end{myitemize}
This is my approach. I find it easy to implement on various websites and use it all the time
CSS and JavaScript:
<style type="text/css">
.scrolloff iframe {
pointer-events: none ;
}
</style>
<script type="text/javascript">
function scrollOn() {
$('#map').removeClass('scrolloff'); // set the pointer events true on click
}
function scrollOff() {
$('#map').addClass('scrolloff');
}
</script>
In the HTML, you will want to wrap the iframe in a div.
<div id="map" class="scrolloff" onclick="scrollOn()" onmouseleave="scrollOff()" >
function scrollOn() {_x000D_
$('#map').removeClass('scrolloff'); // set the pointer events true on click_x000D_
_x000D_
}_x000D_
_x000D_
function scrollOff() {_x000D_
$('#map').addClass('scrolloff'); // set the pointer events true on click_x000D_
_x000D_
}
_x000D_
.scrolloff iframe {_x000D_
pointer-events: none ;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="map" class="scrolloff" onclick="scrollOn()" onmouseleave="scrollOff()" ><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d23845.03946309692!2d-70.0451736316453!3d41.66373705082399!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x89fb159980380d21%3A0x78c040f807017e30!2sChatham+Tides!5e0!3m2!1sen!2sus!4v1452964723177" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe></div>
_x000D_
Hope this helps anyone looking for a simple solution.
Another way you could do it is using the next() function.
matched_obj = next(x for x in list if x.n == 10)
For example:
you can use:
df %>% filter(!is.na(a))
to remove the NA in column a.
From the Docs: http://facebook.github.io/react-native/docs/running-on-device.html#method-2-connect-via-wi-fi
Method 2: Connect via Wi-Fi
You can also connect to the development server over Wi-Fi. You'll
first need to install the app on your device using a USB cable, but
once that has been done you can debug wirelessly by following these
instructions. You'll need your development machine's current IP
address before proceeding.Open a terminal and type /sbin/ifconfig to find your machine's IP address.
- Make sure your laptop and your phone are on the same Wi-Fi network.
- Open your React Native app on your device.
- You'll see a red screen with an error. This is OK. The following steps will fix that.
- Open the in-app Developer menu.
- Go to Dev Settings ? Debug server host for device.
- Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081).
- Go back to the Developer menu and select Reload JS.
If you were to do the following:
<li class="active-item" ng-repeat="item in mc.pageData.items | filter: { itemTypeId: 2, itemStatus: 1 } | orderBy : 'listIndex'"
id="{{item.id}}">
<span class="item-title">{{preference.itemTitle}}</span>
</li>
...you would not only get items of itemTypeId 2 and itemStatus 1, but you would also get items with itemType 20, 22, 202, 123 and itemStatus 10, 11, 101, 123. This is because the filter: {...} syntax works like a string contains query.
However, if you were to add the : true condition, it would do filter by exact match:
<li class="active-item" ng-repeat="item in mc.pageData.items | filter: { itemTypeId: 2, itemStatus: 1 } : true | orderBy : 'listIndex'"
id="{{item.id}}">
<span class="item-title">{{preference.itemTitle}}</span>
</li>
Improvement to @madprops answer - solution as a django management command:
import MySQLdb
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
host = settings.DATABASES['default']['HOST']
password = settings.DATABASES['default']['PASSWORD']
user = settings.DATABASES['default']['USER']
dbname = settings.DATABASES['default']['NAME']
db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(f'Changing table "{row[0]}"...')
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
Hope this helps anybody but me :)
data = "firstName and favoriteFood"
mandatory_fields = ['firstName', 'lastName', 'age']
# for each
for field in mandatory_fields:
if field not in data:
print("Error, missing req field {0}".format(field));
# still fine, multiple if statements
if ('firstName' not in data or
'lastName' not in data or
'age' not in data):
print("Error, missing a req field");
# not very readable, list comprehension
missing_fields = [x for x in mandatory_fields if x not in data]
if (len(missing_fields)>0):
print("Error, missing fields {0}".format(", ".join(missing_fields)));