myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
It's preference mainly
I prefer returns and if you have multiple returns you can wrap them in a Result DTO
public class Result{
public Person Person {get;set;}
public int Sum {get;set;}
}
If you are running Fedora, make sure SELinux is not interfering.You fix this with this command:
sudo /sbin/restorecon -R /var/www/.
More info here: linuxquestions.org/questions/linux-server-73/
If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.
For example:
$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master
Similarly you can clone as if this were a remote repo:
$ git clone ~/repos/myproject.git
Declare this code in Android Manifest :
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_name" />
I hope this useful to you.
Here is a working example in side a function:
function setCurrency(){_x000D_
var returnCurrent;_x000D_
$("#RequestCurrencyType").is(":checked") === true ? returnCurrent = 'Dollar': returnCurrent = 'Euro';_x000D_
_x000D_
return returnCurrent;_x000D_
}
_x000D_
In your case. Change the selector and the return values
$("#blackbox").css('background-color') === 'pink' ? return "black" : return "pink";
_x000D_
lastly, to know what is the value used by the browser run the following in the console:
$("#blackbox").css('background-color')
_x000D_
and use the "rgb(xxx.xxx.xxx)" value instead of the Hex for the color selection.
<html>
<script>
var xmlDoc = null ;
function load() {
if (typeof window.ActiveXObject != 'undefined' ) {
xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
xmlDoc.onreadystatechange = process ;
}
else {
xmlDoc = new XMLHttpRequest();
xmlDoc.onload = process ;
}
xmlDoc.open( "GET", "background.html", true );
xmlDoc.send( null );
}
function process() {
if ( xmlDoc.readyState != 4 ) return ;
document.getElementById("output").value = xmlDoc.responseText ;
}
function empty() {
document.getElementById("output").value = '<empty>' ;
}
</script>
<body>
<textarea id="output" cols='70' rows='40'><empty></textarea>
<br></br>
<button onclick="load()">Load</button>
<button onclick="empty()">Clear</button>
</body>
</html>
Yes, I got the answer.. just simply edit the manifest
file as:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
and set EditText.requestFocus()
in onCreate()
..
Thanks..
Honestly, this doesn't need to be difficult. It may seem that on the onset, but it's not. Here's a simple linq query in C# that does exactly as requested.
In my example, I'm working against a list of persons that have one property called FirstName.
var results = ClientsRepository().Where(c => c.FirstName.ToLower().Contains(searchText.ToLower())).ToList();
This will search the database on lower case search but return full case results.
This should work:
var result = cmd.ExecuteScalar();
conn.Close();
return result != null ? result.ToString() : string.Empty;
Also, I'd suggest using Parameters in your query, something like (just a suggestion):
var cmd = new SqlCommand
{
Connection = conn,
CommandType = CommandType.Text,
CommandText = "select COUNT(idemp_atd) absentDayNo from td_atd where absentdate_atd between @sdate and @edate and idemp_atd=@idemp group by idemp_atd"
};
cmd.Parameters.AddWithValue("@sdate", sdate);
cmd.Parameters.AddWithValue("@edate", edate);
// etc ...
I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.
HEAD
Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
Something like this, based it on this question:
var cli = require('cli');
var http = require('http');
var url = require('url');
cli.parse();
cli.main(function(args, opts) {
this.debug(args[0]);
var siteUrl = url.parse(args[0]);
var site = http.createClient(80, siteUrl.host);
console.log(siteUrl);
var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
request.end();
request.on('response', function(response) {
response.setEncoding('utf8');
console.log('STATUS: ' + response.statusCode);
response.on('data', function(chunk) {
console.log("DATA: " + chunk);
});
});
});
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
ssh user@machine 'bash -s' < local_script.sh
or you can just
ssh user@machine "remote command to run"
Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.
As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:
To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash
and the command to export
. You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources. Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.
The result is this incredibly helpful listing of current environment variables used for building:
As of 2015 and Python 3.4's release, there's now a reasonably complete user-interactive shell available at: http://xon.sh/ or https://github.com/scopatz/xonsh
The demonstration video does not show pipes being used, but they ARE supported when in the default shell mode.
Xonsh ('conch') tries very hard to emulate bash, so things you've already gained muscle memory for, like
env | uniq | sort -r | grep PATH
or
my-web-server 2>&1 | my-log-sorter
will still work fine.
The tutorial is quite lengthy and seems to cover a significant amount of the functionality someone would generally expect at a ash or bash prompt:
?
& ??
*.xsh
Scripts which can also be imported${}
$()
, Uncaptured Subprocess with $[]
, Python Evaluation with @()
*
or Regular Expression Filename Globbing with BackticksIt seems like you can also use the patch command. Put the diff in the root of the repository and run patch
from the command line.
patch -i yourcoworkers.diff
or
patch -p0 -i yourcoworkers.diff
You may need to remove the leading folder structure if they created the diff without using --no-prefix
.
If so, then you can remove the parts of the folder that don't apply using:
patch -p1 -i yourcoworkers.diff
The -p(n) signifies how many parts of the folder structure to remove.
More information on creating and applying patches here.
You can also use
git apply yourcoworkers.diff --stat
to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.
I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.
(This is the same answer I provided here)
A very easy solution to this problem is to do this.
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>
Which will output
<ul>
<li class="current"><a href="index.php">Home</a></li>
<li class=""><a href="portfolio.php">Portfolio</a></li>
<li class=""><a href="services.php">Services</a></li>
<li class=""><a href="contact.php">Contact</a></li>
<li class=""><a href="links.php">Links</a></li>
</ul>
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
You can call tail +[line number] [file]
and pipe it to grep -n
which shows the line number:
tail +[line number] [file] | grep -n /regex/
The only problem with this method is the line numbers reported by grep -n
will be [line number] - 1
less than the actual line number in [file]
.
A little late to the party, but...
The other answers do a good job of explaining what effect the [ChildActionOnly]
attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render @Html.Partial("_MyParialView")
directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.
This can come in handy, for example, in _Layout.cshtml
. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout
can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render @Html.Action
in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout
page need not have a model. It follows that all other view models need not inherit from any base view model.
I'm sure there are other reasons to use the [ChildActionOnly]
attribute, but this seems like a good one to me, so I thought I'd share.
You can do something like this:
function convert(items) {
var result = [];
items.forEach(function (element) {
var existingElement = result.filter(function (item) {
return item.group === element.group;
})[0];
if (existingElement) {
existingElement.color.push(element.color);
} else {
element.color = [element.color];
result.push(element);
}
});
return result;
}
Sometimes you need to reset ADB. To do that, in Eclipse, go:
Window>> Show View >> Android (Might be found in the "Other" option)>>Devices
in the device Tab, click the down arrow, and choose reset adb.
This will work with either an array, an object or a variable and also escapes the special characters that may break your JS :
function debugToConsole($msg) {
echo "<script>console.log(".json_encode($msg).")</script>";
}
Edit : Added json_encode
to the echo
statement. This will prevent your script from breaking if there are quotes in your $msg
variable.
When you create a new File
, you are supposed to provide the file name, not only the directory you want to put your file in.
Try with something like
File file = new File("D:/Data/" + item.getFileName());
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.
$output = array();
foreach( new RecursiveIteratorIterator(
new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {
if ( $value->isFile() ) {
$output[] = array( $value->getMTime(), $value->getRealPath() );
}
}
usort ( $output, function( $a, $b ) {
return $a[0] > $b[0];
});
brief mnemonics:
git reset HEAD : index = HEAD
git checkout : file_tree = index
git reset --hard HEAD : file_tree = index = HEAD
While many of the other answers provide good examples of why you might want to catch an rethrow an exception, no one seems to have mentioned a 'finally' scenario.
An example of this is where you have a method in which you set the cursor (for example to a wait cursor), the method has several exit points (e.g. if () return;) and you want to ensure the cursor is reset at the end of the method.
To do this you can wrap all of the code in a try/catch/finally. In the finally set the cursor back to the right cursor. So that you don't bury any valid exceptions, rethrow it in the catch.
try
{
Cursor.Current = Cursors.WaitCursor;
// Test something
if (testResult) return;
// Do something else
}
catch
{
throw;
}
finally
{
Cursor.Current = Cursors.Default;
}
If you are using Rails/ActiveSupport, you can use squish
method. It removes white space on both ends of the string and groups multiple white space to single space.
For eg.
" a b c ".squish
will result to:
"a b c"
Swift 5
yourButton.setImage(UIImage(named: "BUTTON_FILENAME.png"), for: .normal)
Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.
function A(val){
if(typeof(val) === "undefined")
//do this
else
//do this
}
Similar to another solution here, with minor modification:
<form method="METHOD" id="FORMID">
<!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>
In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.
In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext
, JSF's FacesContext
, Spring's ApplicationContext
, Android's Context
, JNDI's InitialContext
, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.
You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'
SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code],
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title],
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]
This is the easy methods we can use
on jquery button click function
$("#button").click(function(event){
$('video').trigger('play');
$('video').trigger('pause');
}
Thanks
If you do a
sudo yum list | grep python3
you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:
sudo yum install python34 python34-pip
The type int
is a primitive and it cannot be null
, if you want to return null
, mark the signature as
public Integer pollDecrementHigherKey(int x) {
x = 10;
if (condition) {
return x; // This is auto-boxing, x will be automatically converted to Integer
} else if (condition2) {
return null; // Integer inherits from Object, so it's valid to return null
} else {
return new Integer(x); // Create an Integer from the int and then return
}
return 5; // Also will be autoboxed and converted into Integer
}
Correctness of Dijkstra's algorithm:
We have 2 sets of vertices at any step of the algorithm. Set A consists of the vertices to which we have computed the shortest paths. Set B consists of the remaining vertices.
Inductive Hypothesis: At each step we will assume that all previous iterations are correct.
Inductive Step: When we add a vertex V to the set A and set the distance to be dist[V], we must prove that this distance is optimal. If this is not optimal then there must be some other path to the vertex V that is of shorter length.
Suppose this some other path goes through some vertex X.
Now, since dist[V] <= dist[X] , therefore any other path to V will be atleast dist[V] length, unless the graph has negative edge lengths.
Thus for dijkstra's algorithm to work, the edge weights must be non negative.
You could use a watch instead, because that has the old and new value, but then you're adding to the digest cycle.
I'd just keep a second variable in the controller and set that.
Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.
db.test.aggregate([
{$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
{$project: {
list: {$filter: {
input: "$list",
as: "list",
cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
}}
}}
]);
If you want insert all data from one table to another table there is a very simply sql
INSERT INTO destinationTable (SELECT * FROM sourceDbName.SourceTableName);
Just look at this solution, make sure you've turned access on to less secure apps on your google account :javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25
You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.
<p style="font-size: 28px;"> Hello, World! </p>
You can also set the color by setting:
<p style="color: blue;"> Hello, World! </p>
However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/
C:\Users\<Username>\AppData\Local\Continuum\anaconda2
For me this was the default installation directory on Windows 7. Found it via Rusy's answer
Surely you just need:
double seconds = milliseconds / 1000.0;
There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0
(as a double
literal) forces. (I'm assuming your milliseconds
value is an integer of some form.)
Note that as usual with double
, you may not be able to represent the result exactly. Consider using BigDecimal
if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double
is probably appropriate, but...)
After trying all of the previous answers, the only thing that worked for me iOS 14.2 was to run Xcode 12.2 beta, and then switch back to Xcode 12.0.1 production.
Based on the same idea as Super Type Tokens, you could create a typed id to use instead of a string:
public abstract class TypedID<T extends Animal> {
public final Type type;
public final String id;
protected TypedID(String id) {
this.id = id;
Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
}
But I think this may defeat the purpose, since you now need to create new id objects for each string and hold on to them (or reconstruct them with the correct type information).
Mouse jerry = new Mouse();
TypedID<Dog> spike = new TypedID<Dog>("spike") {};
TypedID<Duck> quacker = new TypedID<Duck>("quacker") {};
jerry.addFriend(spike, new Dog());
jerry.addFriend(quacker, new Duck());
But you can now use the class in the way you originally wanted, without the casts.
jerry.callFriend(spike).bark();
jerry.callFriend(quacker).quack();
This is just hiding the type parameter inside the id, although it does mean you can retrieve the type from the identifier later if you wish.
You'd need to implement the comparison and hashing methods of TypedID too if you want to be able to compare two identical instances of an id.
using System.IO;
using System.Text;
using System.Security.Cryptography;
public static class EncryptionHelper
{
public static string Encrypt(string clearText)
{
string EncryptionKey = "abc123";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
public static string Decrypt(string cipherText)
{
string EncryptionKey = "abc123";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
}
You should add user settings:
{
"editor.showFoldingControls": "always",
"editor.folding": true,
"editor.foldingStrategy": "indentation",
}
If you are using postgresql
And i'm using in spring boot 1.5.6
@Column(columnDefinition = "serial")
@Generated(GenerationTime.INSERT)
private Integer orderID;
I tried most of above. I was developing in Flutter so what worked for me was pub cache repair
.
This should be faster than iterating and will work regardless of shape.
numpy.isnan(myarray).any()
Edit: 30x faster:
import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
'numpy.isnan(a).any()',
'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
print " %.2f s" % timeit.Timer(m, s).timeit(1000), m
Results:
0.11 s numpy.isnan(a).any()
3.75 s any(numpy.isnan(x) for x in a.flatten())
Bonus: it works fine for non-array NumPy types:
>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True
Android studio 3.0
step0:
Close android studio
step1:
Goto C:\Program Files\Android\Android Studio\plugins\android\lib\templates\activities\common\root\res\layout\
step2:
Backup simple.xml.ftl
step3:
Change simple.xml.ftl to code below and save :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="12dp"
android:layout_marginTop="21dp"
android:text="don't forget to click useful if this helps. this is my first post at stackoverflow!"
android:textSize="20sp"
/>
</RelativeLayout>
From Numpy Documentation
np.delete(arr, obj, axis=None) Return a new array with sub-arrays along an axis deleted.
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1, 2, 3, 4],
[ 9, 10, 11, 12]])
>>> np.delete(arr, np.s_[::2], 1)
array([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.
Use this class to draw shadow on bitmaps
public class ShadowGenerator {
// Percent of actual icon size
private static final float HALF_DISTANCE = 0.5f;
public static final float BLUR_FACTOR = 0.5f/48;
// Percent of actual icon size
private static final float KEY_SHADOW_DISTANCE = 1f/48;
public static final int KEY_SHADOW_ALPHA = 61;
public static final int AMBIENT_SHADOW_ALPHA = 30;
private static final Object LOCK = new Object();
// Singleton object guarded by {@link #LOCK}
private static ShadowGenerator sShadowGenerator;
private int mIconSize;
private final Canvas mCanvas;
private final Paint mBlurPaint;
private final Paint mDrawPaint;
private final Context mContext;
private ShadowGenerator(Context context) {
mContext = context;
mIconSize = Utils.convertDpToPixel(context,63);
mCanvas = new Canvas();
mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
}
public synchronized Bitmap recreateIcon(Bitmap icon) {
mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
int[] offset = new int[2];
Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
mCanvas.setBitmap(result);
// Draw ambient shadow
mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);
// Draw key shadow
mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);
// Draw the icon
mDrawPaint.setAlpha(255);
mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);
mCanvas.setBitmap(null);
return result;
}
public static ShadowGenerator getInstance(Context context) {
synchronized (LOCK) {
if (sShadowGenerator == null) {
sShadowGenerator = new ShadowGenerator(context);
}
}
return sShadowGenerator;
}
}
This is how did it works like a charm.
#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}
in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)
<div id="loader">
</div>
JS at the bottom of _layout file
<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
$("#loader").fadeOut(1000);
</script>
If you don't want duplicates, use a Set instead of a List
. To convert a List
to a Set
you can use the following code:
// list is some List of Strings
Set<String> s = new HashSet<String>(list);
If really necessary you can use the same construction to convert a Set
back into a List
.
On Windows 10 it is important to make sure the WinRM Service is running to invoke the command
* Set-Item wsman:\localhost\Client\TrustedHosts -value '*' -Force *
All of these solutions manipulate Apple's gesture recognizer in a way they do not recommend. I've just been told by a friend that there's a better solution:
[navigationController.interactivePopGestureRecognizer requireGestureRecognizerToFail: myPanGestureRecognizer];
where myPanGestureRecognizer is the gesture recognizer you are using to e.g. show your menu. That way, Apple's gesture recognizer doesn't get turned back on by them when you push a new navigation controller and you don't need to rely on hacky delays that may fire too early if your phone is put to sleep or under heavy load.
Leaving this here because I know I'll not remember this the next time I need it, and then I'll have the solution to the issue here.
A simple example for the usage of JSONP.
client.html
<html>
<head>
</head>
body>
<input type="button" id="001" onclick=gO("getCompany") value="Company" />
<input type="button" id="002" onclick=gO("getPosition") value="Position"/>
<h3>
<div id="101">
</div>
</h3>
<script type="text/javascript">
var elem=document.getElementById("101");
function gO(callback){
script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://localhost/test/server.php?callback='+callback;
elem.appendChild(script);
elem.removeChild(script);
}
function getCompany(data){
var message="The company you work for is "+data.company +"<img src='"+data.image+"'/ >";
elem.innerHTML=message;
}
function getPosition(data){
var message="The position you are offered is "+data.position;
elem.innerHTML=message;
}
</script>
</body>
</html>
server.php
<?php
$callback=$_GET["callback"];
echo $callback;
if($callback=='getCompany')
$response="({\"company\":\"Google\",\"image\":\"xyz.jpg\"})";
else
$response="({\"position\":\"Development Intern\"})";
echo $response;
?>
Turns out for me that SET NOCOUNT ON
was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery();
always returned -1.
I just set it off: SET NOCOUNT OFF
without needing to use @@ROWCOUNT
.
More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete
Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.
In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.
In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it
Then, Im used:
c = len(list)-1
for element in (reversed(list)):
if condition(element):
del list[c]
c -= 1
print(list)
where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]
Also You can do more pythonic using enumerate:
for i, element in enumerate(reversed(list)):
if condition(element):
del list[(i+1)*-1]
print(list)
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
sort
has been replaced in v0.20 by DataFrame.sort_values
and DataFrame.sort_index
. Aside from this, we also have argsort
.
Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.
# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})
df
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
For example, to sort df
by column "A", use sort_values
with a single column name:
df.sort_values(by='A')
A B
0 a 7
3 a 5
4 b 2
1 c 9
2 c 3
If you need a fresh RangeIndex, use DataFrame.reset_index
.
For example, to sort by both col "A" and "B" in df
, you can pass a list to sort_values
:
df.sort_values(by=['A', 'B'])
A B
3 a 5
0 a 7
4 b 2
2 c 3
1 c 9
df2 = df.sample(frac=1)
df2
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
You can do this using sort_index
:
df2.sort_index()
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
df.equals(df2)
# False
df.equals(df2.sort_index())
# True
Here are some comparable methods with their performance:
%timeit df2.sort_index()
%timeit df2.iloc[df2.index.argsort()]
%timeit df2.reindex(np.sort(df2.index))
605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
For example,
idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])
This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc
will do.
df.iloc[idx]
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
Add a helper class:
public static class Redirector {
public static void RedirectTo(this Controller ct, string action) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
}
public static void RedirectTo(this Controller ct, string action, string controller) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
}
public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
}
}
Then call in your action:
this.RedirectTo("Index", "Cement");
Add javascript code to any global javascript included file or layout file to intercept all ajax requests:
<script type="text/javascript">_x000D_
$(function() {_x000D_
$(document).ajaxComplete(function (event, xhr, settings) {_x000D_
var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
if (urlHeader != null && urlHeader !== undefined) {_x000D_
window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
}_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
Use heroku's fork
Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!
heroku fork -a sourceapp targetapp
Clone it local
git clone [email protected]:youamazingapp.git
Make a new repo on github and add it
git remote add origin https://github.com/yourname/your_repo.git
Push on github
git push origin master
In java you don't check if a key is pressed, instead you listen to KeyEvent
s.
The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}
Then you can always use:
if (IsKeyPressed.isWPressed()) {
// do your thing.
}
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.
So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.
ini_set("include_path", "/your_include_path:".ini_get("include_path"));
This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.
Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:
def rps():
# Code to determine if player wins
if player_wins:
return True
return False
Then, just assign a value to the variable outside this function like so:
player_wins = rps()
It will be assigned the return value (either True or False) of the function you just called.
After the comments, I decided to add that idiomatically, this would be better expressed thus:
def rps():
# Code to determine if player wins, assigning a boolean value (True or False)
# to the variable player_wins.
return player_wins
pw = rps()
This assigns the boolean value of player_wins
(inside the function) to the pw
variable outside the function.
I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:
sudo npm install -g bower
To add all file at a time, use git add -A
To check git whole status, use git log
You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
I was able to get this work. I added the following to my custom CSS:
.wpcf7-form textarea{
width: 100% !important;
height:50px;
}
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
I'm going out on a limb here , since your question was not very detailed, that a) your receipt printer is a thermal printer that needs raw data, b) that "from javascript" you are talking about printing from the web browser and c) that you do not have access to send raw data from browser
Here is a Java Applet that solves all that for you , if I'm correct about those assumptions then you need either Java, Flash, or Silverlight http://code.google.com/p/jzebra/
If i understand your question, you just want to be able to access items in a data frame (or list) by row:
x = matrix( ceiling(9*runif(20)), nrow=5 )
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x) # create a small data frame
df[1,] # get the first row
df[3,] # get the third row
df[nrow(df),] # get the last row
lf = as.list(df)
lf[[1]] # get first row
lf[[3]] # get third row
etc.
You would use the INCLUDE to add one or more columns to the leaf level of a non-clustered index, if by doing so, you can "cover" your queries.
Imagine you need to query for an employee's ID, department ID, and lastname.
SELECT EmployeeID, DepartmentID, LastName
FROM Employee
WHERE DepartmentID = 5
If you happen to have a non-clustered index on (EmployeeID, DepartmentID), once you find the employees for a given department, you now have to do "bookmark lookup" to get the actual full employee record, just to get the lastname column. That can get pretty expensive in terms of performance, if you find a lot of employees.
If you had included that lastname in your index:
CREATE NONCLUSTERED INDEX NC_EmpDep
ON Employee(EmployeeID, DepartmentID)
INCLUDE (Lastname)
then all the information you need is available in the leaf level of the non-clustered index. Just by seeking in the non-clustered index and finding your employees for a given department, you have all the necessary information, and the bookmark lookup for each employee found in the index is no longer necessary --> you save a lot of time.
Obviously, you cannot include every column in every non-clustered index - but if you do have queries which are missing just one or two columns to be "covered" (and that get used a lot), it can be very helpful to INCLUDE those into a suitable non-clustered index.
You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.
<div class="div-image-text">
<input class="input-image-url" type="text" placeholder="Add text" name="input-image">
<input type="button" onclick="addRemoteImage(event);" value="Submit">
</div>
<div class="no-image-url-error" name="input-image-error">Textbox empty</div>
addRemoteImage = function(event) {
var textbox = document.querySelector("input[name='input-image']"),
imageUrl = textbox.value,
errorDiv = document.querySelector("div[name='input-image-error']");
if (imageUrl == "") {
errorDiv.style.display = "block";
textbox.classList.add('text-error');
setTimeout(function() {
errorDiv.style.removeProperty('display');
textbox.classList.remove('text-error');
}, 3000);
} else {
textbox.classList.remove('text-error');
}
}
Just some thoughts on my case.
If you have changed the dbPath and logPath dirs to your custom values (say /data/mongodb/data, /data/mongodb/log), you must chown them to mongodb user, otherwise, the non-existent /data/db/ dir will be used.
sudo chown -R mongodb:mongodb /data/mongodb/
sudo service mongod restart
Better use automatic dimensions (Swift):
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
NB: 1. UITableViewCell prototype should be properly designed (for the instance don't forget set UILabel.numberOfLines = 0 etc) 2. Remove HeightForRowAtIndexPath method
VIDEO: https://youtu.be/Sz3XfCsSb6k
I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."
INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there
Check if SElinux is enabled. If it is in enforcing mode just try with permissive mode. In case that helps you should create SElinux policies for mongodb.
You can try with audit2allow - check https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security-enhanced_linux/sect-security-enhanced_linux-fixing_problems-allowing_access_audit2allow
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
int digits=1;
while (x>=10){
x/=10;
digits++;
}
return digits;
You should first add a new route in global.asax:
routes.MapRoute(
"MyNewRoute",
"{controller}/{action}/{date}",
new { controller="YourControllerName", action="YourActionName", date = "" }
);
The on your Controller:
public ActionResult MyActionName(DateTime date)
{
}
Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.
This seems more concise.
pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U
Explanation:
pip list --outdated
gets lines like these
urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]
In cut -d ' ' -f1
, -d ' '
sets "space" as the delimiter, -f1
means to get the first column.
So the above lines becomes:
urllib3
wheel
then pass them to xargs
to run the command, pip install -U
, with each line as appending arguments
-n1
limits the number of arguments passed to each command pip install -U
to be 1
I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.
Only a manual deletion of the specific dependency in the cache folder works... an artifactory built by a colleague in enterprise repo.
Here's an extension method. Not sure where I found it.
public static class StringExtensions
{
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
{
int startIndex = 0;
while (true)
{
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
startIndex += newValue.Length;
}
return originalString;
}
}
With HTML5 you can do
<input type="number">
You can also use a regex pattern to limit the input text.
<input type="text" pattern="^[0-9]*$" />
The SyntaxError: unexpected EOF while parsing
means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100):
and requires at least one line afterwards that contains code that should be in it.
It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3
but not for code blocks like for loops. See the following example:
In [1]: for i in range(100):
File "<ipython-input-1-ece1e5c2587f>", line 1
for i in range(100):
^
SyntaxError: unexpected EOF while parsing
To avoid this error, you have to enter the whole code block as a single input:
In [2]: for i in range(5):
...: print(i, end=', ')
0, 1, 2, 3, 4,
File Size in MB
ls -l --b=M filename | cut -d " " -f5
File Size in GB
ls -l --b=G filename | cut -d " " -f5
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
/home/jake/xxx
is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:
cd /home/jake/
ln -s /home/jake/doc/test/2000/something xxx
You can also use : mysql> select user,host from mysql.user;
+---------------+-------------------------------+
| user | host |
+---------------+-------------------------------+
| fkernel | % |
| nagios | % |
| readonly | % |
| replicant | % |
| reporting | % |
| reporting_ro | % |
| nagios | xx.xx.xx.xx |
| haproxy_root | xx.xx.xx.xx
| root | 127.0.0.1 |
| nagios | localhost |
| root | localhost |
+---------------+-------------------------------+
adardesign nailed it regarding the file input element being ignored when it is hidden. I also noticed many people shifting element size to 0, or pushing it out of bounds with positioning and overflow adjustments. These are all great ideas.
An alternative way that also seems to work perfectly well is to just set the opacity to 0. Then you can always just set the position to keep it from offsetting other elements as hide does. It just seems a little unnecessary to shift an element nearly 10K pixels in any direction.
Here's a little example for those who want one:
input[type='file']{
position:absolute;
opacity:0;
/* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
/* For IE5 - 7 */
filter: alpha(opacity=0);
}
x = x * 2^value
(normal operation)
x << value
(bit-wise operation)
x = x * 16
(which is the same as 2^4
)
The left shift equivalent would be x = x << 4
x = x / 2^value
(normal arithmetic operation)
x >> value
(bit-wise operation)
x = x / 8
(which is the same as 2^3
)
The right shift equivalent would be x = x >> 3
You might need to activate adb root from the developer settings menu.
If you run adb root
from the cmd line you can get:
root access is disabled by system setting - enable in settings -> development options
Once you activate the root option (ADB only or Apps and ADB) adb will restart and you will be able to use root from the cmd line.
That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.
The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.
But, I'll take a stab. The original sentence is this:
All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.
X here is a category. Endofunctors are functors from a category to itself (which is usually all Functor
s as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.
And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:
* -> *
with a Functor
instance)join
in Haskell)return
in Haskell)With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.
To get back to the parent frame, use:
driver.switchTo().parentFrame();
To get back to the first/main frame, use:
driver.switchTo().defaultContent();
Simply you can save with extension .json but while saving you have to do some changes.
Change Save as type in red circle in image to All Files.
It will create .json file with name bharti.json.
To check this --> Right click at file --> Properties --> Type of file: JSON File (.json)
Update - I verified the below works. Maybe the creation of your JArray isn't quite right.
[TestMethod]
public void TestJson()
{
var jsonString = @"{""trends"": [
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
},
{
""name"": ""#HNCJ"",
""url"": ""http://twitter.com/search?q=%23HNCJ"",
""promoted_content"": null,
""query"": ""%23HNCJ"",
""events"": null
},
{
""name"": ""Boston"",
""url"": ""http://twitter.com/search?q=Boston"",
""promoted_content"": null,
""query"": ""Boston"",
""events"": null
},
{
""name"": ""#prayforboston"",
""url"": ""http://twitter.com/search?q=%23prayforboston"",
""promoted_content"": null,
""query"": ""%23prayforboston"",
""events"": null
},
{
""name"": ""#TheMrsCarterShow"",
""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
""promoted_content"": null,
""query"": ""%23TheMrsCarterShow"",
""events"": null
},
{
""name"": ""#Raw"",
""url"": ""http://twitter.com/search?q=%23Raw"",
""promoted_content"": null,
""query"": ""%23Raw"",
""events"": null
},
{
""name"": ""Iran"",
""url"": ""http://twitter.com/search?q=Iran"",
""promoted_content"": null,
""query"": ""Iran"",
""events"": null
},
{
""name"": ""#gaa"",
""url"": ""http://twitter.com/search?q=%23gaa"",
""promoted_content"": null,
""query"": ""gaa"",
""events"": null
},
{
""name"": ""Facebook"",
""url"": ""http://twitter.com/search?q=Facebook"",
""promoted_content"": null,
""query"": ""Facebook"",
""events"": null
}]}";
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
}
So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.
foreach(var item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
Test if a file exists:
HOST="example.com"
FILE="/path/to/file"
if ssh $HOST "test -e $FILE"; then
echo "File exists."
else
echo "File does not exist."
fi
And the opposite, test if a file does not exist:
HOST="example.com"
FILE="/path/to/file"
if ! ssh $HOST "test -e $FILE"; then
echo "File does not exist."
else
echo "File exists."
fi
if ($name ) { #since undef and '' both evaluate to false #this should work only when string is defined and non-empty... #unless you're expecting someting like $name="0" which is false. #notice though that $name="00" is not false }
In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"
Try my favourite tool logview to get the logs and analyze them during development.
Make sure to mark ./logview
and ./lib/logview.jar
as executable when running in Linux.
If you don't like it, there're a lot of alternative desktop log viewers for Android.
Integrate a real-time crash reporting tool such as Firebase Crashlytics in order to get stacktraces of unhandled exceptions which occurred on users' devices.
Read How to Release a Buggy App (And Live to Tell the Tale) to know more about handling bugs in the field.
Adding this for completeness. If you (like me) use a script in your package.json
file, just add the --timeout
option to mocha:
"scripts": {
"test": "mocha 'test/**/*.js' --timeout 10000",
"test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},
Then you can run npm run test
to run your test suite with the timeout set to 10,000 milliseconds.
You can use this.props.children
to render whatever children the component contains:
const Wrap = ({ children }) => <div>{children}</div>
export default () => <Wrap><h1>Hello word</h1></Wrap>
Are you sure you are using correct SMTP server address?
Both smtp.google.com and smtp.gmail.com work, but SSL certificate is issued to the second one.
Just window.location = "http://wherever.you.wanna.go.com/"
, or, for local links, window.location = "my_relative_link.html"
.
You can try it by typing it into your address bar as well, e.g. javascript: window.location = "http://www.google.com/"
.
Also note that the protocol part of the URL (http://
) is not optional for absolute links; omitting it will make javascript assume a relative link.
I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.
Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:
// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
$this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
$this->exec('SET NAMES utf8');
}
Preinstalled applications are in /system/app
folder. User installed applications are in /data/app
. I guess you can't access unless you have a rooted phone.
I don't have a rooted phone here but try this code out:
public class Testing extends Activity {
private static final String TAG = "TEST";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File appsDir = new File("/data/app");
String[] files = appsDir.list();
for (int i = 0 ; i < files.length ; i++ ) {
Log.d(TAG, "File: "+files[i]);
}
}
It does lists the apks in my rooted htc magic and in the emu.
When you assign a variable to empty curly braces {} eg: new_set = {}
, it becomes a dictionary.
To create an empty set, assign the variable to a 'set()' ie: new_set = set()
You should provide output file name after -o
option. In your case runexp.o
is treated as output file name, not input object file and thus your main
function is undefined.
When you write a lambda expression, the argument list to the left of ->
can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
is incorrect syntax; but
this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
is correct. Or:
this.stops.stream().filter(s -> s.getStation().getName().equals(name));
is also correct if the compiler has enough information to figure out the types.
Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do
pgrep -x PROCESS_NAME
-x Require an exact match of the process name, or argument list if -f is given. The default is to match any substring.
This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.
neat and clean
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
if the absolute element has a width,you can use the code below
.divtagABS{
width:300px;
positon:absolute;
left:0;
right:0;
margin:0 auto;
}
The stopPropagation
options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.
Here is a simple solution based on user2989143's answer:
$('html').click(function(event) {
if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
$('#menu-container').hide();
}
});
Manual of find:
Numeric arguments can be specified as
+n for greater than n,
-n for less than n,
n for exactly n.
-amin n
File was last accessed n minutes ago.
-anewer file
File was last accessed more recently than file was modified. If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points to is always
used.
-atime n
File was last accessed n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
have been accessed at least two days ago.
-cmin n
File's status was last changed n minutes ago.
-cnewer file
File's status was last changed more recently than file was modified. If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it points
to is always used.
-ctime n
File's status was last changed n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times.
Example:
find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time
This is the working code...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class JavaCalculator extends JFrame {
private JButton jbtNum1;
private JButton jbtNum2;
private JButton jbtNum3;
private JButton jbtNum4;
private JButton jbtNum5;
private JButton jbtNum6;
private JButton jbtNum7;
private JButton jbtNum8;
private JButton jbtNum9;
private JButton jbtNum0;
private JButton jbtEqual;
private JButton jbtAdd;
private JButton jbtSubtract;
private JButton jbtMultiply;
private JButton jbtDivide;
private JButton jbtSolve;
private JButton jbtClear;
private double TEMP;
private double SolveTEMP;
private JTextField jtfResult;
Boolean addBool = false;
Boolean subBool = false;
Boolean divBool = false;
Boolean mulBool = false;
String display = "";
public JavaCalculator() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
p1.add(jbtNum1 = new JButton("1"));
p1.add(jbtNum2 = new JButton("2"));
p1.add(jbtNum3 = new JButton("3"));
p1.add(jbtNum4 = new JButton("4"));
p1.add(jbtNum5 = new JButton("5"));
p1.add(jbtNum6 = new JButton("6"));
p1.add(jbtNum7 = new JButton("7"));
p1.add(jbtNum8 = new JButton("8"));
p1.add(jbtNum9 = new JButton("9"));
p1.add(jbtNum0 = new JButton("0"));
p1.add(jbtClear = new JButton("C"));
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jtfResult = new JTextField(20));
jtfResult.setHorizontalAlignment(JTextField.RIGHT);
jtfResult.setEditable(false);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(5, 1));
p3.add(jbtAdd = new JButton("+"));
p3.add(jbtSubtract = new JButton("-"));
p3.add(jbtMultiply = new JButton("*"));
p3.add(jbtDivide = new JButton("/"));
p3.add(jbtSolve = new JButton("="));
JPanel p = new JPanel();
p.setLayout(new GridLayout());
p.add(p2, BorderLayout.NORTH);
p.add(p1, BorderLayout.SOUTH);
p.add(p3, BorderLayout.EAST);
add(p);
jbtNum1.addActionListener(new ListenToOne());
jbtNum2.addActionListener(new ListenToTwo());
jbtNum3.addActionListener(new ListenToThree());
jbtNum4.addActionListener(new ListenToFour());
jbtNum5.addActionListener(new ListenToFive());
jbtNum6.addActionListener(new ListenToSix());
jbtNum7.addActionListener(new ListenToSeven());
jbtNum8.addActionListener(new ListenToEight());
jbtNum9.addActionListener(new ListenToNine());
jbtNum0.addActionListener(new ListenToZero());
jbtAdd.addActionListener(new ListenToAdd());
jbtSubtract.addActionListener(new ListenToSubtract());
jbtMultiply.addActionListener(new ListenToMultiply());
jbtDivide.addActionListener(new ListenToDivide());
jbtSolve.addActionListener(new ListenToSolve());
jbtClear.addActionListener(new ListenToClear());
} //JavaCaluclator()
class ListenToClear implements ActionListener {
public void actionPerformed(ActionEvent e) {
//display = jtfResult.getText();
jtfResult.setText("");
addBool = false;
subBool = false;
mulBool = false;
divBool = false;
TEMP = 0;
SolveTEMP = 0;
}
}
class ListenToOne implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "1");
}
}
class ListenToTwo implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "2");
}
}
class ListenToThree implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "3");
}
}
class ListenToFour implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "4");
}
}
class ListenToFive implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "5");
}
}
class ListenToSix implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "6");
}
}
class ListenToSeven implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "7");
}
}
class ListenToEight implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "8");
}
}
class ListenToNine implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "9");
}
}
class ListenToZero implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "0");
}
}
class ListenToAdd implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
addBool = true;
}
}
class ListenToSubtract implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
subBool = true;
}
}
class ListenToMultiply implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
mulBool = true;
}
}
class ListenToDivide implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
divBool = true;
}
}
class ListenToSolve implements ActionListener {
public void actionPerformed(ActionEvent e) {
SolveTEMP = Double.parseDouble(jtfResult.getText());
if (addBool == true)
SolveTEMP = SolveTEMP + TEMP;
else if ( subBool == true)
SolveTEMP = SolveTEMP - TEMP;
else if ( mulBool == true)
SolveTEMP = SolveTEMP * TEMP;
else if ( divBool == true)
SolveTEMP = SolveTEMP / TEMP;
jtfResult.setText( Double.toString(SolveTEMP));
addBool = false;
subBool = false;
mulBool = false;
divBool = false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JavaCalculator calc = new JavaCalculator();
calc.pack();
calc.setLocationRelativeTo(null);
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calc.setVisible(true);
}
} //JavaCalculator
>>> df
Station ID Pollutants
0 8809 {"a": "46", "b": "3", "c": "12"}
1 8810 {"a": "36", "b": "5", "c": "8"}
2 8811 {"b": "2", "c": "7"}
3 8812 {"c": "11"}
4 8813 {"a": "82", "c": "15"}
speed comparison for a large dataset of 10 million rows
>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)
def json_normalise_drop(df):
return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)
def tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)
def vlues_tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)
def pop_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))
def pop_values_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop | 53min 20s |
| json_normalise_drop | 54.9 s |
| tolist_drop | 6.62 s |
| vlues_tolist_drop | 6.63 s |
| pop_tolist | 5.99 s |
| pop_values_tolist | 5.94 s |
+---------------------+-----------+
df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
is the fastest
Regardless of whether I define this in the main CMakeLists.txt or in the individual ones, it still assumes I want all the libs and bins off the main path, which is the least useful assumption of all.
This is what I use:
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
You can link the globally installed gulp
locally with
npm link gulp
The best practice would be to use traditionnal getters and setters, because of introspection or reflection. There is a way in PHP (exactly like in Java) to obtain the name of a method or of all methods. Such a thing would return "__get" in the first case and "getFirstField", "getSecondField" in the second (plus setters).
More on that: http://php.net/manual/en/book.reflection.php
Using a Swift 'switch-case':
func platformString() -> String {
var devSpec: String
switch platform() {
case "iPhone1,2": devSpec = "iPhone 3G"
case "iPhone2,1": devSpec = "iPhone 3GS"
case "iPhone3,1": devSpec = "iPhone 4"
case "iPhone3,3": devSpec = "Verizon iPhone 4"
case "iPhone4,1": devSpec = "iPhone 4S"
case "iPhone5,1": devSpec = "iPhone 5 (GSM)"
case "iPhone5,2": devSpec = "iPhone 5 (GSM+CDMA)"
case "iPhone5,3": devSpec = "iPhone 5c (GSM)"
case "iPhone5,4": devSpec = "iPhone 5c (GSM+CDMA)"
case "iPhone6,1": devSpec = "iPhone 5s (GSM)"
case "iPhone6,2": devSpec = "iPhone 5s (GSM+CDMA)"
case "iPhone7,1": devSpec = "iPhone 6 Plus"
case "iPhone7,2": devSpec = "iPhone 6"
case "iPod1,1": devSpec = "iPod Touch 1G"
case "iPod2,1": devSpec = "iPod Touch 2G"
case "iPod3,1": devSpec = "iPod Touch 3G"
case "iPod4,1": devSpec = "iPod Touch 4G"
case "iPod5,1": devSpec = "iPod Touch 5G"
case "iPad1,1": devSpec = "iPad"
case "iPad2,1": devSpec = "iPad 2 (WiFi)"
case "iPad2,2": devSpec = "iPad 2 (GSM)"
case "iPad2,3": devSpec = "iPad 2 (CDMA)"
case "iPad2,4": devSpec = "iPad 2 (WiFi)"
case "iPad2,5": devSpec = "iPad Mini (WiFi)"
case "iPad2,6": devSpec = "iPad Mini (GSM)"
case "iPad2,7": devSpec = "iPad Mini (GSM+CDMA)"
case "iPad3,1": devSpec = "iPad 3 (WiFi)"
case "iPad3,2": devSpec = "iPad 3 (GSM+CDMA)"
case "iPad3,3": devSpec = "iPad 3 (GSM)"
case "iPad3,4": devSpec = "iPad 4 (WiFi)"
case "iPad3,5": devSpec = "iPad 4 (GSM)"
case "iPad3,6": devSpec = "iPad 4 (GSM+CDMA)"
case "iPad4,1": devSpec = "iPad Air (WiFi)"
case "iPad4,2": devSpec = "iPad Air (Cellular)"
case "iPad4,4": devSpec = "iPad mini 2G (WiFi)"
case "iPad4,5": devSpec = "iPad mini 2G (Cellular)"
case "iPad4,7": devSpec = "iPad mini 3 (WiFi)"
case "iPad4,8": devSpec = "iPad mini 3 (Cellular)"
case "iPad4,9": devSpec = "iPad mini 3 (China Model)"
case "iPad5,3": devSpec = "iPad Air 2 (WiFi)"
case "iPad5,4": devSpec = "iPad Air 2 (Cellular)"
case "i386": devSpec = "Simulator"
case "x86_64": devSpec = "Simulator"
default: devSpec = "Unknown"
}
return devSpec
}
Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.
I've noticed that sometimes when switching git branches, Visual Studio (2017) will not recognize types from some files that had been added in the second branch. Deleting the .vs folder solves it, but it also trashes all your workspace settings. This trick seems to work well for me:
This causes Intellisense to parse the file that it missed when switching branches.
In SQL Server 2012 and above, you don't need to create a link. You can execute directly
SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET
I don't know whether previous versions of SQL Server work as well
That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).
for you you should do the following:
Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();
or if you want to use HQL you can do something like this:
Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();
Regards.
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);
This will account for
youtube.com/v/{vidid}
youtube.com/vi/{vidid}
youtube.com/?v={vidid}
youtube.com/?vi={vidid}
youtube.com/watch?v={vidid}
youtube.com/watch?vi={vidid}
youtu.be/{vidid}
I improved it slightly to support: http://www.youtube.com/v/5xADESocujo?feature=autoshare&version=3&autohide=1&autoplay=1
The line I use now is:
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches);
It is possible to do (in the deployed repository):
git fetch
// git fetch will download all the recent changes, but it will not put it in your current checked out code (working area).
Followed by:
git checkout origin/master -- path/to/file
// git checkout <local repo name (default is origin)>/<branch name> -- path/to/file will checkout the particular file from the downloaded changes (origin/master).
A more intuitive explanation would be :-
The square root of 100 is 10. Let's say a x b = 100, for various pairs of a and b.
If a == b, then they are equal, and are the square root of 100, exactly. Which is 10.
If one of them is less than 10, the other has to be greater. For example, 5 x 20 == 100. One is greater than 10, the other is less than 10.
Thinking about a x b, if one of them goes down, the other must get bigger to compensate, so the product stays at 100. They pivot around the square root.
The square root of 101 is about 10.049875621. So if you're testing the number 101 for primality, you only need to try the integers up through 10, including 10. But 8, 9, and 10 are not themselves prime, so you only have to test up through 7, which is prime.
Because if there's a pair of factors with one of the numbers bigger than 10, the other of the pair has to be less than 10. If the smaller one doesn't exist, there is no matching larger factor of 101.
If you're testing 121, the square root is 11. You have to test the prime integers 1 through 11 (inclusive) to see if it goes in evenly. 11 goes in 11 times, so 121 is not prime. If you had stopped at 10, and not tested 11, you would have missed 11.
You have to test every prime integer greater than 2, but less than or equal to the square root, assuming you are only testing odd numbers.
`
msbuild "C:\path to solution\project.sln"
I found theDuncs answer very useful and below you can find my own (refactored) version:
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification {
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
float newVerticalPosition = -keyboardSize.height;
[self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
}
- (void)keyboardWillHide:(NSNotification *)notification {
[self moveFrameToVerticalPosition:0.0f forDuration:0.3f];
}
- (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration {
CGRect frame = self.view.frame;
frame.origin.y = position;
[UIView animateWithDuration:duration animations:^{
self.view.frame = frame;
}];
}
I came across the same error when trying to add the callback to an event listener. Strangely, setting the callback type to EventListener solved it. It looks more elegant than defining a whole function signature as a type, but I'm not sure if this is the correct way to do this.
class driving {
// the answer from this post - this works
// private callback: () => void;
// this also works!
private callback:EventListener;
constructor(){
this.callback = () => this.startJump();
window.addEventListener("keydown", this.callback);
}
startJump():void {
console.log("jump!");
window.removeEventListener("keydown", this.callback);
}
}
Use a subquery:
SELECT * FROM
(
SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name
The inner query selects 20 users at random and the outer query orders the selected users by name.
In case you have an async helperFunction()
called from your test... (one explicilty with the ES7 async
keyword, I mean)
? make sure, you call that as await helperFunction(whateverParams)
(well, yeah, naturally, once you know...)
And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:
it('my test', async () => { ...
I've been getting worked up over naming table columns after mysql keywords. It requires stupid column name escaping in every single query you write.
SELECT this, that, `key` FROM sometable WHERE such AND suchmore;
Just horrible.
In your eclipse, go to Windows -> Preferences -> Maven Tick the option "Download repository index updates on startup". You may want to restart the eclipse.
Also go to Windows -> Show view -> Other -> Maven -> Maven repositories
On Maven repositories panel, Expand Global repositories then Right click on Central repositories and check "Full index enabled" option and then click on "Rebuild index".
Working from VaLo's answer:
cd %directory to browser%
%browser's name to main executable (firefox, chrome, opera, etc.)% https://www.google.com
start https://www.google.com
doesn't seem to work (at least in my environment)
info
is a pointer to a dictionary - you keep adding the same pointer to your list contact
.
Insert info = {}
into the loop and it should solve the problem:
...
content = []
for iframe in soup.find_all('iframe'):
info = {}
info['src'] = iframe.get('src')
info['height'] = iframe.get('height')
info['width'] = iframe.get('width')
...
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:
BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)
So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.
def dump(obj):
'''return a printable representation of an object for debugging'''
newobj=obj
if '__dict__' in dir(obj):
newobj=obj.__dict__
if ' object at ' in str(obj) and not newobj.has_key('__type__'):
newobj['__type__']=str(obj)
for attr in newobj:
newobj[attr]=dump(newobj[attr])
return newobj
Here is the usage
class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
and the results.
{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
'int': 1,
'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
I would recommend overriding the onResume()
method in activity number 1, and in there include code to refresh your array adapter, this is done by using [yourListViewAdapater].notifyDataSetChanged();
Read this if you are having trouble refreshing the list: Android List view refresh
I already have used Reportlab in one project.
From the command line it would be just:
svn update
(in the directory you've got a copy of a SVN project).
btn1.setId(1);
addRule()
, check
out the android java docs for this
LayoutParams
object.From here:
ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.
If you are not wanting to use async
you can add .Result
to force the code to execute synchronously:
private string GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
var contents = response.Content.ReadAsStringAsync().Result;
return contents;
}
Using flexbox it is super simple!
#parent_div_1, #parent_div_2, #parent_div_3 {
display: flex;
}
>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> import itertools
>>> k.sort()
>>> list(k for k,_ in itertools.groupby(k))
[[1, 2], [3], [4], [5, 6, 2]]
itertools
often offers the fastest and most powerful solutions to this kind of problems, and is well worth getting intimately familiar with!-)
Edit: as I mention in a comment, normal optimization efforts are focused on large inputs (the big-O approach) because it's so much easier that it offers good returns on efforts. But sometimes (essentially for "tragically crucial bottlenecks" in deep inner loops of code that's pushing the boundaries of performance limits) one may need to go into much more detail, providing probability distributions, deciding which performance measures to optimize (maybe the upper bound or the 90th centile is more important than an average or median, depending on one's apps), performing possibly-heuristic checks at the start to pick different algorithms depending on input data characteristics, and so forth.
Careful measurements of "point" performance (code A vs code B for a specific input) are a part of this extremely costly process, and standard library module timeit
helps here. However, it's easier to use it at a shell prompt. For example, here's a short module to showcase the general approach for this problem, save it as nodup.py
:
import itertools
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
def doset(k, map=map, list=list, set=set, tuple=tuple):
return map(list, set(map(tuple, k)))
def dosort(k, sorted=sorted, xrange=xrange, len=len):
ks = sorted(k)
return [ks[i] for i in xrange(len(ks)) if i == 0 or ks[i] != ks[i-1]]
def dogroupby(k, sorted=sorted, groupby=itertools.groupby, list=list):
ks = sorted(k)
return [i for i, _ in itertools.groupby(ks)]
def donewk(k):
newk = []
for i in k:
if i not in newk:
newk.append(i)
return newk
# sanity check that all functions compute the same result and don't alter k
if __name__ == '__main__':
savek = list(k)
for f in doset, dosort, dogroupby, donewk:
resk = f(k)
assert k == savek
print '%10s %s' % (f.__name__, sorted(resk))
Note the sanity check (performed when you just do python nodup.py
) and the basic hoisting technique (make constant global names local to each function for speed) to put things on equal footing.
Now we can run checks on the tiny example list:
$ python -mtimeit -s'import nodup' 'nodup.doset(nodup.k)'
100000 loops, best of 3: 11.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort(nodup.k)'
100000 loops, best of 3: 9.68 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby(nodup.k)'
100000 loops, best of 3: 8.74 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.donewk(nodup.k)'
100000 loops, best of 3: 4.44 usec per loop
confirming that the quadratic approach has small-enough constants to make it attractive for tiny lists with few duplicated values. With a short list without duplicates:
$ python -mtimeit -s'import nodup' 'nodup.donewk([[i] for i in range(12)])'
10000 loops, best of 3: 25.4 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby([[i] for i in range(12)])'
10000 loops, best of 3: 23.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.doset([[i] for i in range(12)])'
10000 loops, best of 3: 31.3 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort([[i] for i in range(12)])'
10000 loops, best of 3: 25 usec per loop
the quadratic approach isn't bad, but the sort and groupby ones are better. Etc, etc.
If (as the obsession with performance suggests) this operation is at a core inner loop of your pushing-the-boundaries application, it's worth trying the same set of tests on other representative input samples, possibly detecting some simple measure that could heuristically let you pick one or the other approach (but the measure must be fast, of course).
It's also well worth considering keeping a different representation for k
-- why does it have to be a list of lists rather than a set of tuples in the first place? If the duplicate removal task is frequent, and profiling shows it to be the program's performance bottleneck, keeping a set of tuples all the time and getting a list of lists from it only if and where needed, might be faster overall, for example.
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.
Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.
But, I think you already read it on SO; here you have the documentation you want:
Cited from
Apple Developer Relations
10-Oct-2014 09:12 PM
After much deliberation, engineering has removed this feature. The file
/etc/launchd.conf
was intentionally removed for security reasons. As a workaround, you could runlaunchctl limit
as root early during boot, perhaps from aLaunchDaemon
. (...)
Solution:
Put code in to
/Library/LaunchDaemons/com.apple.launchd.limit.plist
by bash-script:
#!/bin/bash
echo '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>eicar</string>
<key>ProgramArguments</key>
<array>
<string>/bin/launchctl</string>
<string>limit</string>
<string>core</string>
<string>unlimited</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>ServiceIPC</key>
<false/>
</dict>
</plist>' | sudo tee /Library/LaunchDaemons/com.apple.launchd.limit.plist
Also for the Google-fodder: check in your text editor whether the .js file is saved as Unicode and consider setting it to ANSI; also check if the linefeeds are set to DOS and consider switching them to Unix (depending on your server, of course).
The data received in your serialPort1_DataReceived
method is coming from another thread context than the UI thread, and that's the reason you see this error.
To remedy this, you will have to use a dispatcher as descibed in the MSDN article:
How to: Make Thread-Safe Calls to Windows Forms Controls
So instead of setting the text property directly in the serialport1_DataReceived
method, use this pattern:
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
So in your case:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
txt += serialPort1.ReadExisting().ToString();
SetText(txt.ToString());
}
Here is example given which so how to use open
and "python close
from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()
It's necessary to how many times you opened file have to close that times.
Why is that not acceptable?
document.getElementById('test').innerHTML += str
would be the textbook way of doing it.
This concerns Java versions 7 and earlier.
To quote a good answer to the same question:
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
public static String combine (String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
Function is the concept mainly belonging to Procedure oriented programming where a function is an an entity which can process data and returns you value
Method is the concept of Object Oriented programming where a method is a member of a class which mostly does processing on the class members.
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
For case1:
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
FROM TAB_TEACHER
WHERE name_teacher = 'Professor Jack'
LIMIT 1
For case2 you just have to do 2 separate insert statements
Manage multiple java version in MAC using jenv
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew install jenv
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
brew tap homebrew/cask-versions
brew search java
brew install cask java6
jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note:- if you get error like “”ln: /Users//.jenv/versions/oracle64-1.8.0.231: No such file or directory, then run following:-
mkdir -p /Users//.jenv/versions/oracle64-1.8.0.231
jenv rehash
jenv versions
jenv global oracle64-1.8.0.231
jenv local oracle64-1.6.0.65
jenv exec bash
echo $JAVA_HOME
A JavaScript function must first be made that holds what you want to be done:
function print() { console.log("Hello World!") }
and then that function must be called in the onClick method from inside an element:
<a onClick="print()"> ... </a>
You can learn more about modal interactions directly from the Bootstrap 3 documentation found here: http://getbootstrap.com/javascript/#modals
Your modal bind is also incorrect. It should be something like this, where "myModal" = ID of element:
$('#myModal').modal(options)
In other words, if you truly want to keep what you already have, put a "#" in front GSCCModal and see if that works.
It is also not very wise to have an onClick bound to a div element; something like a button would be more suitable.
Hope this helps!
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
If you have a hardlink to pip in your PATH
(i.e. if you have multiple python versions installed) and then you upgrade pip, you may also encounter this error.
The solution consists in creating the hardlink again. Or even better, stop using hardlinks and use softlinks.
If you want the keys and values, you can always do this via the entrySet
:
hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]
From each entry you can (of course) get both the key and value via the getKey
and getValue
methods
I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.
The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.
After going through other answers I came up with this, just apply class nested-counter-list
to root ol
tag:
sass code:
ol.nested-counter-list {
counter-reset: item;
li {
display: block;
&::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
}
ol {
counter-reset: item;
& > li {
display: block;
&::before {
content: counters(item, ".") " ";
counter-increment: item;
font-weight: bold;
}
}
}
}
css code:
ol.nested-counter-list {
counter-reset: item;
}
ol.nested-counter-list li {
display: block;
}
ol.nested-counter-list li::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list ol {
counter-reset: item;
}
ol.nested-counter-list ol > li {
display: block;
}
ol.nested-counter-list ol > li::before {
content: counters(item, ".") " ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list {
counter-reset: item;
}
ol.nested-counter-list li {
display: block;
}
ol.nested-counter-list li::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list ol {
counter-reset: item;
}
ol.nested-counter-list ol>li {
display: block;
}
ol.nested-counter-list ol>li::before {
content: counters(item, ".") " ";
counter-increment: item;
font-weight: bold;
}
_x000D_
<ol class="nested-counter-list">
<li>one</li>
<li>two
<ol>
<li>two.one</li>
<li>two.two</li>
<li>two.three</li>
</ol>
</li>
<li>three
<ol>
<li>three.one</li>
<li>three.two
<ol>
<li>three.two.one</li>
<li>three.two.two</li>
</ol>
</li>
</ol>
</li>
<li>four</li>
</ol>
_x000D_
And if you need trailing .
at the end of the nested list's counters use this:
ol.nested-counter-list {
counter-reset: item;
}
ol.nested-counter-list li {
display: block;
}
ol.nested-counter-list li::before {
content: counters(item, ".") ". ";
counter-increment: item;
font-weight: bold;
}
ol.nested-counter-list ol {
counter-reset: item;
}
_x000D_
<ol class="nested-counter-list">
<li>one</li>
<li>two
<ol>
<li>two.one</li>
<li>two.two</li>
<li>two.three</li>
</ol>
</li>
<li>three
<ol>
<li>three.one</li>
<li>three.two
<ol>
<li>three.two.one</li>
<li>three.two.two</li>
</ol>
</li>
</ol>
</li>
<li>four</li>
</ol>
_x000D_
Below are the complete changes I needed to make to run my x64 bit IIS application using IIS Express, so that it was accessible to a remote host:
iisexpress /config:"C:\Users\test-user\Documents\IISExpress\config\applicationhost.config" /site:MyWebSite
Starting IIS Express ...
Successfully registered URL "http://192.168.2.133:8080/" for site "MyWebSite" application "/"
Registration completed for site "MyWebSite"
IIS Express is running.
Enter 'Q' to stop IIS Express
The configuration file (applicationhost.config) had a section added as follows:
<sites>
<site name="MyWebsite" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\build\trunk\MyWebsite" />
</application>
<bindings>
<binding protocol="http" bindingInformation=":8080:192.168.2.133" />
</bindings>
</site>
The 64 bit version of the .NET framework can be enabled as follows:
<globalModules>
<!--
<add name="ManagedEngine" image="%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness32" />
<add name="ManagedEngineV4.0_32bit" image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness32" />
-->
<add name="ManagedEngine64" image="%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness64" />
I have Git version 2.7.4 with the following settings:
git config --global log.abbrevcommit yes
git config --global core.abbrev 8
Now when I do:
git log --pretty=oneline
I get an abbreviated commit id of eight digits:
ed054a38 add project based .gitignore
30a3fa4c add ez version
0a6e9015 add logic for shifting days
af4ab954 add n days ago
...
As it's 2018, use flexbox - no more inline-block
whitespace issues:
body {
margin: 0;
}
#wrapper {
display: flex;
height: 200px;
}
#wrapper > div {
flex-grow: 1;
}
#wrapper > div:first-of-type { background-color: red }
#wrapper > div:nth-of-type(2) { background-color: blue }
#wrapper > div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
_x000D_
Or even CSS grid if you are creating a grid.
body {
margin: 0;
}
#wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(200px, auto);
}
#wrapper>div:first-of-type { background-color: red }
#wrapper>div:nth-of-type(2) { background-color: blue }
#wrapper>div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
_x000D_
Use CSS calc()
:
body {
margin: 0;
}
div {
height: 200px;
width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */
width: calc(100% / 3);
display: inline-block;
}
div:first-of-type { background-color: red }
div:nth-of-type(2) { background-color: blue }
div:nth-of-type(3) { background-color: green }
_x000D_
<div></div><div></div><div></div>
_x000D_
References:
Read the image, convert it to byte[]
, then return a File()
with a content type.
public ActionResult ImageResult(Image image, ImageFormat format, string contentType) {
using (var stream = new MemoryStream())
{
image.Save(stream, format);
return File(stream.ToArray(), contentType);
}
}
}
Here are the usings:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.AspNetCore.Mvc;
Leveraging the power of java.util.Optional#map()
:
List<Car> requiredCars = cars.stream()
.filter (car ->
Optional.ofNullable(car)
.map(Car::getName)
.map(name -> name.startsWith("M"))
.orElse(false) // what to do if either car or getName() yields null? false will filter out the element
)
.collect(Collectors.toList())
;
First install nodemon to your working folder by
npm install nodemon
Add the path of nodemon to the path variable of Environment Variable of System environment. In my case the path of nodemon was.
C:\Users\Dell\Desktop\Internship Project\schema\node_modules\.bin
It worked for me.
There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label
elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log
).
Listening for click
events on checkboxes
is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label
element was clicked. Always listen for the change
event.
Use the jQuery :checkbox
pseudo-selector, rather than input[type=checkbox]
. :checkbox
is shorter and more readable.
Use is()
with the jQuery :checked
pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.
$('#myform :checkbox').change(function () {
if ($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
} else {
console.log($(this).val() + ' is now unchecked');
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/
:checkbox
selector, which is preferable to using input[type=checkbox]
Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).
$('#myform').on('change', ':checkbox', function () {
if ($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
} else {
console.log($(this).val() + ' is now unchecked');
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/
change
) to bubble up to a non-changing ancestor element (in this case #myform
). ':checkbox'
in this case) to only the elements in the bubble chain.document
as the default to connect the delegated event handler, if nothing else is closer/convenient. body
to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.
Q: Is it slower?
A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.
prop('checked', true)
fire the change
event?This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger
(not triggerHandler
):
e.g. without trigger
no event occurs
$cb.prop('checked', !$cb.prop('checked'));
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/
e.g. with trigger
the normal change event is caught
$cb.prop('checked', !$cb.prop('checked')).trigger('change');
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/
Notes:
triggerHandler
as was suggested by one user, as it will not bubble events to a delegated event handler.JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/
although it will work for an event handler directly connected to the element:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/
Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
Reference: http://api.jquery.com/triggerhandler/
If anyone has additional features they feel are not covered by this, please do suggest additions.
Download Microsoft Account Lockout Tools.
Use LockoutStatus
to find the last DC that didn't pre-authenticate the user that is having issues. Note date and time.
Log into that DC, find that timeframe and check Client Address.
Logoff from those servers.
I found a tricky way, just for brainstorm, see the code:
df['a'] = df['A'] # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)
print(df)
the output:
B
A a
one one 0
one 1
one 5
three three 3
three 4
two two 2
The pros is so easy to print, as it returns a dataframe, instead of Groupby Object. And the output looks nice. While the con is that it create a series of redundant data.
Once again the problem with unit-testing comes from manually creating objects using new
operator. Consider passing already created Second
instead:
class First {
private Second second;
public First(int num, Second second) {
this.second = second;
this.num = num;
}
// some other methods...
}
I know this might mean major rewrite of your API, but there is no other way. Also this class doesn't have any sense:
Mockito.when(new Second(any(String.class).thenReturn(null)));
First of all Mockito can only mock methods, not constructors. Secondly, even if you could mock constructor, you are mocking constructor of just created object and never really doing anything with that object.
Location of JRE in Ubuntu:
/usr/lib/jvm/java-7-oracle/jre
Ok, I am definitively late to the party but if you are still looking for an optimal solution I would use the following ( for Java 8 )
Charset inputCharset = Charset.forName("ISO-8859-1");
Path pathToFile = ....
try (BufferedReader br = Files.newBufferedReader( pathToFile, inputCharset )) {
...
}
Try CSS:
<h2 style="color:#069">Process Report</h2>
If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:
<style type="text/css">
h2 {
color:#069;
}
</style>
try keyup instead of change.
<script type="text/javascript">
$(document).ready(function () {
$('#inputDatabaseName').keyup(function () { alert('test'); });
});
</script>
SELECT COUNT(1)
FROM FB
WHERE
Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'
I know it's an old question but I learned alot from the various answers but came up with my own solution as a function. This should dynamically add the parent folder as a prefix to all files that matches a certain pattern but only if it does not have that prefix already.
function Add-DirectoryPrefix($pattern) {
# To debug, replace the Rename-Item with Select-Object
Get-ChildItem -Path .\* -Filter $pattern -Recurse |
Where-Object {$_.Name -notlike ($_.Directory.Name + '*')} |
Rename-Item -NewName {$_.Directory.Name + '-' + $_.Name}
# Select-Object -Property Directory,Name,@{Name = 'NewName'; Expression= {$_.Directory.Name + '-' + $_.Name}}
}
https://gist.github.com/kmpm/4f94e46e569ae0a4e688581231fa9e00
Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.
using ThisNamespace.IsImported.InAllNamespaces.Here;
namespace Namespace1
{
using ThisNamespace.IsImported.InNamespace1.AndNamespace2;
namespace Namespace2
{
using ThisNamespace.IsImported.InJustNamespace2;
}
}
namespace Namespace3
{
using ThisNamespace.IsImported.InJustNamespace3;
}
You can also disable SSL verification, (if the project does not require a high level of security other than login/password) by typing :
git config --global http.sslverify false
enjoy git :)
Put this code to your view controller in which you hide status bar:
- (BOOL)prefersStatusBarHidden {return YES;}
Per google official documentation, use %1$s and %2$s http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
Hello, %1$s! You have %2$d new messages.