You can reference those remote tracking branches ~(listed with git branch -r
) with the name of their remote.
You need to fetch the remote branch:
git fetch origin aRemoteBranch
If you want to merge one of those remote branches on your local branch:
git checkout master
git merge origin/aRemoteBranch
Note 1: For a large repo with a long history, you will want to add the --depth=1
option when you use git fetch
.
Note 2: These commands also work with other remote repos so you can setup an origin
and an upstream
if you are working on a fork.
Note 3: user3265569 suggests the following alias in the comments:
From
aLocalBranch
, rungit combine remoteBranch
Alias:combine = !git fetch origin ${1} && git merge origin/${1}
Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:
git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch
The idea here, is to merge "one of your local branch" (here anotherLocalBranch
) to a remote branch (origin/aBranch
).
For that, you create first "myBranch
" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch
part.
And then you can merge anotherLocalBranch
to it (to myBranch
).
If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.
Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.
Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"
Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:
Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:
plt.figure(figsize=(10,10)) # specifying the overall grid size
for i in range(25):
plt.subplot(5,5,i+1) # the number of images in the grid is 5*5 (25)
plt.imshow(the_array[i])
plt.show()
Also note that I used subplot and not subplots. They're both different
This shows the number of connections per each DB:
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
And this gives the total:
SELECT
COUNT(dbid) as TotalConnections
FROM
sys.sysprocesses
WHERE
dbid > 0
If you need more detail, run:
sp_who2 'Active'
Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)
A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html
Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.
A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.
It is and old question but let me add a detail just in case more people like me arrive here.
The excellent answer posted by Brian is not working for me in Jelly Bean. I have to add also:
browser.setInitialScale(30);
The parameter can be any percentage tha accomplishes that the resized content is smaller than the webview width. Then setUseWideViewPort(true) extends the content width to the maximum of the webview width.
This is a Python 101 type question,
It's a simple question but one where the answer is not so simple.
In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.
To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.
Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.
If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.
print(bytesThing)
Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.
While I think this compiler error is a good thing, there is a way you can work around it. Use a condition you know will be true:
public void myMethod(){
someCodeHere();
if(1 < 2) return; // compiler isn't smart enough to complain about this
moreCodeHere();
}
The compiler is not smart enough to complain about that.
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
If your are on windows you can do it this way :
ng serve --host 192.168.1.2 --open
This not standard way but comfortable to use (which I feel).
Guido has a good explanation of this here. Here's the most relevant part:
I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn't view Python as a functional programming language. However, earlier on, it was clear that users wanted to do much more with lists and functions.
...
It is also worth noting that even though I didn't envision Python as a functional language, the introduction of closures has been useful in the development of many other advanced programming features. For example, certain aspects of new-style classes, decorators, and other modern features rely upon this capability.
Lastly, even though a number of functional programming features have been introduced over the years, Python still lacks certain features found in “real” functional programming languages. For instance, Python does not perform certain kinds of optimizations (e.g., tail recursion). In general, because Python's extremely dynamic nature, it is impossible to do the kind of compile-time optimization known from functional languages like Haskell or ML. And that's fine.
I pull two things out of this:
Even though it is not "the Android way" I have gotten very good results by handling orientation changes myself and simply repositioning the widgets within a view to take the altered orientation into account. This is faster than any other approach, because your views do not have to be saved and restored. It also provides a more seamless experience to the user, because the respositioned widgets are exactly the same widgets, just moved and/or resized. Not only model state, but also view state, can be preserved in this manner.
RelativeLayout
can sometimes be a good choice for a view that has to reorient itself from time to time. You just provide a set of portrait layout params and a set of landscaped layout params, with different relative positioning rules on each, for each child widget. Then, in your onConfigurationChanged()
method, you pass the appropriate one to a setLayoutParams()
call on each child. If any child control itself needs to be internally reoriented, you just call a method on that child to perform the reorientation. That child similarly calls methods on any of its child controls that need internal reorientation, and so on.
You should try
if (row.Table.Columns.Contains("US_OTHERFRIEND"))
I don't believe that row has a columns property itself.
how does rails know that
user_id
is a foreign key referencinguser
?
Rails itself does not know that user_id
is a foreign key referencing user
. In the first command rails generate model Micropost user_id:integer
it only adds a column user_id
however rails does not know the use of the col. You need to manually put the line in the Micropost
model
class Micropost < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :microposts
end
the keywords belongs_to
and has_many
determine the relationship between these models and declare user_id
as a foreign key to User
model.
The later command rails generate model Micropost user:references
adds the line belongs_to :user
in the Micropost
model and hereby declares as a foreign key.
FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench
you find that there is no relationship threads drawn between the models. Like in the following pic
However, if you use the later method you find that you migration file looks like:
def change
create_table :microposts do |t|
t.references :user, index: true
t.timestamps null: false
end
add_foreign_key :microposts, :users
Now the foreign key is set at the database level. and you can generate proper EER
diagrams.
variables defined with var are mutable(Read and Write)
variables defined with val are immutable(Read only)
Kotlin can remove findViewById and reduce code for setOnClickListener in android studio. For full reference: Kotlin awesome features
value of mutable variables can be changed at anytime, while you can not change value of immutable variables.
where should I use var and where val ?
use var where value is changing frequently. For example while getting location of android device
var integerVariable : Int? = null
use val where there is no change in value in whole class. For example you want set textview or button's text programmatically.
val stringVariables : String = "Button's Constant or final Text"
Alternatively, you could create a regular Mac OS X application from your script using Platypus
root.configure(background='black')
or more generally
<widget>.configure(background='black')
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName
to grab all input elements, and loop through the resulting array. Elements with name
starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
IP Version 4 Only ...
Imports System.Net
Module MainLine
Sub Main()
Dim hostName As String = Dns.GetHostName
Console.WriteLine("Host Name: " & hostName & vbNewLine)
Console.WriteLine("IP Version 4 Address(es):")
For Each address In Dns.GetHostEntry(hostName).AddressList().
Where(Function(p) p.AddressFamily = Sockets.AddressFamily.InterNetwork)
Console.WriteLine(vbTab & address.ToString)
Next
Console.ReadKey()
End Sub
End Module
If you are looking for a plain JS solution, then you just use insertBefore()
against nextSibling
.
Something like:
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
Note that default value of nextSibling
is null
, so, you don't need to do anything special for that.
Update: You don't even need the if
checking presence of parentGuest.nextSibling
like the currently accepted answer does, because if there's no next sibling, it will return null
, and passing null
to the 2nd argument of insertBefore()
means: append at the end.
Reference:
.
IF you are using jQuery (ignore otherwise, I have stated plain JS answer above), you can leverage the convenient after()
method:
$("#one").after("<li id='two'>");
Reference:
Use Math.Max
:
int x = 3, y = 4, z = 5;
Console.WriteLine(Math.Max(Math.Max(x, y), z));
I always come to this question when I hit an error in the test environment and remember, "I've done this before, but I can do it straight in the web.config without having to modify code and re-deploy to the test environment, but it takes 2 changes... what was it again?"
For future reference
<system.web>
<customErrors mode="Off"></customErrors>
</system.web>
AND
<system.webServer>
<httpErrors errorMode="Detailed" existingResponse="PassThrough"></httpErrors>
</system.webServer>
Suppose you need to pass an arraylist of following class from current activity to next activity // class of the objects those in the arraylist // remember to implement the class from Serializable interface // Serializable means it converts the object into stream of bytes and helps to transfer that object
public class Question implements Serializable {
...
...
...
}
in your current activity you probably have an ArrayList as follows
ArrayList<Question> qsList = new ArrayList<>();
qsList.add(new Question(1));
qsList.add(new Question(2));
qsList.add(new Question(3));
// intialize Bundle instance
Bundle b = new Bundle();
// putting questions list into the bundle .. as key value pair.
// so you can retrieve the arrayList with this key
b.putSerializable("questions", (Serializable) qsList);
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
i.putExtras(b);
startActivity(i);
in order to get the arraylist within the next activity
//get the bundle
Bundle b = getIntent().getExtras();
//getting the arraylist from the key
ArrayList<Question> q = (ArrayList<Question>) b.getSerializable("questions");
And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:
In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
'WBAN',
'day',
'month',
's_CDsum',
's_CLsum',
's_CNTsum',
's_PCsum',
'tempfamax',
'tempfamin',
'year']
In [2]: df.columns = new_cols
There isn't a direct 1:1 equivalent.
You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.
If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/
As far as I can tell, at this point it is not possible to set click_action in the console.
While not a strict answer to how to get the click_action set in the console, you can use curl as an alternative:
curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"/topics/news\",\"notification\": {\"title\": \"Click Action Message\",\"text\": \"Sample message\",\"click_action\":\"OPEN_ACTIVITY_1\"}}"
This is an easy way to test click_action mapping. It requires an intent filter like the one specified in the FCM docs:
<intent-filter>_x000D_
<action android:name="OPEN_ACTIVITY_1" />_x000D_
<category android:name="android.intent.category.DEFAULT" />_x000D_
</intent-filter>
_x000D_
This also makes use of topics to set the audience. In order for this to work you will need to subscribe to a topic called "news".
FirebaseMessaging.getInstance().subscribeToTopic("news");
Even though it takes several hours to see a newly-created topic in the console, you may still send messages to it through the FCM apis.
Also, keep in mind, this will only work if the app is in the background. If it is in the foreground you will need to implement an extension of FirebaseMessagingService. In the onMessageReceived method, you will need to manually navigate to your click_action target:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//This will give you the topic string from curl request (/topics/news)
Log.d(TAG, "From: " + remoteMessage.getFrom());
//This will give you the Text property in the curl request(Sample Message):
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//This is where you get your click_action
Log.d(TAG, "Notification Click Action: " + remoteMessage.getNotification().getClickAction());
//put code here to navigate based on click_action
}
As I said, at this time I cannot find a way to access notification payload properties through the console, but I thought this work around might be helpful.
There are several possibilities:
You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.
You are not getting the posted value. Try your code with a static value.
Use SMTP mails to send mail...
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity
printf("\nmaximum of %d and %d is = %d",a,b,c);
if you already cd your project type only in windows 10
Scripts/activate
That works for me:)
You can try this(Python-for-PDF-Generation) or you can try PyQt, which has support for printing to pdf.
Python for PDF Generation
The Portable Document Format (PDF) lets you create documents that look exactly the same on every platform. Sometimes a PDF document needs to be generated dynamically, however, and that can be quite a challenge. Fortunately, there are libraries that can help. This article examines one of those for Python.
Read more at http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/#whoCFCPh3TAks368.99
If you have pip
installed (you should have it until you use Python 3.5), list the installed Python packages, like this:
$ pip list | grep -i keras
Keras (1.1.0)
If you don’t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)
Consult the pip.log
to see what’s wrong.
You can also display your Python path like this:
$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages
path (the path is different on Ubuntu).
If not, try do uninstall it, and retry installation:
$ pip uninstall Keras
It’s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).
The best usage is to create a virtualenv
directory (in your home, for instance), and store your virtualenvs in:
cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel
Then install Keras:
pip install keras
You get:
$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)
But, you also need to install extra libraries, like Tensorflow:
$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
...
ImportError: No module named 'tensorflow'
The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation
abarnert
's answer is very good and pythonic. Another completely different route (not in python) is to let bash do this for you:
$ python myscript.py > myoutput.txt
This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to file for more.
Something like this?
The idea is to wrap the <table>
in a non-statically positioned <div>
which has an overflow:auto
CSS property. Then position the elements in the <thead>
absolutely.
#table-wrapper {_x000D_
position:relative;_x000D_
}_x000D_
#table-scroll {_x000D_
height:150px;_x000D_
overflow:auto; _x000D_
margin-top:20px;_x000D_
}_x000D_
#table-wrapper table {_x000D_
width:100%;_x000D_
_x000D_
}_x000D_
#table-wrapper table * {_x000D_
background:yellow;_x000D_
color:black;_x000D_
}_x000D_
#table-wrapper table thead th .text {_x000D_
position:absolute; _x000D_
top:-20px;_x000D_
z-index:2;_x000D_
height:20px;_x000D_
width:35%;_x000D_
border:1px solid red;_x000D_
}
_x000D_
<div id="table-wrapper">_x000D_
<div id="table-scroll">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><span class="text">A</span></th>_x000D_
<th><span class="text">B</span></th>_x000D_
<th><span class="text">C</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr> <td>1, 0</td> <td>2, 0</td> <td>3, 0</td> </tr>_x000D_
<tr> <td>1, 1</td> <td>2, 1</td> <td>3, 1</td> </tr>_x000D_
<tr> <td>1, 2</td> <td>2, 2</td> <td>3, 2</td> </tr>_x000D_
<tr> <td>1, 3</td> <td>2, 3</td> <td>3, 3</td> </tr>_x000D_
<tr> <td>1, 4</td> <td>2, 4</td> <td>3, 4</td> </tr>_x000D_
<tr> <td>1, 5</td> <td>2, 5</td> <td>3, 5</td> </tr>_x000D_
<tr> <td>1, 6</td> <td>2, 6</td> <td>3, 6</td> </tr>_x000D_
<tr> <td>1, 7</td> <td>2, 7</td> <td>3, 7</td> </tr>_x000D_
<tr> <td>1, 8</td> <td>2, 8</td> <td>3, 8</td> </tr>_x000D_
<tr> <td>1, 9</td> <td>2, 9</td> <td>3, 9</td> </tr>_x000D_
<tr> <td>1, 10</td> <td>2, 10</td> <td>3, 10</td> </tr>_x000D_
<!-- etc... -->_x000D_
<tr> <td>1, 99</td> <td>2, 99</td> <td>3, 99</td> </tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
You can install opencv in a simple way
$ pip install opencv-python
If u are having errors, you can do this
$ pip install opencv-python-headless
Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.
If you already have test classes you may:
1) Put a cursor on a class declaration and press Alt
+ Enter
. In the dialogue choose JUnit and press Fix
. This is a standard way to create test classes in IntelliJ.
2) Alternatively you may add JUnit jars manually (download from site or take from IntelliJ files).
The .Equals()
works for me while TKey
is a generic type.
public virtual TOutputDto GetOne(TKey id)
{
var entity =
_unitOfWork.BaseRepository
.FindByCondition(x =>
!x.IsDelete &&
x.Id.Equals(id))
.SingleOrDefault();
// ...
}
Reformat affects the whole source code and may rebreak your lines, while Correct Indentation only affects the whitespace at the beginning of the lines.
Why not combine the onclick method with the <a>
element inside the <td>
for backup for non-JS? Seems to work great.
<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>
You can use NSNotification
Add a post method in your custom class:
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Add an observer in your ViewController:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
Add function in you ViewController:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
Try the -fno-stack-protector
flag.
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
result = initial number + (6 - initial number % 6)
<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;
$.ajax({
type:"GET",
url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
crossDomain:true,
dataType:'jsonp',
success: function jsondata(data)
{
var parsedata=JSON.parse(JSON.stringify(data));
var logindata=parsedata["Status"];
if("sucess"==logindata)
{
alert("success");
}
else
{
alert("failed");
}
}
});
<script>
You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.
MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
Modify your CSS like this:
.vertical_banner {_x000D_
border: 1px solid #E9E3DD;_x000D_
float: left;_x000D_
height: 210px;_x000D_
margin: 2px;_x000D_
padding: 4px 2px 10px 10px;_x000D_
text-align: left;_x000D_
width: 117px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
position:absolute; /* added */_x000D_
bottom:0; /* added */_x000D_
left:0; /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
<div id="bottom_link">_x000D_
<input type="submit" value="Continue">_x000D_
</div>_x000D_
</div>
_x000D_
That restricts T
to reference types. You won't be able to put value types (struct
s and primitive types except string
) there.
For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.
Next code contains only pure and pointfree functions:
const R = require('ramda');
const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
const equalsSyncFunction = isPrototypeEquals(() => {});
const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
As of ES2017, async
functions are available, so we can check against them as well:
const equalsAsyncFunction = isPrototypeEquals(async () => {});
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
And then combine them together:
const isFunction = R.either(isSyncFunction, isAsyncFunction);
Of course, function should be protected against null
and undefined
values, so to make it "safe":
const safeIsFunction = R.unless(R.isNil, isFunction);
And, complete snippet to sum up:
const R = require('ramda');
const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});
const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
const isFunction = R.either(isSyncFunction, isAsyncFunction);
const safeIsFunction = R.unless(R.isNil, isFunction);
// ---
console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));
However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.
This is how I've added a bot to my channel and set up notifications:
telegram.me/whateverIWantAndAvailable
the channel id will be @whateverIWantAndAvailable
Now set up your bot to send notifications by pusshing the messages here:
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test
the message which bot will notify is: Test
I strongly suggest an urlencode of the message like
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works
in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");
I hope it helps
A Spring Boot with Thymeleaf solution could look like:
Lets say my context-path is /app/
In Thymeleaf you can get it via:
<script th:inline="javascript">
/*<![CDATA[*/
let contextPath = /*[[@{/}]]*/
/*]]>*/
</script>
Yes, you can merge them using HTML. When I create tables in .md
files from Github, I always like to use HTML code instead of markdown.
Github Flavored Markdown supports basic HTML in .md
file. So this would be the answer:
Markdown mixed with HTML:
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|
Or pure HTML:
<table>
<tbody>
<tr>
<th>Tables</th>
<th align="center">Are</th>
<th align="right">Cool</th>
</tr>
<tr>
<td>col 3 is</td>
<td align="center">right-aligned</td>
<td align="right">$1600</td>
</tr>
<tr>
<td>col 2 is</td>
<td align="center">centered</td>
<td align="right">$12</td>
</tr>
<tr>
<td>zebra stripes</td>
<td align="center">are neat</td>
<td align="right">$1</td>
</tr>
<tr>
<td>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
</td>
<td align="center">See the list</td>
<td align="right">from the first column</td>
</tr>
</tbody>
</table>
This is how it looks on Github:
If jQuery
is loading asynchronously, you can wait till it is defined, checking for it every period of time:
(function() {
var a = setInterval( function() {
if ( typeof window.jQuery === 'undefined' ) {
return;
}
clearInterval( a );
console.log( 'jQuery is loaded' ); // call your function with jQuery instead of this
}, 500 );
})();
This method can be used for any variable, you are waiting to appear.
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
If you are using modal use view dismiss.
[self dismissViewControllerAnimated:NO completion:nil];
var input = {"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
Object.keys(input.document.people[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
keys.push(key);
}
});
}
console.log(keys);
Top can be compiled from sources or downloaded from sunfreeware.com. As previously posted, vmstat is available (I believe it's in the core install?).
Why do you need a cursor at all? Your entire segment of code can be replaced by this, which will run a lot faster on large numbers of rows.
UPDATE tarinvoice set confirmtocntctkey = PrimaryCntctKey
FROM tarinvoice INNER JOIN tarcustomer ON tarinvoice.custkey = tarcustomer.custkey
WHERE confirmtocntctkey is null and tranno like '%115876'
Markdown syntax for images (external/internal):
![test](https://github.com/favicon.ico)
HTML code for sizing images (internal/external):
<img src="https://github.com/favicon.ico" width="48">
Example:
This should work:
[[ http://url.to/image.png | height = 100px ]]
Source: https://guides.github.com/features/mastering-markdown/
It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386
Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.
The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.
To avoid name clashes, something like this usually works:
declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);
This insures the name is always unique even between simultaneous executions of the same procedure.
Open for new app "HTTPD" (Apache server) in your Firewall
Take a look at this: https://www.youtube.com/watch?v=eqgUGF3NnuM
To get a cookie splitter to work with cookies that have '=' in the cookie values:
var get_cookies = function(request) {
var cookies = {};
request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
var parts = cookie.match(/(.*?)=(.*)$/)
cookies[ parts[1].trim() ] = (parts[2] || '').trim();
});
return cookies;
};
then to get an individual cookie:
get_cookies(request)['my_cookie']
Just use:
git reset HEAD <filename>
This unstages the file and keeps the changes you did to it, so you can, in turn, change branches if you wanted and git add
those files to another branch instead. All changes are kept.
Just to supplement the answers already given, if you also want to NOT minify/obfuscate/concatenate SOME files while still allowing full bundling and minification for other files the best option is to go with a custom renderer which will read the contents of a particular bundle(s) and render the files in the page rather than render the bundle's virtual path. I personally required this because IE 9 was $*%@ing the bed when my CSS files were being bundled even with minification turned off.
Thanks very much to this article, which gave me the starting point for the code which I used to create a CSS Renderer which would render the files for the CSS but still allow the system to render my javascript files bundled/minified/obfuscated.
Created the static helper class:
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
namespace Helpers
{
public static class OptionalCssBundler
{
const string CssTemplate = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
public static MvcHtmlString ResolveBundleUrl(string bundleUrl, bool bundle)
{
return bundle ? BundledFiles(BundleTable.Bundles.ResolveBundleUrl(bundleUrl)) : UnbundledFiles(bundleUrl);
}
private static MvcHtmlString BundledFiles(string bundleVirtualPath)
{
return new MvcHtmlString(string.Format(CssTemplate, bundleVirtualPath));
}
private static MvcHtmlString UnbundledFiles(string bundleUrl)
{
var bundle = BundleTable.Bundles.GetBundleFor(bundleUrl);
StringBuilder sb = new StringBuilder();
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
foreach (BundleFile file in bundle.EnumerateFiles(new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, bundleUrl)))
{
sb.AppendFormat(CssTemplate + Environment.NewLine, urlHelper.Content(file.VirtualFile.VirtualPath));
}
return new MvcHtmlString(sb.ToString());
}
public static MvcHtmlString Render(string bundleUrl, bool bundle)
{
return ResolveBundleUrl(bundleUrl, bundle);
}
}
}
Then in the razor layout file:
@OptionalCssBundler.Render("~/Content/css", false)
instead of the standard:
@Styles.Render("~/Content/css")
I am sure creating an optional renderer for javascript files would need little to update to this helper as well.
In my situation, the problem was nginx docker container disk space. I had 10GB of logs and when I reduce this amount it works.
Enter in your container: docker exec -it <container_id> bash
Go to your logs, for example: cd /var/log/nginx
.
[optional] Show file size: ls -lh
for individual file size or du -h
for folder size.
Empty file(s) with > file_name
.
It works!.
Empty your nginx log with > file_name
or similar.
Hope it helps
Best and easiest way is to use anchor tag in CodeIgniter like eg.
<?php
$this->load->helper('url');
echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => ''));
?>
Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details
This will surely work.
I found that it's easy to write an app that can open another app.
Let's assume that we have two apps called FirstApp
and SecondApp
. When we open the FirstApp, we want to be able to open the SecondApp by clicking a button. The solution to do this is:
In SecondApp
Go to the plist file of SecondApp and you need to add a URL Schemes with a string iOSDevTips(of course you can write another string.it's up to you).
2 . In FirstApp
Create a button with the below action:
- (void)buttonPressed:(UIButton *)button
{
NSString *customURL = @"iOSDevTips://";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL error"
message:[NSString stringWithFormat:@"No custom URL defined for %@", customURL]
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
}
That's it. Now when you can click the button in the FirstApp it should open the SecondApp.
The BackgroundWorker is nice when developing for Windows Forms.
Say you wanted to pass a simple class back and forth:
class Anything {
// Number and Text are for instructional purposes only
public int Number { get; set; }
public string Text { get; set; }
// Data can be any object - even another class
public object Data { get; set; }
}
I wrote up a short class that does the following:
From inside the thread routine:
Adding a delegate can be useful for posting your data directly back to your main thread, but you may need to use Invoke if some of the data items are not thread safe.
class AnyTask {
private object m_lock;
public AnyTask() {
m_lock = new object();
}
// Something to use the delegate
public event MainDelegate OnUpdate;
public void Test_Function(int count) {
var list = new List<Thread>(count);
for (var i = 0; i < count; i++) {
var thread = new Thread(new ParameterizedThreadStart(Thread_Task));
var item = new Anything() {
Number = i,
Text = String.Format("Test_Function #{0}", i)
};
thread.Start(item);
list.Add(thread);
}
foreach (var thread in list) {
thread.Join();
}
}
private void MainUpdate(Anything item, bool original) {
if (OnUpdate != null) {
OnUpdate(item, original);
}
}
private void Thread_Task(object parameter) {
lock (m_lock) {
var item = (Anything)parameter;
MainUpdate(item, true);
item.Text = String.Format("{0}; Thread_Task #{1}", item.Text, item.Number);
item.Number = 0;
MainUpdate(item, false);
}
}
}
To test this, create a little Console Application, and put this in the Program.cs file:
// A delegate makes life simpler
delegate void MainDelegate(Anything sender, bool original);
class Program {
private const int COUNT = 15;
private static List<Anything> m_list;
static void Main(string[] args) {
m_list = new List<Anything>(COUNT);
var obj = new AnyTask();
obj.OnUpdate += new MainDelegate(ThreadMessages);
obj.Test_Function(COUNT);
Console.WriteLine();
foreach (var item in m_list) {
Console.WriteLine("[Complete]:" + item.Text);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static void ThreadMessages(Anything item, bool original) {
if (original) {
Console.WriteLine("[main method]:" + item.Text);
} else {
m_list.Add(item);
}
}
}
Here is a screenshot of what I got with this:
I hope others can understand what I've tried to explain.
I enjoy working on threads and using delegates. They make C# a lot of fun.
I wanted to see what was involved in writing the code above as a VB Console Application. The conversion involved a few things I didn't expect, so I will update this thread here for those wanting to know how to thread in VB.
Imports System.Threading
Delegate Sub MainDelegate(sender As Anything, original As Boolean)
Class Main
Private Const COUNT As Integer = 15
Private Shared m_list As List(Of Anything)
Public Shared Sub Main(args As String())
m_list = New List(Of Anything)(COUNT)
Dim obj As New AnyTask()
AddHandler obj.OnUpdate, New MainDelegate(AddressOf ThreadMessages)
obj.Test_Function(COUNT)
Console.WriteLine()
For Each item As Anything In m_list
Console.WriteLine("[Complete]:" + item.Text)
Next
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
Private Shared Sub ThreadMessages(item As Anything, original As Boolean)
If original Then
Console.WriteLine("[main method]:" + item.Text)
Else
m_list.Add(item)
End If
End Sub
End Class
Class AnyTask
Private m_lock As Object
Public Sub New()
m_lock = New Object()
End Sub
' Something to use the delegate
Public Event OnUpdate As MainDelegate
Public Sub Test_Function(count As Integer)
Dim list As New List(Of Thread)(count)
For i As Int32 = 0 To count - 1
Dim thread As New Thread(New ParameterizedThreadStart(AddressOf Thread_Task))
Dim item As New Anything()
item.Number = i
item.Text = String.Format("Test_Function #{0}", i)
thread.Start(item)
list.Add(thread)
Next
For Each thread As Thread In list
thread.Join()
Next
End Sub
Private Sub MainUpdate(item As Anything, original As Boolean)
RaiseEvent OnUpdate(item, original)
End Sub
Private Sub Thread_Task(parameter As Object)
SyncLock m_lock
Dim item As Anything = DirectCast(parameter, Anything)
MainUpdate(item, True)
item.Text = [String].Format("{0}; Thread_Task #{1}", item.Text, item.Number)
item.Number = 0
MainUpdate(item, False)
End SyncLock
End Sub
End Class
Class Anything
' Number and Text are for instructional purposes only
Public Property Number() As Integer
Get
Return m_Number
End Get
Set(value As Integer)
m_Number = value
End Set
End Property
Private m_Number As Integer
Public Property Text() As String
Get
Return m_Text
End Get
Set(value As String)
m_Text = value
End Set
End Property
Private m_Text As String
' Data can be anything or another class
Public Property Data() As Object
Get
Return m_Data
End Get
Set(value As Object)
m_Data = value
End Set
End Property
Private m_Data As Object
End Class
If you are on a linux machine running Python 2 you can run this commands:
1st make sure python 2 is installed:
python2 --version
2nd check to see if pip is installed:
pip --version
If you are running Python 3 you can run this command:
1st make sure python 3 is installed:
python3 --version
2nd check to see if pip3 is installed:
pip3 --version
If you do not have pip installed you can run these commands to install pip (it is recommended you install pip for Python 2 and Python 3):
Install pip for Python 2:
sudo apt install python-pip
Then verify if it is installed correctly:
pip --version
Install pip for Python 3:
sudo apt install python3-pip
Then verify if it is installed correctly:
pip3 --version
For more info see: https://itsfoss.com/install-pip-ubuntu/
UPDATE
I would like to mention a few things. When working with Django I learned that my Linux install requires me to use python 2.7, so switching my default python version for the python
and pip
command alias's to python 3 with alias python=python3
is not recommended. Therefore I use the python3
and pip3
commands when installing software like Django 3.0, which works better with Python 3. And I keep their alias's pointed towards whatever Python 3 version I want like so alias python3=python3.8
.
Keep In Mind
When you are going to use your package in the future you will want to use the pip
or pip3
command depending on which one you used to initially install the package. So for example if I wanted to change my change my Django package version I would use the pip3
command and not pip
like so, pip3 install Django==3.0.11
.
Notice
When running checking the packages version for python: $ python -m django --version
and python3: $ python3 -m django --version
, two different versions of django will show because I installed django v3.0.11 with pip3
and django v1.11.29 with pip
.
Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.
Derived from book.cls
\def\@endpart{\vfil\newpage
\if@twoside
\null
\thispagestyle{empty}%
\newpage
\fi
\if@tempswa
\twocolumn
\fi}
It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.
\makeatletter
\renewcommand\@endpart{\vfil
\if@twoside
\null
\thispagestyle{empty}%
\newpage
\fi
\if@tempswa
\twocolumn
\fi}
\makeatother
Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it. Lambdas have been made for functional style of programming and this means: No side effects. What you want to do is considered bad style. It is also dangerous in case of parallel streams.
You should either find a solution without side effects or use a traditional for loop.
My own solution to solve this kind of Enum JPA mapping is the following.
Step 1 - Write the following interface that we will use for all enums that we want to map to a db column:
public interface IDbValue<T extends java.io.Serializable> {
T getDbVal();
}
Step 2 - Implement a custom generic JPA converter as follows:
import javax.persistence.AttributeConverter;
public abstract class EnumDbValueConverter<T extends java.io.Serializable, E extends Enum<E> & IDbValue<T>>
implements AttributeConverter<E, T> {
private final Class<E> clazz;
public EnumDbValueConverter(Class<E> clazz){
this.clazz = clazz;
}
@Override
public T convertToDatabaseColumn(E attribute) {
if (attribute == null) {
return null;
}
return attribute.getDbVal();
}
@Override
public E convertToEntityAttribute(T dbData) {
if (dbData == null) {
return null;
}
for (E e : clazz.getEnumConstants()) {
if (dbData.equals(e.getDbVal())) {
return e;
}
}
// handle error as you prefer, for example, using slf4j:
// log.error("Unable to convert {} to enum {}.", dbData, clazz.getCanonicalName());
return null;
}
}
This class will convert the enum value E
to a database field of type T
(e.g. String
) by using the getDbVal()
on enum E
, and vice versa.
Step 3 - Let the original enum implement the interface we defined in step 1:
public enum Right implements IDbValue<Integer> {
READ(100), WRITE(200), EDITOR (300);
private final Integer dbVal;
private Right(Integer dbVal) {
this.dbVal = dbVal;
}
@Override
public Integer getDbVal() {
return dbVal;
}
}
Step 4 - Extend the converter of step 2 for the Right
enum of step 3:
public class RightConverter extends EnumDbValueConverter<Integer, Right> {
public RightConverter() {
super(Right.class);
}
}
Step 5 - The final step is to annotate the field in the entity as follows:
@Column(name = "RIGHT")
@Convert(converter = RightConverter.class)
private Right right;
IMHO this is the cleanest and most elegant solution if you have many enums to map and you want to use a particular field of the enum itself as mapping value.
For all others enums in your project that need similar mapping logic, you only have to repeat steps 3 to 5, that is:
IDbValue
on your enum;EnumDbValueConverter
with only 3 lines of code (you may also do this within your entity to avoid creating a separated class);@Convert
from javax.persistence
package.Hope this helps.
As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:
<?php echo strtotime('+1 day'); ?>
Above code will add 1 day or 24 hours to your current timestamp.
in place of +1 day
you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.
examples from the manual are as below:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
Rules:
You're almost there. As you can see, the onItemSelected
will give you a position
parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position)
.
Example:
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
This will put a message on screen, with the selected item printed by its toString() method.
You can do:
foo.instance_of?(String)
And the more general:
foo.kind_of?(String)
You can also left pad with zeros. For example if you want number
to have 9 characters length, left padded with zeros use:
print('{:09.3f}'.format(number))
Thus, if number = 4.656
, the output is: 00004.656
For your example the output will look like this:
numbers = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers:
print('{:010.4f}'.format(x))
prints:
00023.2300
00000.1233
00001.0000
00004.2230
09887.2000
One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...
Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.
Wxruby is a great framework, simple and clean. Try it or use glade with ruby (the simpliest option)
Here is a quick console program to make it clear to those who follow. The TaskToDo
method is your long running method that you want to make async. Making it run async is done by the TestAsync
method. The test loops method just runs through the TaskToDo
tasks and runs them async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestingAsync
{
class Program
{
static void Main(string[] args)
{
TestLoops();
Console.Read();
}
private static async void TestLoops()
{
for (int i = 0; i < 100; i++)
{
await TestAsync(i);
}
}
private static Task TestAsync(int i)
{
return Task.Run(() => TaskToDo(i));
}
private async static void TaskToDo(int i)
{
await Task.Delay(10);
Console.WriteLine(i);
}
}
}
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
$(function(){
$(".myclass").live("click", function() {
// do something
});
});
My non pythonic approach would be using & suffix. That is:
python flashpolicyd.py &
To stop the script
killall flashpolicyd.py
also piping & suffix with disown would put the process under superparent (upper):
python flashpolicyd.pi & disown
You can do it in this way with Swift 3.0:
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.
<?php
$args=[
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
];
echo generate_token($args);
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}
The following is probably not fully equivalent to a clone in all cases but did the trick for me:
git init .
git remote add -t \* -f origin <repository-url>
git checkout master
In my case, this produces a .git/config
file which is equivalent to the one I get when doing a clone.
I believe {}
was recommended in one of the Javascript vids on here as a good coding convention. new
is necessary for pseudoclassical inheritance. the var obj = {};
way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new
is when you are using constructors functions. For example:
var Mammal = function (name) {
this.name = name;
};
Mammal.prototype.get_name = function () {
return this.name;
}
Mammal.prototype.says = function() {
return this.saying || '';
}
Then it is used like so:
var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();
Another advantage to using {}
as oppose to new Object
is you can use it to do JSON-style object literals.
The border css property will increase all elements "outer" size, excepts tds in tables. You can get a visual idea of how this works in Firebug (discontinued), under the html->layout tab.
Just as an example, a div with a width and height of 10px and a border of 1px, will have an outer width and height of 12px.
For your case, to make it appear like the border is on the "inside" of the div, in your selected CSS class, you can reduce the width and height of the element by double your border size, or you can do the same for the elements padding.
Eg:
div.navitem
{
width: 15px;
height: 15px;
/* padding: 5px; */
}
div.navitem .selected
{
border: 1px solid;
width: 13px;
height: 13px;
/* padding: 4px */
}
Using ignore Duplicates
on the unique index as suggested by IanC here was my solution for a similar issue, creating the index with the Option WITH IGNORE_DUP_KEY
In backward compatible syntax
, WITH IGNORE_DUP_KEY is equivalent to WITH IGNORE_DUP_KEY = ON.
Ref.: index_option
.getDay returns day of week. You need .getDate instead. .getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.
debug_backtrace()[1]['function'];
You can use it like this:
echo 'The calling function: ' . debug_backtrace()[1]['function'];
Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.
The answer from niaher stating that to use the fluent API you need a custom extension may have been correct at the time of writing. You can now (EF core 2.1) use the fluent API as follows:
modelBuilder.Entity<ClassName>()
.HasIndex(a => new { a.Column1, a.Column2}).IsUnique();
The distinction between "self"
and "cls"
is defined in PEP 8
. As Adrien said, this is not a mandatory. It's a coding style. PEP 8
says:
Function and method arguments:
Always use
self
for the first argument to instance methods.Always use
cls
for the first argument to class methods.
Just assuming you want to get the i-th least significant digit from an integer number x, you can try:
(abs(x)%(10**i))/(10**(i-1))
I hope it helps.
See the crypto.createHash()
function and the associated hash.update()
and hash.digest()
functions:
var crypto = require('crypto')
var shasum = crypto.createHash('sha1')
shasum.update('foo')
shasum.digest('hex') // => "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
SELECT * FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Update : for better performance and faster query its good to add e1
before *
SELECT e1.* FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
In one line and probably faster then arr.indexOf(Math.max.apply(Math, arr))
:
var a = [0, 21, 22, 7];_x000D_
var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);_x000D_
_x000D_
document.write("indexOfMaxValue = " + indexOfMaxValue); // prints "indexOfMaxValue = 2"
_x000D_
Where:
iMax
- the best index so far (the index of the max element so far, on the first iteration iMax = 0
because the second argument to reduce()
is 0
, we can't omit the second argument to reduce()
in our case)x
- the currently tested element from the arrayi
- the currently tested indexarr
- our array ([0, 21, 22, 7]
)About the reduce()
method (from "JavaScript: The Definitive Guide" by David Flanagan):
reduce() takes two arguments. The first is the function that performs the reduction operation. The task of this reduction function is to somehow combine or reduce two values into a single value, and to return that reduced value.
Functions used with reduce() are different than the functions used with forEach() and map(). The familiar value, index, and array values are passed as the second, third, and fourth arguments. The first argument is the accumulated result of the reduction so far. On the first call to the function, this first argument is the initial value you passed as the second argument to reduce(). On subsequent calls, it is the value returned by the previous invocation of the function.
When you invoke reduce() with no initial value, it uses the first element of the array as the initial value. This means that the first call to the reduction function will have the first and second array elements as its first and second arguments.
You can try following sample http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
If you want they to be paragraph, then use it.
<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>
Both <label>
and <input>
are paragraph and flow content so you can insert as paragraph elements and as block elements.
HTML 5 invites you give add a lot of semantic value to your code. What's more, there are natives solution to embed multimedia content.
The rest is important, but it's more technical sugar that will save you from doing the same stuff with a client programming language.
Try yum install php-bcmath
.
If you still can't find anything, try yum search bcmath
to find the package name
Singleton is better approach from testing perspective. Unlike static classes , singleton could implement interfaces and you can use mock instance and inject them.
In the example below I will illustrate this. Suppose you have a method isGoodPrice() which uses a method getPrice() and you implement getPrice() as a method in a singleton.
singleton that’s provide getPrice functionality:
public class SupportedVersionSingelton {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
@Override
public int getPrice() {
// calculate price logic here
return 0;
}
}
Use of getPrice:
public class Advisor {
public boolean isGoodDeal(){
boolean isGoodDeal = false;
ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
int price = supportedVersion.getPrice();
// logic to determine if price is a good deal.
if(price < 5){
isGoodDeal = true;
}
return isGoodDeal;
}
}
In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it.
public interface ICalculator {
int getPrice();
}
Final Singleton implementation:
public class SupportedVersionSingelton implements ICalculator {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
@Override
public int getPrice() {
return 0;
}
// for testing purpose
public static void setInstance(ICalculator mockObject){
if(instance != null ){
instance = mockObject;
}
test class:
public class TestCalculation {
class SupportedVersionDouble implements ICalculator{
@Override
public int getPrice() {
return 1;
}
}
@Before
public void setUp() throws Exception {
ICalculator supportedVersionDouble = new SupportedVersionDouble();
SupportedVersionSingelton.setInstance(supportedVersionDouble);
}
@Test
public void test() {
Advisor advidor = new Advisor();
boolean isGoodDeal = advidor.isGoodDeal();
Assert.assertEquals(isGoodDeal, true);
}
}
In case we take the alternative of using static method for implementing getPrice() , it was difficult to the mock getPrice(). You could mock static with power mock, yet not all product could use it.
You can change color programmatically by using this code :
ProgressBar v = (ProgressBar) findViewById(R.id.progress);
v.getIndeterminateDrawable().setColorFilter(0xFFcc0000,
android.graphics.PorterDuff.Mode.MULTIPLY);
If you want to change ProgressDialog's progressbar color, u can use this :
mDilog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
ProgressBar v = (ProgressBar)mDilog.findViewById(android.R.id.progress);
v.getIndeterminateDrawable().setColorFilter(0xFFcc0000,
android.graphics.PorterDuff.Mode.MULTIPLY);
}
});
I got this when I forgot to unprotect workbook or sheet.
You may also have a look on Runtyper - a tool that performs type checking of operands in ===
(and other operations).
For your example, if you have strict comparison x === y
and x = 123, y = "123"
, it will automatically check typeof x, typeof y
and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
i == 'InvKey' && i == 'PostDate'
will never be true, since i
can never equal two different things at once.
You're probably trying to write
if (i !== 'InvKey' && i !== 'PostDate'))
It means that the query you wrote returns more than one element(result) while your code expects a single result.
df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <- letters[1:10]
df[c('a','b'),]
Just to add a different approach - you can simply cast your ref, something like:
let myInputElement: Element = this.refs["myInput"] as Element
resized = Bitmap.createScaledBitmap(yourImageBitmap,(int)(yourImageBitmap.getWidth()*0.9), (int)(yourBitmap.getHeight()*0.9), true);
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
DECLARE @id INT
SET @id = 0
UPDATE cartemp
SET @id = CarmasterID = @id + 1
GO
It may not sound a good idea but i used java and used simple TCP/IP socket programming to connect to a telnet server and exchange communication. ANd it works perfectly if you know the protocol implemented. For SSH etc, it might be tough unless you know how to do the handshake etc, but simple telnet works like a treat.
Another way i tried, was using external process in java System.exec() etc, and then let the windows built in telnet do the job for you and you just send and receive data to the local system process.
Container widths will drop down to 940 pixels for viewports less than 992 pixels. If you really don’t want containers larger than 940 pixels wide, then go to the Bootstrap customize page, and set @container-lg-desktop
to either @container-desktop
or hard-coded 940px
.
Textareas shouldn't wrap by default, but you can set wrap="soft" to explicitly disable wrap:
<textarea name="nowrap" cols="30" rows="3" wrap="soft"></textarea>
EDIT: The "wrap" attribute is not officially supported. I got it from the german SELFHTML page (an english source is here) that says IE 4.0 and Netscape 2.0 support it. I also tested it in FF 3.0.7 where it works as supposed. Things have changed here, SELFHTML is now a wiki and the english source link is dead.
EDIT2: If you want to be sure every browser supports it, you can use CSS to change wrap behaviour:
Using Cascading Style Sheets (CSS), you can achieve the same effect with
white-space: nowrap; overflow: auto;
. Thus, the wrap attribute can be regarded as outdated.
From here (seems to be an excellent page with information about textarea).
EDIT3: I'm not sure when it changed (according to the comments, must've been around 2014), but wrap
is now an official HTML5 attribute, see w3schools. Changed the answer to match this.
Using parameter --force:
npm i -f
sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;
connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;
truncate table tmp;
exit;
EOF
You should install Android SDK Build Tools 23.0.1 via Android SDK. Don't forget to check Show Packages Details
.
There is a Superuser Roles: root, which is a Built-In Roles, may meet your need.
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
Under the connection properties, uncheck "Enable background refresh". This will make the connection refresh when told to, not in the background as other processes happen.
With background refresh disabled, your VBA procedure will wait for your external data to refresh before moving to the next line of code.
Then you just modify the following code:
ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
Sheets("SHEET_NAME").PivotTables("PIVOT_TABLE_NAME").PivotCache.Refresh
You can also turn off background refresh in VBA:
ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection.BackgroundQuery = False
I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.
index.html (or .php)
/resources
/css
/fonts
/images
/js
/controllers
/directives
/filters
/services
/partials (views)
I find that good for single apps. I haven't really had a project yet where I'd need multiple.
I have struggled with this when trying to remotely connect to a new PostgreSQL installation on my Raspberry Pi. Here's the full breakdown of what I did to resolve this issue:
First, open the PostgreSQL configuration file and make sure that the service is going to listen outside of localhost.
sudo [editor] /etc/postgresql/[version]/main/postgresql.conf
I used nano
, but you can use the editor of your choice, and while I have version 9.1
installed, that directory will be for whichever version you have installed.
Search down to the section titled 'Connections and Authentication'. The first setting should be 'listen_addresses'
, and might look like this:
#listen_addresses = 'localhost' # what IP address(es) to listen on;
The comments to the right give good instructions on how to change this field, and using the suggested '*'
for all will work well.
Please note that this field is commented out with #. Per the comments, it will default to 'localhost', so just changing the value to '*'
isn't enough, you also need to uncomment the setting by removing the leading #
.
It should now look like this:
listen_addresses = '*' # what IP address(es) to listen on;
You can also check the next setting, 'port', to make sure that you're connecting correctly. 5432 is the default, and is the port that psql will try to connect to if you don't specify one.
Save and close the file, then open the Client Authentication config file, which is in the same directory:
sudo [editor] /etc/postgresql/[version]/main/pg_hba.conf
I recommend reading the file if you want to restrict access, but for basic open connections you'll jump to the bottom of the file and add a line like this:
host all all all md5
You can press tab instead of space to line the fields up with the existing columns if you like.
Personally, I instead added a row that looked like this:
host [database_name] pi 192.168.1.0/24 md5
This restricts the connection to just the one user and just the one database on the local area network subnet.
Once you've saved changes to the file you will need to restart the service to implement the changes.
sudo service postgresql restart
Now you can check to make sure that the service is openly listening on the correct port by using the following command:
sudo netstat -ltpn
If you don't run it as elevated (using sudo
) it doesn't tell you the names of the processes listening on those ports.
One of the processes should be Postgres, and the Local Address should be open (0.0.0.0) and not restricted to local traffic only (127.0.0.1). If it isn't open, then you'll need to double check your config files and restart the service. You can again confirm that the service is listening on the correct port (default is 5432
, but your configuration could be different).
Finally you'll be able to successfully connect from a remote computer using the command:
psql -h [server ip address] -p [port number, optional if 5432] -U [postgres user name] [database name]
If you only want to look at the memory usage of an object, (answer to other question)
There is a module called Pympler which contains the
asizeof
module.Use as follows:
from pympler import asizeof asizeof.asizeof(my_object)
Unlike
sys.getsizeof
, it works for your self-created objects.>>> asizeof.asizeof(tuple('bcd')) 200 >>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'}) 400 >>> asizeof.asizeof({}) 280 >>> asizeof.asizeof({'foo':'bar'}) 360 >>> asizeof.asizeof('foo') 40 >>> asizeof.asizeof(Bar()) 352 >>> asizeof.asizeof(Bar().__dict__) 280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:
asizeof(*objs, **opts)
Return the combined size in bytes of all objects passed as positional arguments.
The limit is not 2g or 3gb its 4gb for 32bit.
The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.
Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.
4Gig not 3 not 2 got it?
sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'
dissect the URL code and unicode error. this symbol came to me as well on google translate in the armenian text and sometimes the broken burmese.
<div data-ng-init="featureClass=false"
data-ng-click="featureClass=!featureClass"
data-ng-class="{'active': featureClass}">
Click me to toggle my class!
</div>
Analogous to jQuery's toggleClass
method, this is a way to toggle the active
class on/off when the element is clicked.
If you don't feel like importing anything, you can try:
raise SystemExit, 0
Brief syntax lesson
Cells(Row, Column)
identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)
.Cells(Row, Column)
identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column)
is within the active worksheet. So wsh = ActiveWorkbook
wsh.Range
is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column)
identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value
is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value
is good.
Cells(Row,Column) like "*Miami*"
will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.
Cells(Row,Column).Value = "Miami"
will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami"
when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, "South Miami" and "Miami, North".
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, "Miami" and "Florida".
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don't care about case.
This will help
1- First Define This Constants
public static final String FACEBOOK_PACKAGE_NAME = "com.facebook.katana";
public static final String TWITTER_PACKAGE_NAME = "com.twitter.android";
public static final String INSTAGRAM_PACKAGE_NAME = "com.instagram.android";
public static final String PINTEREST_PACKAGE_NAME = "com.pinterest";
public static final String WHATS_PACKAGE_NAME = "com.whatsapp";
2- Second Use This method
public static void shareAppWithSocial(Context context, String application, String title,
String description) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setPackage(application);
intent.putExtra(android.content.Intent.EXTRA_TITLE, title);
intent.putExtra(Intent.EXTRA_TEXT, description);
intent.setType("text/plain");
try {
// Start the specific social application
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
// The application does not exist
Toast.makeText(context, "app have not been installed.", Toast.LENGTH_SHORT).show();
}
}
Try this,
var arg = new { i = 123, j = 456 };
var task = new TaskFactory().StartNew(new Func<dynamic, int>((argument) =>
{
dynamic x = argument.i * argument.j;
return x;
}), arg, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
task.Wait();
var result = task.Result;
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.
Maybe someone will be interested in my solution:
class Version private constructor(private val versionString: String) : Comparable<Version> {
private val major: Int by lazy { versionString.split(".")[0].toInt() }
private val minor: Int by lazy { versionString.split(".")[1].toInt() }
private val patch: Int by lazy {
val splitArray = versionString.split(".")
if (splitArray.size == 3)
splitArray[2].toInt()
else
0
}
override fun compareTo(other: Version): Int {
return when {
major > other.major -> 1
major < other.major -> -1
minor > other.minor -> 1
minor < other.minor -> -1
patch > other.patch -> 1
patch < other.patch -> -1
else -> 0
}
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Version) return false
return compareTo(other) == 0
}
override fun hashCode(): Int {
return major * minor * patch
}
companion object {
private fun doesContainsVersion(string: String): Boolean {
val versionArray = string.split(".")
return versionArray.size in 2..3
&& versionArray[0].toIntOrNull() != null
&& versionArray[1].toIntOrNull() != null
&& (versionArray.size == 2 || versionArray[2].toIntOrNull() != null)
}
fun from(string: String): Version? {
return if (doesContainsVersion(string)) {
Version(string)
} else {
null
}
}
}
}
Usage:
val version1 = Version.from("3.2")
val version2 = Version.from("3.2.1")
version1 <= version2
With OpenSSL you can convert pfx to Apache compatible format with next commands:
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
First command extracts public key to domain.cer
.
Second command extracts private key to domain.key
.
Update your Apache configuration file with:
<VirtualHost 192.168.0.1:443>
...
SSLEngine on
SSLCertificateFile /path/to/domain.cer
SSLCertificateKeyFile /path/to/domain.key
...
</VirtualHost>
You can have all the different styles to datetime conversion
:
https://www.w3schools.com/sql/func_sqlserver_convert.asp
This has range of values :-
CONVERT(data_type(length),expression,style)
For style values,
Choose anyone you need like I needed 106.
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
Try This :
document.getElementById(<element_ID>).readOnly=true;
I had the same issue and i fixed it with the following:
The problem is that when you specify a file that only your app has access to (e.g. by calling getFileStreamPath("file");
)
That is why i just made sure that the given file really exists and that EVERYONE has write access to it.
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File outFile = getFileStreamPath(Config.IMAGE_FILENAME);
outFile.createNewFile();
outFile.setWritable(true, false);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(outFile));
startActivityForResult(intent, 2);
This way, the camera app has write access to the given Uri and the OK button works fine :)
Added some more logic to solution provided by @Andrew Burgess. Here is the full solution:
Created a action filter to get errors for ajax request:
public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode =
(int)HttpStatusCode.BadRequest;
}
}
}
Added the filter to my controller method as:
[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}
Added a common script for jquery validation:
function onAjaxFormError(data) {
var form = this;
var errorResponse = data.responseJSON;
$.each(errorResponse, function (index, value) {
// Element highlight
var element = $(form).find('#' + value.key);
element = element[0];
highLightError(element, 'input-validation-error');
// Error message
var validationMessageElement = $('span[data-valmsg-for="' + value.key + '"]');
validationMessageElement.removeClass('field-validation-valid');
validationMessageElement.addClass('field-validation-error');
validationMessageElement.text(value.errors[0]);
});
}
$.validator.setDefaults({
ignore: [],
highlight: highLightError,
unhighlight: unhighlightError
});
var highLightError = function(element, errorClass) {
element = $(element);
element.addClass(errorClass);
}
var unhighLightError = function(element, errorClass) {
element = $(element);
element.removeClass(errorClass);
}
Finally added the error javascript method to my Ajax Begin form:
@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}
You can check if it's not set (or empty) in a number of ways.
if (!$var){ }
Or:
if ($var === null){ } // This checks if the variable, by type, IS null.
Or:
if (empty($var)){ }
You can check if it's declared with:
if (!isset($var)){ }
Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.
If you are using postgres use text wherever you can, unless you have a size constraint since there is no performance penalty for text vs varchar
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead
UPDATE 2:
See this answer . - 2019-11-05
You can also now have it auto-open Developer Tools in Pop-ups if they were open where you opened them from. For example, if you do not have Dev Tools open and you get a popup, it won't open with Dev Tools. But if you Have Dev Tools Open and then you click something, the popup will have Dev-Tools Automatically opened.
UPDATE:
Time has changed, you can now use --auto-open-devtools-for-tabs as in this answer – Wouter Huysentruit May 18 at 11:08
OP:
I played around with the startup string for Chrome on execute, but couldn't get it to persist to new tabs.
I also thought about a defined PATH method that you could invoke from prompt. This is possible with the SendKeys command, but again, only on a new instance. And DevTools doesn't persist to new tabs.
Browsing the Google Product Forums, there doesn't seem to be a built-in way to do this in Chrome. You'll have to use a keystroke solution or F12 as mentioned above.
I recommended it as a feature. I know I'm not the first either.
"<pre>"
is an HTML tag. If you insert this line of code in your program
echo "<pre>";
then you will enable the viewing of multiple spaces and line endings. Without this, all \n
, \r
and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br>
you would be able to break the line and go to the next one.
For example,
the code below would be displayed on multiple lines, due to \n
line ending specifier.
<?php
echo "<pre>";
printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
printf("Goodbye");
?>
However the following code, would be displayed in one line only (line endings are disregarded).
<?php
printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
printf("Goodbye");
?>
You can use os.sep:
>>> import os
>>> os.sep
'/'
TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)
The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.
"name":"value"
.Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.
What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name")
, and then create another JProperty of your desire and then add it after this using AddAfterSelf
method. You are done then.
For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm
This is the code I modified.
public class Program
{
public static void Main()
{
try
{
string jsonText = @"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
Console.WriteLine(foodJsonObj.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
}
In VSCode, Go to File => Preferences => Settings (or Control+comma) and it will open the User Settings file. Search "javascript.implicitProjectConfig.experimentalDecorators": true and then check the checkbox for experimentalDecorators to the file and it should fix it. It did for me.
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
Variant without JavaScript. Only CSS.
CSS:
.toggle_block {
border: 1px solid #ccc;
text-align: left;
background: #fff;
overflow: hidden;
}
.toggle_block .toggle_flag {
display: block;
width: 1px;
height: 1px;
position: absolute;
z-index: 0;
left: -1000px;
}
.toggle_block .toggle_key {
font-size: 16px;
padding: 10px;
cursor: pointer;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
}
.toggle_block .content {
padding: 0 10px;
overflow: hidden;
max-height: 0;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
}
.toggle_block .content .toggle_close {
cursor: pointer;
font-size: 12px;
}
.toggle_block .toggle_flag:checked ~ .toggle_key {
background: #dfd;
}
.toggle_block .toggle_flag:checked ~ .content {
max-height: 1000px;
padding: 10px 10px;
}
HTML:
<div class="toggle_block">
<input type="checkbox" id="toggle_1" class="toggle_flag">
<label for="toggle_1" class="toggle_key">clicker</label>
<div class="content">
Text 1<br>
Text 2<br>
<label for="toggle_1" class="toggle_close">close</label>
</div>
</div>
For next block only change ID and FOR attributes in html.
Having two divs,
<div id="div1">The two divs are</div>
<div id="div2">next to each other.</div>
you could also use the display
property:
#div1 {
display: inline-block;
}
#div2 {
display: inline-block;
}
jsFiddle example here.
If div1
exceeds a certain height, div2
will be placed next to div1
at the bottom. To solve this, use vertical-align:top;
on div2
.
jsFiddle example here.
In your layout XML file :
set android:inputType="textCapSentences"
On your EditText
to have first alphabet of the first word of each sentence as capital
Or android:inputType="textCapWords"
on your EditText to have first alphabet of each word as capital
Try installing these packages.
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-pil python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libssl-dev
sudo easy_install greenlet
sudo easy_install gevent
Here are some good sample applications. Below is one possible way.
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.
Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
if (MainForm.RunningInstance() != null)
{
MessageBox.Show("Duplicate Instance");
//TODO:
//Your application logic for duplicate
//instances would go here.
}
Many other possible ways. See the examples for alternatives.
EDIT 1: Just saw your comment that you have got a console application. That is discussed in the second sample.
From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.
Take note that resize
initialize the newly allocated vector where reserve
just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'
You can refer to the documentation regarding the difference of resize and reserve
We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.
import pandas as pd
import seaborn as sns
import numpy as np
numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.
for i in data[numeric_features].columns:
plt.figure(figsize=(12,5))
plt.title(i)
sns.boxplot(data=data[i])
You need to create the variable to assign the new value to, like this:
String str = string.replaceAll("abcd","dddd");
Process p = Runtime.getRuntime().exec(
new String[]{"cmd", "/C", "orgreg.bat"},
null,
new File("D://TEST//home//libs//"));
tested with jdk1.5 and jdk1.6
This was working fine for me, hope it helps others too. to get this i have struggled more days. :(
Maybe you don't need it anymore but if someone needs this using node: https://www.npmjs.com/package/btoa
// check for the app if it exist in the phone it will lunch it otherwise, it will search for the app in google play app in the phone and to avoid any crash, if no google play app installed in the phone, it will search for the app in the google play store using the browser :
public void onLunchAnotherApp() {
final String appPackageName = getApplicationContext().getPackageName();
Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
onGoToAnotherInAppStore(intent, appPackageName);
}
}
public void onGoToAnotherInAppStore(Intent intent, String appPackageName) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + appPackageName));
startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
startActivity(intent);
}
}
perhaps psql isn't in the PATH
of the postgres user. Use the locate command to find where psql is and ensure that it's path is in the PATH
for the postgres user.
If you run binary on linux machine you could use shell script.
overwrite into a file
./binaryapp > binaryapp.log
append into a file
./binaryapp >> binaryapp.log
overwrite stderr into a file
./binaryapp &> binaryapp.error.log
append stderr into a file
./binaryapp &>> binalyapp.error.log
it can be more dynamic using shell script file.
Communication between controllers is done though $emit
+ $on
/ $broadcast
+ $on
methods.
So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
While $rootScope.$emit
is called, you can send any data as second parameter.
Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.
While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!
Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)
Use Azure Data Studio if you: [..] Are mostly editing or executing queries.
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects
. So, you create a blank array. Create an object for each input
by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}]
There's no built-in command for that because it's illegal. You can't modify the size of an array once declared.
What you're looking for is either std::vector
to simulate a dynamic array, or better yet a std::string
.
std::string first ("The dog jumps ");
std::string second ("over the log");
std::cout << first + second << std::endl;
For Python2 WIN10 Users:
1.Uninstall python thoroughly ,include all folders.
2.Fetch and install the lastest python-2.7.msi (ver 2.7.15)
3.After step 2,you may find pip had been installed too.
4.Now ,if your system'env haven't been changed,you can use pip to install packages now.The "tlsv1 alert protocol version" will not appear.
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.
write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
cmd /c Pause | Out-Null
Read-Host -Prompt "Press Enter to continue"
This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.
Function Pause ($Message = "Press any key to continue . . . ") {
if ((Test-Path variable:psISE) -and $psISE) {
$Shell = New-Object -ComObject "WScript.Shell"
$Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
}
else {
Write-Host -NoNewline $Message
[void][System.Console]::ReadKey($true)
Write-Host
}
}
From W3 web site Common HTML entities used for typography
For the sake of portability, Unicode entity references should be reserved for use in documents certain to be written in the UTF-8 or UTF-16 character sets. In all other cases, the alphanumeric references should be used.
Translation: If you are looking for widest support, go with —
The problem with your query is that in CASE
expressions, the THEN
and ELSE
parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.
You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:
WHERE
DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0
OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
)
IE doesn't allow pressing the ENTER key for form submission if the submit button is not visible, and the form has more than one field. Give it what it wants by providing a 1x1 pixel transparent image as a submit button. Of course it will take up a pixel of the layout, but look what you have to do to hide it.
<input type="image" src="img/1x1trans.gif"/>
There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype()
does) definitely check out the link.
[update 2015-09-28] Now Google lets you add custom domains (including naked domains) and setup SSL without the need of Google Apps. For details refer to here: https://cloud.google.com/appengine/docs/using-custom-domains-and-ssl?hl=en
I just discovered today (as of 2014-04-11) a new custom domain settings page is available from Google Developers Console:
1. Go to https://console.developers.google.com/project
2. Click on your project
3. On the left click "App Engine"
4. Click "Settings"
There you go! You can configure custom domain without the need of Google App account!
Edited my eclipse.ini file to update the newly updated JDK. Previously I had jdk1.7.0_09 and updated now to jdk1.7.0_80 and eclipse threw this error.
A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations: C:/Program Files/Java/jdk1.7.0_09/bin/javaw
After updating eclipse.ini from,
-vm
C:/Program Files/Java/jdk1.7.0_09/bin/javaw
to
-vm
C:/Program Files/Java/jdk1.7.0_80/bin/javaw
Eclipse works fine.
It's not unique to WP7--it's present on all .Net objects. It sort of does what you describe, but I would not recommend it as a unique identifier in your apps, as it is not guaranteed to be unique.
If values aren't unique AND may be a hash (one dimension):
for k, v in myDict.items():
if len(v) > 1:
for item in v:
invDict[item] = invDict.get(item, [])
invDict[item].append(k)
else:
invDict[v] = invDict.get(v, [])
invDict[v].append(k)
And with a recursion if you need to dig deeper then just one dimension:
def digList(lst):
temp = []
for item in lst:
if type(item) is list:
temp.append(digList(item))
else:
temp.append(item)
return set(temp)
for k, v in myDict.items():
if type(v) is list:
items = digList(v)
for item in items:
invDict[item] = invDict.get(item, [])
invDict[item].append(k)
else:
invDict[v] = invDict.get(v, [])
invDict[v].append(k)
If you specify @GET("foobar?a=5")
, then any @Query("b")
must be appended using &
, producing something like foobar?a=5&b=7
.
If you specify @GET("foobar")
, then the first @Query
must be appended using ?
, producing something like foobar?b=7
.
That's how Retrofit works.
When you specify @GET("foobar?")
, Retrofit thinks you already gave some query parameter, and appends more query parameters using &
.
Remove the ?
, and you will get the desired result.
Accepted answer is right but lacks solution. To avoid this error, you can add setHttpRequestRetryHandler (or setRetryHandler for apache components 4.4) for your HTTP client like in this answer.
Suppose s = "ZWzaAd"
To sort above string the simple solution will be below one.
print ''.join(sorted(s))
If you don't want to change keymaps you can quickly enter and exit Presentation Mode via the following shortcut sequence (use Ctrl in macOS, too):
Adding more information to @Jesco
post.
Element.scrollIntoViewIfNeeded()
non-standard WebKit method
for Chrome, Opera, Safari browsers.
Element.scrollIntoView()
method scrolls the element on which it's called into the visible area of the browser window.Try the below code in mozilla.org
scrollIntoView()
link. Post to identify Browser
var xpath = '//*[@id="Notes"]';
ScrollToElement(xpath);
function ScrollToElement(xpath) {
var ele = $x(xpath)[0];
console.log( ele );
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
if (isChrome) { // Chrome
ele.scrollIntoViewIfNeeded();
} else {
var inlineCenter = { behavior: 'smooth', block: 'center', inline: 'start' };
ele.scrollIntoView(inlineCenter);
}
}
I would try:
self.wordList = list(wordList)
to force it to make a copy instead of referencing the same object.
As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.
You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the
/*
//@ sourceMappingURL=angular.min.js.map
*/
at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.
Swift: You need to add a subview with clip to bounds
var DateView = UIView(frame: CGRectMake(0, 0, view.frame.width, 100))
DateView.layer.borderWidth=1
DateView.clipsToBounds = true
var myDatepicker = UIDatePicker(frame:CGRectMake(0,-20,view.frame.width,162));
DateView.addSubview(myDatepicker);
self.view.addSubview(DateView)
This should add a clipped 100 height date picker in the top of the view controller.
Finally got it: The way Eclipse picks up the JRE is using the system's PATH.
I did not have C:\home\SFTWR\jdk1.6.0_21\bin
in the path at all before and I did have C:\Program Files (x86)\Java\jre6\bin
. I had both JRE_HOME
and JAVA_HOME
set to C:\home\SFTWR\jdk1.6.0_21
but neither of those two mattered. I guess Eclipse did (something to the effect of) where java (or which on UNIX/Linux) to see where Java is in the path and took the JRE to which that java.exe
belonged. In my case, despite all the configuration tweaks I had done (including eclipse.ini
-vm option as suggested above), it remained stuck to what was in the path.
I removed the old JRE bin from the path, put the new one in, and it works for all workspaces.
Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)
String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
File newFile = new File(newFilePath);
try {
FileUtils.moveFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
AppDomain.CurrentDomain.BaseDirectory
There's a ES6 shorthand import, you can reference. More readable and easy to type.
import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';
class ExampleComponent extends Component {
static propTypes = {
annotationRanges: arrayOf(shape({
start: number,
end: number,
})).isRequired,
}
static defaultProps = {
annotationRanges: [],
}
}
Here's a better option:
git remote set-head -a origin
From the documentation:
With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.
This has actually been around quite a while (since v1.6.3); not sure how I missed it!
You can achieve this also by using JavaScripts's native method. Its pretty simple and doesn't require any extra library to import.
<input type="text" name="date" placeholder="yyyy-mm-dd" onkeyup="
var date = this.value;
if (date.match(/^\d{4}$/) !== null) {
this.value = date + '-';
} else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
this.value = date + '-';
}" maxlength="10">
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
I wouldn't use checkboxes, i'd use the code you already have
DEMO http://jsfiddle.net/6W7XD/1/
CSS
body {
display: block;
}
.span3:focus ~ .alert {
display: none;
}
.span2:focus ~ .alert {
display: block;
}
.alert{display:none;}
HTML
<span class="span3">Hide Me</span>
<span class="span2">Show Me</span>
<p class="alert" >Some alarming information here</p>
This way the text is only hidden on click of the hide element
Add this CSS to the paragraph.
width:420px;
min-height:15px;
height:auto!important;
color:#666;
padding: 1%;
font-size: 14px;
font-weight: normal;
word-wrap: break-word;
text-align: left;
<router-outlet [node]="..."></router-outlet>
is just invalid. The component added by the router is added as sibling to <router-outlet>
and does not replace it.
See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
@Injectable()
export class NodeService {
private node:Subject<Node> = new BehaviorSubject<Node>([]);
get node$(){
return this.node.asObservable().filter(node => !!node);
}
addNode(data:Node) {
this.node.next(data);
}
}
@Component({
selector : 'node-display',
providers: [NodeService],
template : `
<router-outlet></router-outlet>
`
})
export class NodeDisplayComponent implements OnInit {
constructor(private nodeService:NodeService) {}
node: Node;
ngOnInit(): void {
this.nodeService.getNode(path)
.subscribe(
node => {
this.nodeService.addNode(node);
},
err => {
console.log(err);
}
);
}
}
export class ChildDisplay implements OnInit{
constructor(nodeService:NodeService) {
nodeService.node$.subscribe(n => this.node = n);
}
}
It could be that the corresponding Gradle version was not downloaded properly.
You could delete the broken file at
rm -rf .gradle/wrapper/dists/
and restart studio.
or try
File -> Settings -> Gradle -> Check Offline Work
and download the file from the official site and extract to the destination location
.gradle/wrapper/dists/