On Ubuntu Server 16, I have the same problem with python27. Try this:
Change
from pip import main
if __name__ == '__main__':
sys.exit(main())
To
from pip._internal import main
if __name__ == '__main__':
sys.exit(main())
The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.
Step 1: Create a custom view class.
public class CustomView extends FrameLayout {
private TextView titleView;
public CustomView(Context context) {
super(context);
init(null, 0, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
@RequiresApi(21)
public CustomView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
public void setTitle(String title) {
titleView.setText(title);
}
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
}
}
Step 2: Define a string attribute in the values/attrs.xml
resource file:
<resources>
<declare-styleable name="CustomView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
Step 3: Apply the @StringHandler
annotation to the setTitle
method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.
@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
titleView.setText(title);
}
Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion
class.
Step 4: Use the generated class in the custom view's init
method:
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
CustomView_SpyglassCompanion
.builder()
.withTarget(this)
.withContext(getContext())
.withAttributeSet(attrs)
.withDefaultStyleAttribute(defStyleAttr)
.withDefaultStyleResource(defStyleRes)
.build()
.callTargetMethodsNow();
}
That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle
will be called with "Hello, World!"
as the argument.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:width="match_parent"
android:height="match_parent">
<com.example.CustomView
android:width="match_parent"
android:height="match_parent"
app:title="Hello, World!"/>
</FrameLayout>
The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.
Have a look at the Github repo for more information and examples.
The slidingExpiration=true value is basically saying that after every request made, the timer is reset and as long as the user makes a request within the timeout value, he will continue to be authenticated.
This is not correct. The authentication cookie timeout will only be reset if half the time of the timeout has passed.
See for example https://support.microsoft.com/de-ch/kb/910439/en-us or https://itworksonmymachine.wordpress.com/2008/07/17/forms-authentication-timeout-vs-session-timeout/
I hope this will work, I tried a lot of methods but this one worked for me in fragments
. just put this line in onCreateview/init.
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.
While you can write
mylist = [1, 2 ,3 ,4]
mylist.pop(0)
It's very inefficient.
If you only want to delete items from your list, you can do this with del
:
del mylist[:n]
Which is also really fast:
In [34]: %%timeit
help=range(10000)
while help:
del help[:1000]
....:
10000 loops, best of 3: 161 µs per loop
If you need to obtain elements from the beginning of the list, you should use collections.deque
by Raymond Hettinger and its popleft()
method.
from collections import deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
A comparison:
In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop
I think your problem is that
int selection = scanner.nextInt();
reads just the number, not the end of line or anything after the number. When you declare
String sentence = scanner.nextLine();
This reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
You could execute an external tool for that task (like copy
in windows environments) but, to keep the code portable, the general approach is to:
File#renameTo
will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
cgi.escape
should be good to escape HTML in the limited sense of escaping the HTML tags and character entities.
But you might have to also consider encoding issues: if the HTML you want to quote has non-ASCII characters in a particular encoding, then you would also have to take care that you represent those sensibly when quoting. Perhaps you could convert them to entities. Otherwise you should ensure that the correct encoding translations are done between the "source" HTML and the page it's embedded in, to avoid corrupting the non-ASCII characters.
If you need this for PHP:
The PHP DOM functions won't work properly unless it is properly formatted XML. No matter how much better their use is for the rest of mankind.
simplehtmldom is good, but I found it a bit buggy, and it is is quite memory heavy [Will crash on large pages.]
I have never used querypath, so can't comment on its usefulness.
Another one to try is my DOMParser which is very light on resources and I've been using happily for a while. Simple to learn & powerful.
For Python and Java, similar links were posted.
For the downvoters - I only wrote my class when the XML parsers proved unable to withstand real use. Religious downvoting just prevents useful answers from being posted - keep things within perspective of the question, please.
Distinct will sort records in ascending order. If you want to sort in desc order use:
SELECT DISTINCT Category
FROM MonitoringJob
ORDER BY Category DESC
If you want to sort records based on CreationDate field then this field must be in the select statement:
SELECT DISTINCT Category, creationDate
FROM MonitoringJob
ORDER BY CreationDate DESC
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
This recent June 2013 post goes into some detail into explaining the transition from relationship databases to objects with associations for some data types.
https://www.facebook.com/notes/facebook-engineering/tao-the-power-of-the-graph/10151525983993920
There's a longer paper available at https://www.usenix.org/conference/atc13/tao-facebook’s-distributed-data-store-social-graph
Maybe you are already using the system proxy setting - in this case unset all git proxies will work:
git config --global --unset http.proxy
git config --global --unset https.proxy
When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).
You can't download the file directly via ajax.
You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe
and set the URL of the source of that iframe
dynamically. This way you can download the file without refreshing the page.
Here is the code
$.ajax({
url : "yourURL.php",
type : "GET",
success : function(data) {
$("#iframeID").attr('src', 'downloadFileURL');
}
});
Just found the answer, it appears that the view where I was placing the RenderPartial code had a dynamic model, and thus, MVC couldn't choose the correct method to use. Casting the model in the RenderPartial call to the correct type fixed the issue.
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
I can see people giving lots of comments on this question. But I think, simple use of LIKE
could be easier to get the data from the table.
SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
Use LIKE
and post data wild character search. Hopefully this will solve your problem.
Running Visual Studio Code as Administrator should do the trick.
If you're on Windows you can:
Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.
Related Changes in CodebaseIf for some weird reason this is not running your commands as an Administrator you can try the runas
command. Microsoft: runas command
runas /user:Administrator myCommand
runas "/user:First Last" "my command"
In your test class, the tested class should be annotated with @InjectMocks
. This tells Mockito which class to inject mocks into:
@InjectMocks
private SomeManager someManager;
From then on, we can specify which specific methods or objects inside the class, in this case, SomeManager
, will be substituted with mocks:
@Mock
private SomeDependency someDependency;
In this example, SomeDependency
inside the SomeManager
class will be mocked.
The hashes are just because your column width is not enough to display the "number".
About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).
Regards
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
I really do not understand some of the answers given here (sorry for that). The top-voted answer for example does not return the Windows architecture, instead it will give you the processor architecture. While running a 32-bits Windows build on a 64-bits CPU you will get the wrong result (it's a query on hardware being used).
The safest option is to query the BuildLabEx value from the registry.
Determine x86 (intel) or x86-64 (amd)
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".x86fre." && set "_ARCH_=x86" || set "_ARCH_=x86-64"
Determine x86 (intel), x86-64 (amd) or arm
set "_ARCH_=unknown"
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".x86fre." && set "_ARCH_=x86"
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".amd64fre." && set "_ARCH_=x86-64"
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".armfre." && set "_ARCH_=arm"
An alternative option (mentioned before)
if defined ProgramFiles(x86) ( set "_ARCH_=x86-64" ) else ( set "_ARCH_=x86" )
The problem with the latter is when you mess up your variables, you are not able to use this method. Checking for the folder's existence will cause problems too when there are leftovers from a previous install (or some user purposely created the folder).
So much code here, but I think this is the best answer
function resize() {
var input = $("#picture");
var maxWidth = 300;
var maxHeight = 300;
var width = input.width();
var height = input.height();
var ratioX = (maxWidth / width);
var ratioY = (maxHeight / height);
var ratio = Math.min(ratioX, ratioY);
var newWidth = (width * ratio);
var newHeight = (height * ratio);
input.css("width", newWidth);
input.css("height", newHeight);
};
Summary
Assuming ordering is not important:
std::unordered_map
std::map
. This is because reads on it are O(log n)
.std::map
is good option. std::unordered_map
.Historical Context
In most languages, unordered map (aka hash based dictionaries) are the default map however in C++ you get ordered map as default map. How did that happen? Some people erroneously assume that C++ committee made this decision in their unique wisdom but the truth is unfortunately uglier than that.
It is widely believed that C++ ended up with ordered map as default because there are not too many parameters on how they can be implemented. On the other hand, hash based implementations has tons of things to talk about. So to avoid gridlocks in standardization they just got along with ordered map. Around 2005, many languages already had good implementations of hash based implementation and so it was more easier for the committee to accept new std::unordered_map
. In a perfect world, std::map
would have been unordered and we would have std::ordered_map
as separate type.
Performance
Below two graphs should speak for themselves (source):
Using reflect.deepEqual also works, especially when you have map inside the struct
package main
import "fmt"
import "time"
import "reflect"
type Session struct {
playerId string
beehive string
timestamp time.Time
}
func (s Session) IsEmpty() bool {
return reflect.DeepEqual(s,Session{})
}
func main() {
x := Session{}
if x.IsEmpty() {
fmt.Print("is empty")
}
}
Note many third-party clients have own timezone settings overlapping any Postgres server and\or session settings.
E.g. if you're using 'IntelliJ IDEA 2017.3' (or DataGrips), you should define timezone as:
'DB source properties' -> 'Advanced' tab -> 'VM Options': -Duser.timezone=UTC+06:00
otherwise you will see 'UTC' despite of whatever you have set anywhere else.
Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.
astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')
which results in
[1] "Abcdeacoauu"
You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.
Sample snippet for time-diff:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
TimeSpan.FromTicks(DateTime.Now.Ticks)
In my case, the problem was the optional parameter indicator('?') missing in my template configuration.
For example:
.when('/abc/:id?', {
templateUrl: 'views/abc.html',
controller: 'abcControl'
})
$location.path('/abc');
Without the interrogation character the route obviously would not change suppressing the route parameter.
I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:
// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;
doc = PDDocument.load(filename);
// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
//System.out.println(o.toString() + " " + dict.getString(o));
System.out.println(o.toString());
}
// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);
List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());
You can open the background page's console if you click on the "background.html" link in the extensions list.
To access the background page that corresponds to your extensions open Settings / Extensions
or open a new tab and enter chrome://extensions
. You will see something like this screenshot.
Under your extension click on the link background page
. This opens a new window.
For the context menu sample the window has the title: _generated_background_page.html
.
Use Double.parseDouble(String a)
what you are looking for is not an integer as it is not a whole number.
You can also use echo
to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.
$ myVar=" kokor iiij ook "
$ echo "$myVar"
kokor iiij ook
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
If you are concerned about the file's content being served rather than its output. You can use a double extension like: file.inc.php
. It then serves the same purpose of helpfulness and maintainability.
I normally have 2 php files for each page on my site:
welcome.php
in the root folder, containing all of the HTML markup. welcome.inc.php
in the inc
folder, containing all PHP functions specific to the welcome.php
page.EDIT: Another benefit of using the double extention .inc.php
would be that any IDE can still recognise the file as PHP code.
if your SQL query is this
SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'
then rawQuery will be
String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"}
db.rawQuery(query, selectionArgs);
The problem with your query is that when using a GROUP BY clause (which you essentially do by using distinct) you can only use columns that you group by or aggregate functions. You cannot use the column id because there are potentially different values. In your case there is always only one value because of the HAVING clause, but most RDBMS are not smart enough to recognize that.
This should work however (and doesn't need a join):
UPDATE sales
SET status='ACTIVE'
WHERE id IN (
SELECT MIN(id) FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(id) = 1
)
You could also use MAX or AVG instead of MIN, it is only important to use a function that returns the value of the column if there is only one matching row.
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
The common way is to make the private method protected or package-private and to put the unit test for this method in the same package as the class under test.
Guava has a @VisibleForTesting
annotation, but it's only for documentation purposes.
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
Try + (instancetype)appearance of UITableView:
Objective-C:
[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"
Swift 3.0:
UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"
Note: Change will reflect to all tables used in application.
The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.
Some reasons why this might happen:
If the problem is related to timeout settings, you may be able to resolve it by investigating the following:
The "IN" clause is built into linq via the .Contains() method.
For example, to get all People whose .States's are "NY" or "FL":
using (DataContext dc = new DataContext("connectionstring"))
{
List<string> states = new List<string>(){"NY", "FL"};
List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}
I agree with Brandrew, the problem is most likely caused by some missing dlls that can't be found neither on the system path nor in the folder where the executable is. Try putting the following DLLs nearby the executable:
Alternatively, try loading the executable into Dependency Walker ( http://www.dependencywalker.com/ ), it should point out the missing dlls for you.
XML has a much wider application than f.ex. HTML. It doesn't have an intrinsic, or default "application". So, while you might not really care that web pages are also governed by what's allowed, from the author's side, you'll probably want to precisely define what an XML document may and may not contain.
It's like designing a database.
The thing about XML technologies is that they are textual in nature. With XSD, it means you have a data structure definition framework that can be "plugged in" to text processing tools like PHP. So not only can you manipulate the data itself, but also very easily change and document the structure, and even auto-generate front-ends.
Viewed like this, XSD is the "glue" or "middleware" between data (XML) and data-processing tools.
Use the util namespace, you will be able to register the list as a bean in your application context. You can then reuse the list to inject it in other bean definitions.
If you're iterating over an object instead of an array, you'll need to access the properties using:
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
That, or change your object to an array.
If working with Python =2.6 (including 3.x), you can:
from __future__ import division
import operator, itertools
def getmin(alist):
return min(
(operator.div(*pair), pair)
for pair in itertools.product(alist, repeat=2)
)[1]
getmin([1, 2, 3, 4, 5])
EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:
def getmin(alist):
return min(alist), max(alist)
If String.Compare(string1,string2,True) Then
'perform operation
EndIf
The best and easy solution for solving this issue is pass your data from this function in controller.
$scope.trustSrcurl = function(data)
{
return $sce.trustAsResourceUrl(data);
}
In html page
<iframe class="youtube-player" type="text/html" width="640" height="385" ng-src="{{trustSrcurl(video.src)}}" allowfullscreen frameborder="0"></iframe>
Similar to one of the answers above, I used
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6
AFAIK the best you can do to emulate Split()
is to use FILTERXML
which is available from Excel 2013 onwards (not Excel Online or Mac).
The syntax more or less always is:
=FILTERXML("<t><s>"&SUBSTITUTE(A1,"|","</s><s>")&"</s></t>","//s")
This would return an array to be used in other functions and would even hold up if no delimiter is found. If you want to read more about it, maybe you are interested in this post.
I would say that when you have a language like Lisp with its support for macros, then you can build you own domain-specific abstractions, abstractions which often are much better than the general idiom solutions.
There's no built in type for ConcurrentHashSet
because you can always derive a set from a map. Since there are many types of maps, you use a method to produce a set from a given map (or map class).
Prior to Java 8, you produce a concurrent hash set backed by a concurrent hash map, by using Collections.newSetFromMap(map)
In Java 8 (pointed out by @Matt), you can get a concurrent hash set view via ConcurrentHashMap.newKeySet()
. This is a bit simpler than the old newSetFromMap
which required you to pass in an empty map object. But it is specific to ConcurrentHashMap
.
Anyway, the Java designers could have created a new set interface every time a new map interface was created, but that pattern would be impossible to enforce when third parties create their own maps. It is better to have the static methods that derive new sets; that approach always works, even when you create your own map implementations.
This one more version - this will help in generic
Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer
Sub Create()
Dim strFilePath As String
Dim strFileName As String
'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value
strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value
Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName
End Sub
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
Dim Q As String
Dim sOutputFileNamewithPath As String
Q = Chr$(34)
Dim sXML As String
'sXML = sXML & "<rows>"
' ''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
Dim iCount As Integer
iRow = iDataStartRow
iCount = 1
While Cells(iRow, 1) > ""
'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
For iCOl = 1 To iColCount - 1
If (iStartCol = iCOl) Then
sXML = sXML & "<" & strSubTag & ">"
End If
If (iEndCol = iCOl) Then
sXML = sXML & "</" & strSubTag & ">"
End If
If (iStartCol2 = iCOl) Then
sXML = sXML & "<" & strSubTag2 & ">"
End If
If (iEndCol2 = iCOl) Then
sXML = sXML & "</" & strSubTag2 & ">"
End If
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
sXML = sXML & Trim$(Cells(iRow, iCOl))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
Next
'sXML = sXML & "</row>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
''Write the entire file to sText
Open sOutputFileNamewithPath For Output As #nDestFile
Print #nDestFile, sXML
iRow = iRow + 1
sXML = ""
iCount = iCount + 1
Wend
'sXML = sXML & "</rows>"
Close
End Sub
You can execute any class which has a public final static main
method from a JAR file, even if the jar file has a Main-Class
defined.
Execute Main-Class:
java -jar MyJar.jar // will execute the Main-Class
Execute another class with a public static void main
method:
java -cp MyJar.jar com.mycomp.myproj.AnotherClassWithMainMethod
Note: the first uses -jar
, the second uses -cp
.
The ZingChart library has an AngularJS directive that was built in-house. Features include:
Support from the development team
...
$scope.myJson = {
type : 'line',
series : [
{ values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
]
};
...
<zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
There is a full demo with code examples available.
Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.
If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:
$text = "Hello, {$vars->name},\r\n\r\n"
. "The second line starts two lines below.\r\n"
. ".. Third line... etc";
This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.
You need to roll your own method to eliminate the files you don't want.
This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.
Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).
This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.
#import "Foundation/Foundation.h" #import "RegexKit/RegexKit.h" @interface MTFileMatcher : NSObject { } - (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath; @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // insert code here... MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease]; [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]]; [pool drain]; return 0; } @implementation MTFileMatcher - (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath; { NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex]; NSEnumerator* itr = [filesAtPath objectEnumerator]; NSString* obj; while (obj = [itr nextObject]) { NSLog(obj); } } @end
In 2021 the easiest way is to use asyncio:
import asyncio, time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(4, 'hello'))
task2 = asyncio.create_task(
say_after(3, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
References:
Just to give the reason behind what everyone else is saying.
The binary representation of a float is kind of annoying.
In binary, most programmers know the correlation between 1b=1d, 10b=2d, 100b=4d, 1000b=8d
Well it works the other way too.
.1b=.5d, .01b=.25d, .001b=.125, ...
The problem is that there is no exact way to represent most decimal numbers like .1, .2, .3, etc. All you can do is approximate in binary. The system does a little fudge-rounding when the numbers print so that it displays .1 instead of .10000000000001 or .999999999999 (which are probably just as close to the stored representation as .1 is)
Edit from comment: The reason this is a problem is our expectations. We fully expect 2/3 to be fudged at some point when we convert it to decimal, either .7 or .67 or .666667.. But we don't automatically expect .1 to be rounded in the same way as 2/3--and that's exactly what's happening.
By the way, if you are curious the number it stores internally is a pure binary representation using a binary "Scientific Notation". So if you told it to store the decimal number 10.75d, it would store 1010b for the 10, and .11b for the decimal. So it would store .101011 then it saves a few bits at the end to say: Move the decimal point four places right.
(Although technically it's no longer a decimal point, it's now a binary point, but that terminology wouldn't have made things more understandable for most people who would find this answer of any use.)
In your stylesheet:
div#content.myClass
Edit: These might help, too:
div#content.myClass.aSecondClass.aThirdClass /* Won't work in IE6, but valid */
div.firstClass.secondClass /* ditto */
and, per your example:
div#content.sectionA
Edit, 4 years later: Since this is super old and people keep finding it: don't use the tagNames in your selectors. #content.myClass
is faster than div#content.myClass
because the tagName adds a filtering step that you don't need. Use tagNames in selectors only where you must!
Instructions:
which java
to find the path to the Java
executable file.su -
to become the root user.vi /root/.bash_profile
to open the system
bash_profile file in the Vi text editor. You can replace vi with
your preferred text editor.export JAVA_HOME=/usr/local/java/
at the bottom of the file.
Replace /usr/local/java
with the location found in step two.exit
to close the root session.echo $JAVA_HOME
to ensure that the path was set
correctly.If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.
Just define an empty navbar prior to the fixed one, it will create the space needed.
<nav class="navbar navbar-default ">
</nav>
<nav class="navbar navbar-default navbar-fixed-top ">
<div class="container-fluid">
// Your menu code
</div>
</nav>
Update:
As of Sep 2017 this method no longer works: --no-install
was removed in pip 7
Use pip install -v
, you can see all versions that available
root@node7:~# pip install web.py -v
Downloading/unpacking web.py
Using version 0.37 (newest of versions: 0.37, 0.36, 0.35, 0.34, 0.33, 0.33, 0.32, 0.31, 0.22, 0.2)
Downloading web.py-0.37.tar.gz (90Kb): 90Kb downloaded
Running setup.py egg_info for package web.py
running egg_info
creating pip-egg-info/web.py.egg-info
To not install any package, use one of following solution:
root@node7:~# pip install --no-deps --no-install flask -v
Downloading/unpacking flask
Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
Downloading Flask-0.10.1.tar.gz (544Kb): 544Kb downloaded
or
root@node7:~# cd $(mktemp -d)
root@node7:/tmp/tmp.c6H99cWD0g# pip install flask -d . -v
Downloading/unpacking flask
Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
Downloading Flask-0.10.1.tar.gz (544Kb): 4.1Kb downloaded
Tested with pip 1.0
root@node7:~# pip --version
pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7)
if($('selector').hasClass('active')){ }
i think this will check if the selector hasClass active ...
The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.
So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.
One way to convert a string to an integer is to use the int function. For example:
percent = (int(pyc) / int(tpy)) * 100
No. While the definition from w3c for HTML 4 doesn't seem to explicitly cover your question, the definition of the name and id attribute says no spaces in the identifier:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
You just need to name the anonymous property the same on both sides
on new { t1.ProjectID, SecondProperty = true } equals
new { t2.ProjectID, SecondProperty = t2.Completed } into j1
Based on the comments of @svick, here is another implementation that might make more sense:
from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
.DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }
For your case the only difference is performance: append is twice as fast.
Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141
In general case append
will add one item to the list, while +=
will copy all elements of right-hand-side list into the left-hand-side list.
Update: perf analysis
Comparing bytecodes we can assume that append
version wastes cycles in LOAD_ATTR
+ CALL_FUNCTION
, and += version -- in BUILD_LIST
. Apparently BUILD_LIST
outweighs LOAD_ATTR
+ CALL_FUNCTION
.
>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_ATTR 1 (append)
12 LOAD_CONST 0 ('spam')
15 CALL_FUNCTION 1
18 POP_TOP
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_CONST 0 ('spam')
12 BUILD_LIST 1
15 INPLACE_ADD
16 STORE_NAME 0 (s)
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
We can improve performance even more by removing LOAD_ATTR
overhead:
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566
The easiest is to convert your data to a "tall" format.
s <-
"A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23
"
d <- read.delim(textConnection(s), sep="")
library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")
# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) +
geom_point() +
stat_smooth()
# Separate plots
ggplot(d, aes(Xax,value)) +
geom_point() +
stat_smooth() +
facet_wrap(~variable)
matches()
will only return true if the full string is matched.
find()
will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find()
multiple times might not be the same. In addition, by using find()
you can call start()
to return the position the substring was matched.
final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());
System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
Will output:
Found: false Found: true - position 4 Found: true - position 17 Found: true - position 20 Found: false Found: false Matched: false ----------- Found: true - position 0 Found: false Found: false Matched: true Matched: true Matched: true Matched: true
So, be careful when calling find()
multiple times if the Matcher
object was not reset, even when the regex is surrounded with ^
and $
to match the full string.
In my system, I use the update alternatives.
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip2 2
If I want to switch between them I use the following command.
sudo update-alternatives --config pip
Note: The 1st line is enough if you have only pip3 installed and not pip2.
git update-index function has several option you can find typing as below:
git update-index --help
Here you will find various option - how to handle with the function update-index.
[if you don't know the file name]
git update-index --really-refresh
[if you know the file name ]
git update-index --no-assume-unchanged <file>
will revert all the files those have been added in ignore list through.
git update-index --assume-unchanged <file>
If you use Ubuntu or Debian, I made a tutorial easy to follow: Install LaTeX on Ubuntu or Debian. This tutorial explains how to install LaTeX and how to create your first PDF.
You can do it in a few lines, just override onPostExecute when you call your AsyncTask. Here is an example for you:
new AasyncTask()
{
@Override public void onPostExecute(String result)
{
// do whatever you want with result
}
}.execute(a.targetServer);
I hope it helped you, happy codding :)
Why not just disable the button if EditText is empty? IMHO This looks more professional:
final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
txtFrecuencia.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
toggle.setEnabled(txtFrecuencia.length() > 0);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
Using WHERE DATE(datetime) = '2009-10-20'
has performance issues. As stated here:
DATE()
for all rows, including those that don't match.Use BETWEEN
or >
, <
, =
operators which allow to use an index:
SELECT * FROM data
WHERE datetime BETWEEN '2009-10-20 00:00:00' AND '2009-10-20 23:59:59'
Update: the impact on using LIKE
instead of operators in an indexed column is high. These are some test results on a table with 1,176,000 rows:
datetime LIKE '2009-10-20%'
=> 2931msdatetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59'
=> 168msWhen doing a second call over the same query the difference is even higher: 2984ms vs 7ms (yes, just 7 milliseconds!). I found this while rewriting some old code on a project using Hibernate.
You can upgrade to Subversion 1.7. In order to update to Subversion 1.7 you have to launch existing project in Xcode 5 or above. This will prompt an warning ‘The working copy ProjectName should be upgraded to Subversion 1.7
’ (shown in below screenshot).
You should select ‘Upgrade
’ button to upgrade to Subversion 1.7. This will take a bit of time.
If you are using terminal then you can upgrade to Subversion 1.7 by running below command in your project directory: svn upgrade
Note that once you have upgraded to Subversion 1.7 you cannot go back to Subversion 1.6.
You can do it like this:
//HTML BUTTON
<button type="button" onclick="disableAll()">Disable</button>
//Jquery function
function disableAll() {
//DISABLE ALL FIELDS THAT ARE NOT DISABLED
$('form').find(':input:not(:disabled)').prop('disabled', true);
//ENABLE ALL FIELDS THAT DISABLED
//$('form').find(':input(:disabled)').prop('disabled', false);
}
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
On iOS 9.2 Profiles
renamed to Device Management
.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.
I have written This library which allows you to wrap your form element components, and lets you define your validators in the format :-
<Validation group="myGroup1"
validators={[
{
validator: (val) => !validator.isEmpty(val),
errorMessage: "Cannot be left empty"
},...
}]}>
<TextField value={this.state.value}
className={styles.inputStyles}
onChange={
(evt)=>{
console.log("you have typed: ", evt.target.value);
}
}/>
</Validation>
Pillow is released with installation wheels on Windows:
We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included
https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation
Update: Python 3.6 is now supported by Pillow. Install with pip install pillow
and check https://pillow.readthedocs.io/en/latest/installation.html for more information.
However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).
https://travis-ci.org/python-pillow/Pillow/jobs/155605577
If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:
https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source
And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):
https://github.com/python-pillow/Pillow/tree/master/winbuild
Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.
If this is long array you could use
var sb = arr.Aggregate(new StringBuilder(), ( s, i ) => s.Append( i ), s.ToString());
If the current directory is empty, you can do that with:
git clone git@github:me/name.git .
(Note the .
at the end to specify the current directory.) Of course, this also creates the .git
directory in your current folder, not just the source code from your project.
This optional [directory]
parameter is documented in the git clone
manual page, which points out that cloning into an existing directory is only allowed if that directory is empty.
function readURL(input) {_x000D_
if (input.files && input.files[0]) {_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onload = function(e) {_x000D_
$('#ImdID').attr('src', e.target.result);_x000D_
};_x000D_
_x000D_
reader.readAsDataURL(input.files[0]);_x000D_
}_x000D_
}
_x000D_
img {_x000D_
max-width: 180px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type='file' onchange="readURL(this);" />_x000D_
<img id="ImdID" src="" alt="Image" />
_x000D_
private void Button1_Click(object sender, EventArgs e)
{
NewForm newForm = new NewForm(); //Create the New Form Object
this.Hide(); //Hide the Old Form
newForm.ShowDialog(); //Show the New Form
this.Close(); //Close the Old Form
}
Yes, but you can select only one column in your subselect
SELECT (SELECT id FROM bla) AS my_select FROM bla2
Since you're using JPA, use the Lob
annotation (and optionally the Column
annotation). Here is what the JPA specification says about it:
9.1.19 Lob Annotation
A
Lob
annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use theLob
annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with theBasic
annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.
So declare something like this:
@Lob
@Column(name="CONTENT", length=512)
private String content;
Pragma mark - [SOME TEXT HERE]
was used in Objective-C to group several function together by line separating.
In Swift you can achieve this using MARK, TODO OR FIXME
i. MARK : //MARK: viewDidLoad
This will create a horizontal line with functions grouped under viewDidLoad(shown in screenshot 1)
ii. TODO : //TODO: - viewDidLoad
This will group function under TODO: - viewDidLoad category (shown in screenshot 2)
iii. FIXME : //FIXME - viewDidLoad
This will group function under FIXME: - viewDidLoad category (shown in screenshot 3)
Check this apple documentation for details.
onload event it only supports with few tags like listed below.
<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
Here the reference for onload event
Corrected as of 25.06.2019:
var newDate = new Date(date.setMonth(date.getMonth()+8));
Old From here:
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);
macOS 10.15.7
Prefrences...
Window
tabScrollback
to Limit number of rows to:
what your wanted.You were close. format=
needs to be added to the as.Date
call:
mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"
I have just figured out a simple way to achieve this using an Array filter
var list = [9, 9, 111, 2, 3, 4, 4, 5, 7];_x000D_
_x000D_
// Filter 1: to find all duplicates elements_x000D_
var duplicates = list.filter(function(value,index,self) {_x000D_
return self.indexOf(value) !== self.lastIndexOf(value) && self.indexOf(value) === index;_x000D_
});_x000D_
_x000D_
console.log(duplicates);
_x000D_
UPDATE R
SET R.status = '0'
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P
ON R.pid = P.id
WHERE R.id = '17190'
AND P.shopkeeper = '89137';
Additional information for modern (systemd) linux systems.
There are many resources about this of values that may need tweaking (such as How to increase maximum number of JVM threads (Linux 64bit)); however a new limit is imposed by way of the systemd "TasksMax" limit which sets pids.max on the cgroup.
For login sessions the UserTasksMax default is 33% of the kernel limit pids_max (usually 12,288) and can be override in /etc/systemd/logind.conf.
For services the DefaultTasksMax default is 15% of the kernel limit pids_max (usually 4,915). You can override it for the service by setting TasksMax in "systemctl edit" or update DefaultTasksMax in /etc/systemd/system.conf
This will add thousand separators while retaining the decimal part of a given number:
function format(n, sep, decimals) {
sep = sep || "."; // Default to period as decimal separator
decimals = decimals || 2; // Default to 2 decimals
return n.toLocaleString().split(sep)[0]
+ sep
+ n.toFixed(decimals).split(sep)[1];
}
format(4567354.677623); // 4,567,354.68
You could also probe for the locale's decimal separator with:
var sep = (0).toFixed(1)[1];
If something does not work, when coming thru the front-door, then take the back-door:
drop table if exists apples;
create table if not exists apples(variety char(10) primary key, price int);
insert into apples values('fuji', 5), ('gala', 6);
drop table if exists apples_new;
create table if not exists apples_new like apples;
insert into apples_new select * from apples;
update apples_new
set price = (select price from apples where variety = 'gala')
where variety = 'fuji';
rename table apples to apples_orig;
rename table apples_new to apples;
drop table apples_orig;
It's fast. The bigger the data, the better.
Please try below code, I think this will solve your problem.
var classObj = new Class1();
classObj.Name => "StackOverflow";
var property = new Class1().GetType().GetProperty(nameof(classObj.Name));
var displayNameAttributeValue = (property ?? throw new InvalidOperationException())
.GetCustomAttributes(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
if (displayNameAttributeValue != null)
{
Console.WriteLine("{0} = {1}", displayNameAttributeValue, classObj.Name);
}
Since the img is an inline element, Just use text-center
on it's container. Using mx-auto
will center the container (column) too.
<div class="row">
<div class="col-4 mx-auto text-center">
<img src="..">
</div>
</div>
By default, images are display:inline
. If you only want the center the image (and not the other column content), make the image display:block
using the d-block
class, and then mx-auto
will work.
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="..">
</div>
</div>
Option 1. Using boost library, you can declare the string as below
const boost::string_view helpText = "This is very long help text.\n"
"Also more text is here\n"
"And here\n"
// Pass help text here
setHelpText(helpText);
Option 2. If boost is not available in your project, you can use std::string_view() in modern C++.
Try something like the following if you want to use pure JavaScript:
document.getElementsByName('link')[0].placeholder='Type here to search';
To get the type name as a string in Swift 4 (I haven't checked the earlier versions), just use string interpolation:
"\(type(of: myViewController))"
You can use .self
on a type itself, and the type(of:_)
function on an instance:
// Both constants will have "UIViewController" as their value
let stringFromType = "\(UIViewController.self)"
let stringFromInstance = "\(type(of: UIViewController()))"
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
Use this to find total count in resulting collection.
db.collection.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );
The getElementById
method returns an Element object that you can use to interact with the element. If the element is not found, null
is returned. In case of an input element, the value
property of the object contains the string in the value attribute.
By using the fact that the &&
operator short circuits, and that both null
and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:
var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
alert("My input has a value!");
}
declare @T table
(
Col varchar(20)
)
insert into @T
Select 'images/test1.jpg'
union all
Select 'images/test2.png'
union all
Select 'images/test3.jpg'
union all
Select 'images/test4.jpeg'
union all
Select 'images/test5.jpeg'
Select substring( LEFT(Col,charindex('.',Col)-1),charindex('/',Col)+1,len(LEFT(Col,charindex('.',Col)-1))-1 )
from @T
div.section > div
Postman is the best application to test your APIs !
You can import or export your routes and let him remember all your body requests ! :)
EDIT : This comment is 5 yea's old and deprecated :D
Here's the new Postman App : https://www.postman.com/
i personally would prefer
if(true == foo)
{
}
there is no chance for the ==/= mistype and i find it more expressive in terms of foo's type. But it is a very subjective question.
Use the CREATE TABLE SELECT syntax.
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
After evaluating the answers and studying the topic I'd like to summarize.
The Docker way to upgrade containers seems to be the following:
Application containers should not store application data. This way you can replace app container with its newer version at any time by executing something like this:
docker pull mysql
docker stop my-mysql-container
docker rm my-mysql-container
docker run --name=my-mysql-container --restart=always \
-e MYSQL_ROOT_PASSWORD=mypwd -v /my/data/dir:/var/lib/mysql -d mysql
You can store data either on host (in directory mounted as volume) or in special data-only container(s). Read more about it
Upgrading applications (eg. with yum/apt-get upgrade) within containers is considered to be an anti-pattern. Application containers are supposed to be immutable, which shall guarantee reproducible behavior. Some official application images (mysql:5.6 in particular) are not even designed to self-update (apt-get upgrade won't work).
I'd like to thank everybody who gave their answers, so we could see all different approaches.
A very useful but lesser-known fact about sed is that the familiar s/foo/bar/
command can use any punctuation, not only slashes. A common alternative is s@foo@bar@
, from which it becomes obvious how to solve your problem.
To get the first key of your object
const myObject = {
'foo1': { name: 'myNam1' },
'foo2': { name: 'myNam2' }
}
const result = Object.keys(myObject)[0];
// result will return 'foo1'
Or you could just use justify-content: flex-end
.main { display: flex; }
.c { justify-content: flex-end; }
Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.
I like this way of adding a confirmation prompt before deleting a record from a gridview. This is the CommandField definition nested within a GridView web control in the aspx page. There's nothing fancy here--just a straightforward Commandfield.
<asp:CommandField ShowEditButton="true" UpdateText="Save" ShowDeleteButton="True">_x000D_
<ControlStyle CssClass="modMarketAdjust" />_x000D_
</asp:CommandField>
_x000D_
Then, all I had to do was add some code to the RowDeleting event of the GridView control. This event fires before the row is actually deleted, which allows you to get the user's confirmation, and to cancel the event if he doesn't want to cancel after all. Here is the code that I put in the RowDeleting event handler:
Private Sub grdMarketAdjustment_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grdMarketAdjustment.RowDeleting
Dim confirmed As Integer = MsgBox("Are you sure that you want to delete this market adjustment?", MsgBoxStyle.YesNo + MsgBoxStyle.MsgBoxSetForeground, "Confirm Delete")
If Not confirmed = MsgBoxResult.Yes Then
e.Cancel = True 'Cancel the delete.
End If
End Sub
And that seems to work fine.
I followed the following steps:--
react-native unlink <lib name>
-- this command has done the unlinking of the library from both platforms.
react-native uninstall <lib name>
-- this has uninstalled the library from the node modules and its dependencies
Manually removed the library name from package.json
-- somehow the --save command was not working for me to remove the library declaration from package.json.
After this I have manually deleted the empty react-native library from the node_modules folder
Most of the answers for this question can not helped me in 2020.
This notification from download site of Oracle may be the reason:
Important Oracle JDK License Update
The Oracle JDK License has changed for releases starting April 16, 2019.
I try to google a little bit and those tutorials below helped me a lot.
Remove completely the previous version of JVM installed on your PC.
sudo update-alternatives --remove-all java
sudo update-alternatives --remove-all javac
sudo update-alternatives --remove-all javaws
# /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
sudo rm -rf /usr/lib/jvm/jdk1.7.0
Check to see whether java is uninstalled or not
java -version
1.8.0_251
. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.cd /usr/lib/jvm
sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
sudo gedit /etc/environment
:/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
update-alternatives --list java
update-alternatives --list javac
I solve this trouble with config APACHE ! All methods (in this topic) is incorrect for me... Then I try chanche apache config:
Timeout 3600
Then my script worked!
This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.
The handler you wish to use
Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());
The inner class
class IncomingHandlerCallback implements Handler.Callback{
@Override
public boolean handleMessage(Message message) {
// Handle message code
return true;
}
}
You will need to melt
your dataframe to get it into the so-called long format:
require(reshape2)
sample.data.M <- melt(sample.data)
Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:
require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")
Instead of stacking you may also be interested in showing multiple plots using facets:
c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")
You should be able to set the className property of the element. You could do a += to append it.
It's hard to do this.
There is a min-height:
css style, but it doesn't work in all browsers. You can use it, but the biggest problem is that you will need to set it to something like 90% or numbers like that (percents), but the top and bottom divs use fixed pixel sizes, and you won't be able to reconcile them.
var minHeight = $(window).height() -
$('#a').outerHeight(true) -
$('#c').outerHeight(true));
if($('#b').height() < minHeight) $('#b').height(minHeight);
I know a
and c
have fixed heights, but I rather measure them in case they change later.
Also, I am measuring the height of b
(I don't want to make is smaller after all), but if there is an image in there that did not load the height can change, so watch out for things like that.
It may be safer to do:
$('#b').prepend('<div style="float: left; width: 1px; height: ' + minHeight + 'px;"> </div>');
Which simply adds an element into that div with the correct height - that effectively acts as min-height even for browsers that don't have it. (You may want to add the element into your markup, and then just control the height of it via javascript instead of also adding it that way, that way you can take it into account when designing the layout.)
I'm starting to think of a really simple solution, don't know why I didn't think of it before!!
This way I can switch branches without worrying about database schema changes.
By duplicate, I mean create another database with a different name (like my_db_2
); not doing a dump or anything like that.
If you define your array in properties file like:
base.module.elementToSearch=1,2,3,4,5,6
You can load such array in your Java class like this:
@Value("${base.module.elementToSearch}")
private String[] elementToSearch;
For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:
easy_install -U packageName
Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#abc').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'post.php',
method:'POST',
data: new FormData(this),
contentType: false,
cache:false,
processData:false,
success: function (data) {
alert(data);
location.reload();
}
});
});
});
</script>
</head>
<body>
<form enctype= "multipart/form-data" id="abc">
<input name="fname" ><br>
<input name="lname"><br>
<input type="file" name="file" required=""><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
I used a list in my controller class to set data into grid view. The code works fine for me:
public ActionResult ExpExcl()
{
List<PersonModel> person= new List<PersonModel>
{
new PersonModel() {FirstName= "Jenny", LastName="Mathew", Age= 23},
new PersonModel() {FirstName= "Paul", LastName="Meehan", Age=25}
};
var grid= new GridView();
grid.DataSource= person;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition","attachement; filename=data.xls");
Response.ContentType="application/excel";
StringWriter sw= new StringWriter();
HtmlTextWriter htw= new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View();
}
Your best bet is to use WMI. Specifically the Win32_Product class.
I got this after upgrading to ruby 2.1.0. My PATH
was set in my login script to include .gem/ruby/2.0.0/bin
. Updating the version number fixed it.
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.
The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.
You can use different types of redirect method in laravel -
return redirect()->intended('http://heera.it');
OR
return redirect()->to('http://heera.it');
OR
use Illuminate\Support\Facades\Redirect;
return Redirect::to('/')->with(['type' => 'error','message' => 'Your message'])->withInput(Input::except('password'));
OR
return redirect('/')->with(Auth::logout());
OR
return redirect()->route('user.profile', ['step' => $step, 'id' => $id]);
There's a messy workaround at http://www.ozgrid.com/Excel/autocomplete-validation.htm that basically works like this:
Tools - Options > Edit
;You can't do window.history.back(); and location.reload(); in the same function.
window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.
location.reload() has to be called on the page you redirect to when using window.history.back().
I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.
Validate the INPUT.
$time = strtotime($_POST['dateFrom']);
if ($time) {
$new_date = date('Y-m-d', $time);
echo $new_date;
} else {
echo 'Invalid Date: ' . $_POST['dateFrom'];
// fix it.
}
Looking at the dates for which it doesn't work -- those where the day is less than or equal to 12 -- I'm wondering whether it's parsing the dates as being in YYYY-DD-MM format?
Sometimes, the best solution is to use both. Sometimes, it is to use neither. And sometimes, it is to use one or the other. If you want all the styles, including margin and padding reset across all browsers, use reset.css. Then apply all decorations and stylings yourself. If you simply like the built-in stylings but want more cross-browser synchronicity i.e. normalizations then use normalize.css. But if you choose to use both reset.css and normalize.css, link the reset.css stylesheet first and then the normalize.css stylesheet (immediately) afterwards. Sometimes it's not always a matter of which is better, but when to use which one versus when to use both versus when to use neither. IMHO.
So in your build.gradle
file, add this:
compile 'com.android.support:design:27.1.1'
AndroidX Note: Google is introducing new AndroidX extension libraries to replace the older Support Libraries. To use AndroidX, first make sure you've updated your gradle.properties
file, edited build.gradle
to set compileSdkVersion
to 28
(or higher), and use the following line instead of the previous compile
one.
implementation 'com.google.android.material:material:1.0.0'
Next, in your themes.xml
or styles.xml
or whatever, make sure you set this- it's your app's accent color-- and the color of your FAB unless you override it (see below):
<item name="colorAccent">@color/floating_action_button_color</item>
In the layout's XML:
<RelativeLayout
...
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.FloatingActionButton
android:id="@+id/myFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_plus_sign"
app:elevation="4dp"
... />
</RelativeLayout>
Or if you are using the AndroidX material library above, you'd instead use this:
<RelativeLayout
...
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/myFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:srcCompat="@drawable/ic_plus_sign"
app:elevation="4dp"
... />
</RelativeLayout>
You can see more options in the docs (material docs here) (setRippleColor
, etc.), but one of note is:
app:fabSize="mini"
Another interesting one-- to change the background color of just one FAB, add:
app:backgroundTint="#FF0000"
(for example to change it to red) to the XML above.
Anyway, in code, after the Activity/Fragment's view is inflated....
FloatingActionButton myFab = (FloatingActionButton) myView.findViewById(R.id.myFAB);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doMyThing();
}
});
Observations:
Here's a way to remove or change the padding if there's too much:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) myFab.getLayoutParams();
p.setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
myFab.setLayoutParams(p);
}
Also, I was going to programmatically place the FAB on the "seam" between two areas in a RelativeLayout by grabbing the FAB's height, dividing by two, and using that as the margin offset. But myFab.getHeight() returned zero, even after the view was inflated, it seemed. Instead I used a ViewTreeObserver to get the height only after it's laid out and then set the position. See this tip here. It looked like this:
ViewTreeObserver viewTreeObserver = closeButton.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
closeButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
closeButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// not sure the above is equivalent, but that's beside the point for this example...
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) closeButton.getLayoutParams();
params.setMargins(0, 0, 16, -closeButton.getHeight() / 2); // (int left, int top, int right, int bottom)
closeButton.setLayoutParams(params);
}
});
}
Not sure if this is the right way to do it, but it seems to work.
If you want the FAB on a "seam" you can use layout_anchor
and layout_anchorGravity
here is an example:
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_anchor="@id/appbar"
app:layout_anchorGravity="bottom|right|end"
android:src="@drawable/ic_discuss"
android:layout_margin="@dimen/fab_margin"
android:clickable="true"/>
Remember that you can automatically have the button jump out of the way when a Snackbar comes up by wrapping it in a CoordinatorLayout.
More:
I'm using UAParser https://github.com/faisalman/ua-parser-js
var a = new UAParser();
var name = a.getResult().browser.name;
var version = a.getResult().browser.version;
An other implementation of @qneill code which include CRC checksum of the original message, it throw an exception if the check fail:
import hashlib
import struct
import zlib
def vigenere_encode(text, key):
text = '{}{}'.format(text, struct.pack('i', zlib.crc32(text)))
enc = []
for i in range(len(text)):
key_c = key[i % len(key)]
enc_c = chr((ord(text[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def vigenere_decode(encoded_text, key):
dec = []
encoded_text = base64.urlsafe_b64decode(encoded_text)
for i in range(len(encoded_text)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(encoded_text[i]) - ord(key_c)) % 256)
dec.append(dec_c)
dec = "".join(dec)
checksum = dec[-4:]
dec = dec[:-4]
assert zlib.crc32(dec) == struct.unpack('i', checksum)[0], 'Decode Checksum Error'
return dec
Hi For jQuery You can only use like this
Use async and type="text/javascript" only
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
To replace a string in multiple files you can use:
grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'
E.g.
grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'
First run ng g module newModule
. Then run ng g component newModule/newModule --flat
I am using Oh-My-Zshell and the previous aliases stated didn't work for me so I wrote a simple bash function that will allow you to open Sublime from the command line by using sublime
to open the current folder in the editor. With the addition functionality to specify a file to open the editor from.
# Open Sublime from current folder or specified folder
sublime(){
/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl ./$1
}
Usage to open current folder in terminal:
$ sublime
Usage to open specific folder:
$ sublime path/to/the/file/to/open
Each Java process has a pid
, which you first need to find with the jps
command.
Once you have the pid, you can use jstat -gc [insert-pid-here]
to find statistics of the behavior of the garbage collected heap.
jstat -gccapacity [insert-pid-here]
will present information about memory pool generation and space capabilities.
jstat -gcutil [insert-pid-here]
will present the utilization of each generation as a percentage of its capacity. Useful to get an at a glance view of usage.
See jstat docs on Oracle's site.
The breakdown of your declaration and its members is somewhat littered:
Remove the typedef
The typedef
is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos
as-written, which is core to your current compilation failure.
Change this:
typedef struct {....} pos;
To this:
struct pos { ... };
Remove extraneous inlines
You're both declaring and defining your member operators within the class definition itself. The inline
keyword is not needed so long as your implementations remain in their current location (the class definition)
Return references to *this
where appropriate
This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:
a = b = c;
This assigns c
to b
, and the resulting value b
is then assigned to a
. This is not equivalent to the following code, contrary to what you may think:
a = c;
b = c;
Therefore, your assignment operator should be implemented as such:
pos& operator =(const pos& a)
{
x = a.x;
y = a.y;
return *this;
}
Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)
Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:
pos& operator=(pos a) // by-value param invokes class copy-ctor
{
this->swap(a);
return *this;
}
Then a swap method is implemented:
void pos::swap(pos& obj)
{
// TODO: swap object guts with obj
}
You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.
Pass objects by const reference when appropriate
All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:
Change this:
bool operator==(pos a) const{
if(a.x==x && a.y== y)return true;
else return false;
}
To this: (also simplified)
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
No copies of anything are made, resulting in more efficient code.
Finally, in answering your question, what is the difference between a member function or operator declared as const
and one that is not?
A const
member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const
member functions can be invoked against const
objects, or const
references and pointers. For example, your operator +()
does not modify your local object and thus should be declared as const
. Your operator =()
clearly modifies the local object, and therefore the operator should not be const
.
Summary
struct pos
{
int x;
int y;
// default + parameterized constructor
pos(int x=0, int y=0)
: x(x), y(y)
{
}
// assignment operator modifies object, therefore non-const
pos& operator=(const pos& a)
{
x=a.x;
y=a.y;
return *this;
}
// addop. doesn't modify object. therefore const.
pos operator+(const pos& a) const
{
return pos(a.x+x, a.y+y);
}
// equality comparison. doesn't modify object. therefore const.
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
};
EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:
a = b = c;
Is equivalent to this:
b = c;
a = b;
And that this does not always equate to this:
a = c;
b = c;
Sample code:
#include <iostream>
#include <string>
using namespace std;
struct obj
{
std::string name;
int value;
obj(const std::string& name, int value)
: name(name), value(value)
{
}
obj& operator =(const obj& o)
{
cout << name << " = " << o.name << endl;
value = (o.value+1); // note: our value is one more than the rhs.
return *this;
}
};
int main(int argc, char *argv[])
{
obj a("a", 1), b("b", 2), c("c", 3);
a = b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
a = c;
b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
return 0;
}
Output
b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3
In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline()
. While by default it will read up to the next '\n'
(which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like =
in your example.
For simplicity, the following presumes that the =
are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws
before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.
const char config[] = "url=http://example.com\n"
"file=main.exe\n"
"true=0";
std::istringstream is_file(config);
std::string line;
while( std::getline(is_file, line) )
{
std::istringstream is_line(line);
std::string key;
if( std::getline(is_line, key, '=') )
{
std::string value;
if( std::getline(is_line, value) )
store_line(key, value);
}
}
(Adding error handling is left as an exercise to the reader.)
git pull origin master
will fetch all the changes from the remote's master branch and will merge it into your local.We generally don't use git pull origin/master.We can do the same thing by git merge origin/master
.It will merge all the changes from "cached copy" of origin's master branch into your local branch.In my case git pull origin/master
is throwing the error.
The following might be useful (tested on: Linux/Ubuntu 12.04 (Precise Pangolin)):
cat /dev/ttyUSB0
Using the above, you can then do all the re-directions that you need. For example, to dump output to your console while saving to your file, you'd do:
cat /dev/ttyUSB0 | tee console.log
If you need to continue with additional logic use...
break;
or if you have a value to return...
return my_value_to_be_returned;
However, looking at your code, I believe you will control the loop with the revised example below without using a break or return...
private void CheckLog()
{
bool continueLoop = true;
while (continueLoop)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while (continueLoop && (s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
continueLoop = false;
}
}
}
}
}
The Wingware editor from http://www.wingware.com is Python-specific with very good auto-completion for Python/Django/Zope, etc.
It has a built in Python shell to run snippets (or select and run) and support for Mercurial/Git, etc. and a built-in unittest/nose/doctest test runner. It's commercial though, but as it is written in Python, it's cross platform.
I bought it a while ago, and thought it looked dorky, but I've tried them all and keep coming back. Caveat that I am a Windows guy with no Emacs or Vim skills, so leveraging that was not an option. And the Mac version requires X Window and seems to be more glitchy.
You're looking for Select
which can be used to transform\project the input sequence:
IEnumerable<string> strings = integers.Select(i => i.ToString());
I currently use this statusbar settings:
set laststatus=2
set statusline=\ %f%m%r%h%w\ %=%({%{&ff}\|%{(&fenc==\"\"?&enc:&fenc).((exists(\"+bomb\")\ &&\ &bomb)?\",B\":\"\")}%k\|%Y}%)\ %([%l,%v][%p%%]\ %)
My complete .vimrc file: http://gabriev82.altervista.org/projects/vim-configuration/
This is specifically mentioned in the libcurl FAQ entry "Protocol xxx not supported or disabled in libcurl".
For your pleasure I'm embedding the explanation here too:
When passing on a URL to curl to use, it may respond that the particular protocol is not supported or disabled. The particular way this error message is phrased is because curl doesn't make a distinction internally of whether a particular protocol is not supported (ie never got any code added that knows how to speak that protocol) or if it was explicitly disabled. curl can be built to only support a given set of protocols, and the rest would then be disabled or not supported.
Note that this error will also occur if you pass a wrongly spelled protocol part as in "htpt://example.com" or as in the less evident case if you prefix the protocol part with a space as in " http://example.com/".
The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
If you want to do something x times, you can do this:
Example (x = 200):
FOR /L %%A IN (1,1,200) DO (
ECHO %%A
)
1,1,200
means:
$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);
Where
Although I am not sure if this is the result you expect, you can save your DataFrame in png by plotting the DataFrame with Seaborn Heatmap with annotations on, like this:
http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html#seaborn.heatmap
It works right away with a Pandas Dataframe. You can look at this example: Efficiently ploting a table in csv format using Python
You might want to change the colormap so it displays a white background only.
Hope this helps.
DELETE FROM ... WHERE id=...;
protected function templateRemove($id){
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));
if ($entity != null){
$em->remove($entity);
$em->flush();
}
}
Here's a script that claims to be able to fix this.
Get admin rights to your local SQL Server Express with this simple script
Description
This command script allows you to easily add yourself to the sysadmin role of a local SQL Server instance. You must be a member of the Windows local Administrators group, or have access to the credentials of a user who is. The script supports SQL Server 2005 and later.
The script is most useful if you are a developer trying to use SQL Server 2008 Express that was installed by someone else. In this situation you usually won't have admin rights to the SQL Server 2008 Express instance, since by default only the person installing SQL Server 2008 is granted administrative privileges.
The user who installed SQL Server 2008 Express can use SQL Server Management Studio to grant the necessary privileges to you. But what if SQL Server Management Studio was not installed? Or worse if the installing user is not available anymore?
This script fixes the problem in just a few clicks!
Note: You will need to provide the BAT file with an 'Instance Name' (Probably going to be 'MSSQLSERVER' - but it might not be): you can get the value by first running the following in the "Microsoft SQL Server Management Console":
SELECT @@servicename
Then copy the result to use when the BAT file prompts for 'SQL instance name'.
@echo off
rem
rem ****************************************************************************
rem
rem Copyright (c) Microsoft Corporation. All rights reserved.
rem This code is licensed under the Microsoft Public License.
rem THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
rem ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
rem IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
rem PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
rem
rem ****************************************************************************
rem
rem CMD script to add a user to the SQL Server sysadmin role
rem
rem Input: %1 specifies the instance name to be modified. Defaults to SQLEXPRESS.
rem %2 specifies the principal identity to be added (in the form "<domain>\<user>").
rem If omitted, the script will request elevation and add the current user (pre-elevation) to the sysadmin role.
rem If provided explicitly, the script is assumed to be running elevated already.
rem
rem Method: 1) restart the SQL service with the '-m' option, which allows a single connection from a box admin
rem (the box admin is temporarily added to the sysadmin role with this start option)
rem 2) connect to the SQL instance and add the user to the sysadmin role
rem 3) restart the SQL service for normal connections
rem
rem Output: Messages indicating success/failure.
rem Note that if elevation is done by this script, a new command process window is created: the output of this
rem window is not directly accessible to the caller.
rem
rem
setlocal
set sqlresult=N/A
if .%1 == . (set /P sqlinstance=Enter SQL instance name, or default to SQLEXPRESS: ) else (set sqlinstance=%1)
if .%sqlinstance% == . (set sqlinstance=SQLEXPRESS)
if /I %sqlinstance% == MSSQLSERVER (set sqlservice=MSSQLSERVER) else (set sqlservice=MSSQL$%sqlinstance%)
if .%2 == . (set sqllogin="%USERDOMAIN%\%USERNAME%") else (set sqllogin=%2)
rem remove enclosing quotes
for %%i in (%sqllogin%) do set sqllogin=%%~i
@echo Adding '%sqllogin%' to the 'sysadmin' role on SQL Server instance '%sqlinstance%'.
@echo Verify the '%sqlservice%' service exists ...
set srvstate=0
for /F "usebackq tokens=1,3" %%i in (`sc query %sqlservice%`) do if .%%i == .STATE set srvstate=%%j
if .%srvstate% == .0 goto existerror
rem
rem elevate if <domain/user> was defaulted
rem
if NOT .%2 == . goto continue
echo new ActiveXObject("Shell.Application").ShellExecute("cmd.exe", "/D /Q /C pushd \""+WScript.Arguments(0)+"\" & \""+WScript.Arguments(1)+"\" %sqlinstance% \""+WScript.Arguments(2)+"\"", "", "runas"); >"%TEMP%\addsysadmin{7FC2CAE2-2E9E-47a0-ADE5-C43582022EA8}.js"
call "%TEMP%\addsysadmin{7FC2CAE2-2E9E-47a0-ADE5-C43582022EA8}.js" "%cd%" %0 "%sqllogin%"
del "%TEMP%\addsysadmin{7FC2CAE2-2E9E-47a0-ADE5-C43582022EA8}.js"
goto :EOF
:continue
rem
rem determine if the SQL service is running
rem
set srvstarted=0
set srvstate=0
for /F "usebackq tokens=1,3" %%i in (`sc query %sqlservice%`) do if .%%i == .STATE set srvstate=%%j
if .%srvstate% == .0 goto queryerror
rem
rem if required, stop the SQL service
rem
if .%srvstate% == .1 goto startm
set srvstarted=1
@echo Stop the '%sqlservice%' service ...
net stop %sqlservice%
if errorlevel 1 goto stoperror
:startm
rem
rem start the SQL service with the '-m' option (single admin connection) and wait until its STATE is '4' (STARTED)
rem also use trace flags as follows:
rem 3659 - log all errors to errorlog
rem 4010 - enable shared memory only (lpc:)
rem 4022 - do not start autoprocs
rem
@echo Start the '%sqlservice%' service in maintenance mode ...
sc start %sqlservice% -m -T3659 -T4010 -T4022 >nul
if errorlevel 1 goto startmerror
:checkstate1
set srvstate=0
for /F "usebackq tokens=1,3" %%i in (`sc query %sqlservice%`) do if .%%i == .STATE set srvstate=%%j
if .%srvstate% == .0 goto queryerror
if .%srvstate% == .1 goto startmerror
if NOT .%srvstate% == .4 goto checkstate1
rem
rem add the specified user to the sysadmin role
rem access tempdb to avoid a misleading shutdown error
rem
@echo Add '%sqllogin%' to the 'sysadmin' role ...
for /F "usebackq tokens=1,3" %%i in (`sqlcmd -S np:\\.\pipe\SQLLocal\%sqlinstance% -E -Q "create table #foo (bar int); declare @rc int; execute @rc = sp_addsrvrolemember '$(sqllogin)', 'sysadmin'; print 'RETURN_CODE : '+CAST(@rc as char)"`) do if .%%i == .RETURN_CODE set sqlresult=%%j
rem
rem stop the SQL service
rem
@echo Stop the '%sqlservice%' service ...
net stop %sqlservice%
if errorlevel 1 goto stoperror
if .%srvstarted% == .0 goto exit
rem
rem start the SQL service for normal connections
rem
net start %sqlservice%
if errorlevel 1 goto starterror
goto exit
rem
rem handle unexpected errors
rem
:existerror
sc query %sqlservice%
@echo '%sqlservice%' service is invalid
goto exit
:queryerror
@echo 'sc query %sqlservice%' failed
goto exit
:stoperror
@echo 'net stop %sqlservice%' failed
goto exit
:startmerror
@echo 'sc start %sqlservice% -m' failed
goto exit
:starterror
@echo 'net start %sqlservice%' failed
goto exit
:exit
if .%sqlresult% == .0 (@echo '%sqllogin%' was successfully added to the 'sysadmin' role.) else (@echo '%sqllogin%' was NOT added to the 'sysadmin' role: SQL return code is %sqlresult%.)
endlocal
pause
There is a calc
function in both SCSS [compile-time] and CSS [run-time]. You're likely invoking the former instead of the latter.
For obvious reasons mixing units won't work compile-time, but will at run-time.
You can force the latter by using unquote
, a SCSS function.
.selector { height: unquote("-webkit-calc(100% - 40px)"); }
How do you change your cursor to the finger (like for clicking on links) instead of the regular pointer?
This is very simple to achieve using the CSS property cursor
, no jQuery
needed.
You can read more about in: CSS cursor property
and cursor - CSS | MDN
.default {_x000D_
cursor: default;_x000D_
}_x000D_
.pointer {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<a class="default" href="#">default</a>_x000D_
_x000D_
<a class="pointer" href="#">pointer</a>
_x000D_
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
For Bootstrap 4, use the below code:
<div class="mx-auto" style="width: 200px;">
Centered element
</div>
Ref: https://getbootstrap.com/docs/4.0/utilities/spacing/#horizontal-centering
window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';
Nothing Worked for me.
Refactoring of @srini-beerge's answer which gets the output and the return code
import subprocess
def run_win_cmd(cmd):
result = []
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in process.stdout:
result.append(line)
errcode = process.returncode
for line in result:
print(line)
if errcode is not None:
raise Exception('cmd %s failed, see above for details', cmd)
Normally the native way we do things in linux and the way we think is from left to right.
So you would go and write what you are looking for first:
find / -name "*.php"
Then you probably hit enter and realize you are getting too many files from
directories you wish not to.
Let's exclude /media to avoid searching your mounted drives.
You should now just APPEND the following to the previous command:
-print -o -path '/media' -prune
so the final command is:
find / -name "*.php" -print -o -path '/media' -prune
...............|<--- Include --->|....................|<---------- Exclude --------->|
I think this structure is much easier and correlates to the right approach
It's my way to resolve this question. Tested on SQLServer2008R2
CREATE PROC SearchAllTables
@SearchStr nvarchar(100)
AS
BEGIN
DECLARE @dml nvarchar(max) = N''
IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL DROP TABLE dbo.#Results
CREATE TABLE dbo.#Results
([tablename] nvarchar(100),
[ColumnName] nvarchar(100),
[Value] nvarchar(max))
SELECT @dml += ' SELECT ''' + s.name + '.' + t.name + ''' AS [tablename], ''' +
c.name + ''' AS [ColumnName], CAST(' + QUOTENAME(c.name) +
' AS nvarchar(max)) AS [Value] FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) +
' (NOLOCK) WHERE CAST(' + QUOTENAME(c.name) + ' AS nvarchar(max)) LIKE ' + '''%' + @SearchStr + '%'''
FROM sys.schemas s JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types ty ON c.system_type_id = ty.system_type_id AND c .user_type_id = ty .user_type_id
WHERE t.is_ms_shipped = 0 AND ty.name NOT IN ('timestamp', 'image', 'sql_variant')
INSERT dbo.#Results
EXEC sp_executesql @dml
SELECT *
FROM dbo.#Results
END
Pass 65536
to mysql_connect
as 5th parameter.
Example:
$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */)
or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);
DELETE FROM table3 WHERE field6 = 6;
UPDATE table4 SET field7 = 7 WHERE field8 = 8;
INSERT INTO table5
SELECT t6.field11, t6.field12, t7.field13
FROM table6 t6
INNER JOIN table7 t7 ON t7.field9 = t6.field10;
-- etc
");
When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.
For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
SELECT * FROM table2;
");
Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
SELECT * FROM table2;
INSERT INTO table1 (field1,field2) VALUES(1,2);
");
I really recommend you read about Information Theory, bayesian methods and MaxEnt. The place to start is this (freely available online) book by David Mackay:
http://www.inference.phy.cam.ac.uk/mackay/itila/
Those inference methods are really far more general than just text mining and I can't really devise how one would learn how to apply this to NLP without learning some of the general basics contained in this book or other introductory books on Machine Learning and MaxEnt bayesian methods.
The connection between entropy and probability theory to information processing and storing is really, really deep. To give a taste of it, there's a theorem due to Shannon that states that the maximum amount of information you can pass without error through a noisy communication channel is equal to the entropy of the noise process. There's also a theorem that connects how much you can compress a piece of data to occupy the minimum possible memory in your computer to the entropy of the process that generated the data.
I don't think it's really necessary that you go learning about all those theorems on communication theory, but it's not possible to learn this without learning the basics about what is entropy, how it's calculated, what is it's relationship with information and inference, etc...
Depending on your use case, this might also be an option:
$str = 'In My Cart : 11 items';
$num = '';
for ($i = 0; $i < strlen($str); $i++) {
if (is_numeric($str[$i])) {
$num .= $str[$i];
}
}
echo $num; // 11
Though I'd agree a regex or filter_var()
would be more useful in the stated case.
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
Component:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
For more options, examples and browser compatibility visit this link.
They are called the Positional Parameters.
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
This worked perfectly fine for me. Add the annotation @JsonIgnore on the child class where you mention the reference to the parent class.
@ManyToOne
@JoinColumn(name = "ID", nullable = false, updatable = false)
@JsonIgnore
private Member member;
As Brad Wilson states in his answer here:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
Try using :-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy this and this
Here is example of using separated parallel
and for
here. In short it can be used for dynamic allocation of OpenMP thread-private arrays before executing for
cycle in several threads.
It is impossible to do the same initializing in parallel for
case.
UPD: In the question example there is no difference between single pragma and two pragmas. But in practice you can make more thread aware behavior with separated parallel and for directives. Some code for example:
#pragma omp parallel
{
double *data = (double*)malloc(...); // this data is thread private
#pragma omp for
for(1...100) // first parallelized cycle
{
}
#pragma omp single
{} // make some single thread processing
#pragma omp for // second parallelized cycle
for(1...100)
{
}
#pragma omp single
{} // make some single thread processing again
free(data); // free thread private data
}
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
Remove the z-index value.
I would also recommend this approach.
HTML:
<header class="main-header" role="banner">
<img src="mybannerimage.gif" alt="Banner Image"/>
</header>
CSS:
.main-header {
text-align: center;
}
This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.
It should be this:
if (myString!="-1")
{
//Do things
}
Your equals and exclamation are the wrong way round.
It looks like you have a typo on your array, it should read:
int my_array[3][3] = {...
You don't have the _
or the {
.
Also my_array[3][3]
is an invalid location. Since computers begin counting at 0
, you are accessing position 4
. (Arrays are weird like that).
If you want just the last element:
printf("%d\n", my_array[2][2]);
If you want the entire array:
for(int i = 0; i < my_array.length; i++) {
for(int j = 0; j < my_array[i].length; j++)
printf("%d ", my_array[i][j]);
printf("\n");
}
Easier solution will be changing this line
ft.replace(R.id.content_frame, A);
to ft.add(R.id.content_frame, A);
And inside your XML layout please use
android:background="@color/white"
android:clickable="true"
android:focusable="true"
Clickable
means that it can be clicked by a pointer device or be tapped by a touch device.
Focusable
means that it can gain the focus from an input device like a keyboard. Input devices like keyboards cannot decide which view to send its input events to based on the inputs itself, so they send them to the view that has focus.
This means the port is used somewhere else. so, you need to try another one or stop using the old port.
I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:
function test() {_x000D_
document.getElementById("box").classList.toggle("hide");_x000D_
}
_x000D_
.right {_x000D_
float:right;_x000D_
}_x000D_
#box {_x000D_
position:absolute; background:#feb;_x000D_
width:20em; margin-left:-20em; padding:1ex;_x000D_
}_x000D_
#box.hide {_x000D_
display:none;_x000D_
}
_x000D_
<div>_x000D_
<div class="right">_x000D_
<button onclick="test()">box</button>_x000D_
<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</p>_x000D_
</div>
_x000D_
I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).
This is the easiest solution:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
std::vector<std::string> parse(std::string str,std::string delim){
std::vector<std::string> tokens;
char *str_c = strdup(str.c_str());
char* token = NULL;
token = strtok(str_c, delim.c_str());
while (token != NULL) {
tokens.push_back(std::string(token));
token = strtok(NULL, delim.c_str());
}
delete[] str_c;
return tokens;
}
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
a['Names'].str.contains('Mel')
will return an indicator vector of boolean values of size len(BabyDataSet)
Therefore, you can use
mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
print ("There are {m} Mels".format(m=mel_count))
Or any()
, if you don't care how many records match your query
if a['Names'].str.contains('Mel').any():
print ("Mel is there")