If you use SonarScanner CLI with Docker, you may have this error because the SonarScanner container can not access to the Sonar UI container.
Note that you will have the same error with a simple curl from another container:
docker run --rm byrnedo/alpine-curl 127.0.0.1:9000
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused
The solution is to connect the SonarScanner container to the same docker network of your sonar instance, for instance with --network=host
:
docker run --network=host -e SONAR_HOST_URL='http://127.0.0.1:9000' --user="$(id -u):$(id -g)" -v "$PWD:/usr/src" sonarsource/sonar-scanner-cli
(other parameters of this command comes from the SonarScanner CLI documentation)
You are incorrectly using Dependency Injection. The proper way is to have your controllers take the dependencies they need and leave to the dependency injection framework inject the concrete instances:
public class HomeController: Controller
{
private readonly ISettingsManager settingsManager;
public HomeController(ISettingsManager settingsManager)
{
this.settingsManager = settingsManager;
}
public ActionResult Index()
{
// you could use the this.settingsManager here
}
}
As you can see in this example the controller doesn't know anything about the container. And that's how it should be.
All the DI wiring should happen in your Bootstraper. You should never use container.Resolve<>
calls in your code.
As far as your error is concerned, probably the mUnityContainer
you are using inside your controller is not the same instance as the one constructed in your Bootstraper. But since you shouldn't be using any container code in your controllers, this shouldn't be a problem anymore.
When the C# 5 CTP was introduced, you certainly could mark Main with async
... although it was generally not a good idea to do so. I believe this was changed by the release of VS 2013 to become an error.
Unless you've started any other foreground threads, your program will exit when Main
completes, even if it's started some background work.
What are you really trying to do? Note that your GetList()
method really doesn't need to be async at the moment - it's adding an extra layer for no real reason. It's logically equivalent to (but more complicated than):
public Task<List<TvChannel>> GetList()
{
return new GetPrograms().DownloadTvChannels();
}
var marker = [];
for ( var i = 0; i < 6; i++) {
marker[i]='Hello'+i;
}
console.log(marker);
alert(marker);
There is no direct option to export a single request from Postman.
You can create and export collections. Here is a link to help with that.
Regarding the single request thing, you can try a workaround. I tried with the RAW body parameters and it worked.
What you can do is,
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
Check the below links:
Implicit Wait
- It instructs the web driver to wait for some time by poll the DOM. Once you declared implicit wait it will be available for the entire life of web driver instance. By default the value will be 0. If you set a longer default, then the behavior will poll the DOM on a periodic basis depending on the browser/driver implementation.
Explicit Wait
+ ExpectedConditions
- It is the custom one. It will be used if we want the execution to wait for some time until some condition achieved.
Adding <validation validateIntegratedModeConfiguration="false"/>
addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)
Background:
This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.
So, what's the difference? The key difference is how ASP.NET interacts with IIS.
Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.
Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.
Overcoming the error:
Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible httpHandlers
or httpModules
have been added to system.web
. The outcome is the error that you are seeing because validateIntegratedModeConfiguration
defaults true
. Now you have two choices:
httpHandlers
and httpModules
elements from system.web
. There are a couple possible outcomes from this:
httpHandlers
and httpModules
that NuGet packages keep adding to system.web
, hey do what you need to.validateIntegratedModeConfiguration
to false
, but at least you know what you're doing and why it matters.Good reads:
*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.
You can update all outdated packages like so:
brew install `brew outdated`
or
brew outdated | xargs brew install
or
brew upgrade
This is from the brew site..
for upgrading individual formula:
brew install formula-name && brew cleanup formula-name
You can maintain a Map
(for fast lookup) and List
(for order) but a LinkedHashMap
may be the simplest. You can also try a SortedMap
e.g. TreeMap
, which an have any order you specify.
This can be done in a very simple way. Instead of setting the adapter using the built-in values (android.R.layout.simple_list_item_1), create your own xml layout for both TextView and DropDown, and use them. In the TextView layout, define Hint text and Hint color. Last step, create and empty item as the first item in the item array defined in Strings.
<string-array name="professional_qualification_array">
<item></item>
<item>B.Pharm</item>
<item>M.Pharm</item>
<item>PharmD</item>
</string-array>
Create XML layout for Spinner TextView (spnr_qualification.xml)
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:hint="Qualification"
android:textColorHint="@color/light_gray"
android:textColor="@color/blue_black" />
Create XML layout for spinner DropDown.(drpdn_qual.xml)
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:textColor="#FFFFFF"/>
Define spinner in the main XML layout
<Spinner
android:id="@+id/spnQualification"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
/>
And finally in the code, while setting adapter for the spinner, use your custom XML layout.
ArrayAdapter<CharSequence> qual_adapter = ArrayAdapter.createFromResource(this, R.array.professional_qualification_array,R.layout.spnr_qualification);
qual_adapter.setDropDownViewResource(R.layout.drpdn_qual);
spnQualification.setAdapter(qual_adapter)
Try change minimum Android version >= 21 in your build.gradle android{}
This can be easily done by using rd
command with two parameters:
rd <folder> /Q /S
/Q - Quiet mode, do not ask if ok to remove a directory tree with /S
/S - Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
Solved the problem with:
sudo chown -R $USER:$USER /var/www/folder-name
sudo chmod -R 755 /var/www
Grant permissions
In case others have the same issue:
I had a similar error happening. turned out I was wrapping several SQL statements in a transactions, where one of them executed on a linked server (Merge statement in an EXEC(...) AT Server statement). I resolved the issue by opening a separate connection to the linked server, encapsulating that statement in a try...catch then abort the transaction on the original connection in case the catch is tripped.
I'm also extremely late to the party, but I'll leave my version of the answer here for others who may have gotten here, like I did, searching for how to hide something that was placed on the screen with the .place()
function, and not .pack()
neither .grid()
.
In short, you can hide a widget by setting the width and height to zero, like this:
widget.place(anchor="nw", x=0, y=0, width=0, height=0)
To give a bit of context so you can see what my requirement was and how I got here. In my program, I have a window that needs to display several things that I've organized into 2 frames, something like this:
[WINDOW - app]
[FRAME 1 - hMainWndFrame]
[Buttons and other controls (widgets)]
[FRAME 2 - hJTensWndFrame]
[other Buttons and controls (widgets)]
Only one frame needs to be visible at a time, so on application initialisation, i have something like this:
hMainWndFrame = Frame(app, bg="#aababd")
hMainWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)
...
hJTensWndFrame = Frame(app, bg="#aababd")
I'm using .place()
instead of .pack()
or .grid()
because i specifically want to set precise coordinates on the window for each widget. So, when i want to hide the main frame and display the other one (along with all the other controls), all i have to do is call the .place()
function again, on each frame, but specifying zero for width and height for the one i want to hide and the necessary width and height for the one i want to show, such as:
hMainWndFrame.place(anchor="nw", x=0, y=0, width=0, height=0)
hJTensWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)
Now it's true, I only tested this on Frame
s, not on other widgets, but I guess it should work on everything.
A lot of the given answers fail on one or more of:
Here's what I wrote:
static int countMatches(Pattern pattern, String string)
{
Matcher matcher = pattern.matcher(string);
int count = 0;
int pos = 0;
while (matcher.find(pos))
{
count++;
pos = matcher.start() + 1;
}
return count;
}
Example call:
Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2
If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL
flag:
Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2
I put a getchar()
at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar
, getch
, or getc
You can't have a non-keyword argument after a keyword argument.
Make sure you re-arrange your function arguments like so:
def a(len1,til,hgt=len1,col=0):
system('mode con cols='+len1,'lines='+hgt)
system('title',til)
system('color',col)
a(64,"hi",25,"0b")
Given that this question/answer have gained some popularity, I figured it was worth an update.
When this question was originally posted, MySQL had no support for JSON data types and the support in PostgreSQL was in its infancy. Since 5.7, MySQL now supports a JSON data type (in a binary storage format), and PostgreSQL JSONB has matured significantly. Both products provide performant JSON types that can store arbitrary documents, including support for indexing specific keys of the JSON object.
However, I still stand by my original statement that your default preference, when using a relational database, should still be column-per-value. Relational databases are still built on the assumption of that the data within them will be fairly well normalized. The query planner has better optimization information when looking at columns than when looking at keys in a JSON document. Foreign keys can be created between columns (but not between keys in JSON documents). Importantly: if the majority of your schema is volatile enough to justify using JSON, you might want to at least consider if a relational database is the right choice.
That said, few applications are perfectly relational or document-oriented. Most applications have some mix of both. Here are some examples where I personally have found JSON useful in a relational database:
When storing email addresses and phone numbers for a contact, where storing them as values in a JSON array is much easier to manage than multiple separate tables
Saving arbitrary key/value user preferences (where the value can be boolean, textual, or numeric, and you don't want to have separate columns for different data types)
Storing configuration data that has no defined schema (if you're building Zapier, or IFTTT and need to store configuration data for each integration)
I'm sure there are others as well, but these are just a few quick examples.
If you really want to be able to add as many fields as you want with no limitation (other than an arbitrary document size limit), consider a NoSQL solution such as MongoDB.
For relational databases: use one column per value. Putting a JSON blob in a column makes it virtually impossible to query (and painfully slow when you actually find a query that works).
Relational databases take advantage of data types when indexing, and are intended to be implemented with a normalized structure.
As a side note: this isn't to say you should never store JSON in a relational database. If you're adding true metadata, or if your JSON is describing information that does not need to be queried and is only used for display, it may be overkill to create a separate column for all of the data points.
From tutorial here
"It has the extremely useful property that if all of the edges in a graph are unweighted (or the same weight) then the first time a node is visited is the shortest path to that node from the source node"
You can specify the latest version of ruby by looking at https://www.ruby-lang.org/en/downloads/
Fetch the latest version:
curl -sSL https://get.rvm.io | bash -s stable --ruby
Install it:
rvm install 2.2
Use it as default:
rvm use 2.2 --default
Or run the latest command from ruby:
rvm install ruby --latest
rvm use 2.2 --default
You can use a while loop like this:
String text = "Hello";
while (text.length() < 10) { text += "*"; }
System.out.println(text);
Will give you:
Hello*****
Or get the same result with a custom method:
public static String extendString(String text, String symbol, Integer len) {
while (text.length() < len) { text += symbol; }
return text;
}
Then just call:
extendString("Hello", "*", 10)
It may also be a good idea to set a length check to prevent infinite loop.
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).
The previous code was
<p class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></p>
So I have to changed it to
<div class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></div>
It was the easy fix. And the CSS for the above code is
.item {
position: relative;
border: 1px solid green;
height: 30px;
}
.item .name {
position: absolute;
top: 0px;
left: 0px;
}
.item .price {
position: absolute;
right: 0px;
bottom: 0px;
}
So div tag can contain other elements. P should not be forced to do that.
At least in "Docker for Windows" you can see if you are logged in to docker hub over the UI. Just right click the docker icon in the windows notification area:
I just had a similar problem, the DISTINCT keyword works magic:
INSERT INTO Table2(Id, Name) SELECT DISTINCT Id, Name FROM Table1
Here is the simplest way I found,
num <- c(5665,1615,5154,65564,69895646)
num <- sort(num, decreasing = F)
tail(num, 1) # Highest number
head(tail(num, 2),1) # Second Highest number
head(tail(num, 3),1) # Third Highest number
head(tail(num, n),1) # Generl equation for finding nth Highest number
You should be able to do the count on the purch variable:
purch.Count();
e.g.
var purch = from purchase in myBlaContext.purchases
select purchase;
purch.Count();
Disable Deploy on Save in the Project's Properties/Run screen. That's what worked for me finally. Why the hell NetBeans screws this up is beyond me.
Note: I was able to compile the file it was complaining about using right-click in NetBeans. Apparently it wasn't really compiling it when I used Build & Compile since that gave no errors at all. But then after that, the errors just moved to another java class file. I couldn't compile then since it was grayed out. I also tried deleting the build and dist directories in my NetBeans project files but that didn't help either.
Services are singletons, and it is not logical for a scope to be injected in service (which is case indeed, you cannot inject scope in service). You can pass scope as a parameter, but that is also a bad design choice, because you would have scope being edited in multiple places, making it hard for debugging. Code for dealing with scope variables should go in controller, and service calls go to the service.
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
I see this hasn't been answered as final.
I see you have max-width as 100% and width as 600. Flip those.
A simple way also is:
<img src="image.png" style="max-width:600px;width:100%">
I use this often, and then you can control individual images as well, and not have it on all img tags. You could CSS it also like below.
.image600{
width:100%;
max-width:600px;
}
<img src="image.png" class="image600">
For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID )
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql
There is another way to do it, using org.apache.commons.io.IOUtils
to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON
or other object with Gson
, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
You can try to add some time.sleep
calls to your code.
It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.
In order to avoid your code from crashing, try to catch this error with try .. except
around the urllib2 calls.
Using return;
will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach
loop.
Try the following little program:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.stream().forEach(str -> {
if (str.equals("b")) return; // only skips this iteration.
System.out.println(str);
});
}
Output:
a
c
Notice how the return;
is executed for the b
iteration, but c
prints on the following iteration just fine.
The reason the behavior seems unintuitive at first is because we are used to the return
statement interrupting the execution of the whole method. So in this case, we expect the main
method execution as a whole to be halted.
However, what needs to be understood is that a lambda expression, such as:
str -> {
if (str.equals("b")) return;
System.out.println(str);
}
... really needs to be considered as its own distinct "method", completely separate from the main
method, despite it being conveniently located within it. So really, the return
statement only halts the execution of the lambda expression.
The second thing that needs to be understood is that:
stringList.stream().forEach()
... is really just a normal loop under the covers that executes the lambda expression for every iteration.
With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
for(String s : stringList) {
lambdaExpressionEquivalent(s);
}
}
private static void lambdaExpressionEquivalent(String str) {
if (str.equals("b")) {
return;
}
System.out.println(str);
}
With this "less magic" code equivalent, the scope of the return
statement becomes more apparent.
You can take advantage of the HTML prompt to unload mechanism, by specifying no unload handler:
window.onbeforeunload = null;
window.location.replace(URL);
See the notes section of the WindowEventHandlers.onbeforeunload
for more information.
add a textbox and scrollbar
in VB
Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
If e.OldValue > e.NewValue Then
Textbox1.Text = (Textbox1.Text + 1)
Else
Textbox1.Text = (Textbox1.Text - 1)
End If
End Sub
System Preferences => Keyboard => Key Repeat Rate
You 100% can do this on the server side...
Protected Sub Button3_Click(sender As Object, e As System.EventArgs)
MesgBox("Test")
End Sub
Private Sub MesgBox(ByVal sMessage As String)
Dim msg As String
msg = "<script language='javascript'>"
msg += "alert('" & sMessage & "');"
msg += "</script>"
Response.Write(msg)
End Sub
here is actually a whole slew of ways to go about this http://www.sislands.com/coin70/week1/dialogbox.htm
If the goal is to simply insert a record without callbacks or validations, and you would like to do it without resorting to additional gems, adding conditional checks, using RAW SQL, or futzing with your exiting code in any way, consider using a "shadow object" pointing to your existing db table. Like so:
class ImportedPerson < ActiveRecord::Base
self.table_name = 'people'
end
This works with every version of Rails, is threadsafe, and completely eliminates all validations and callbacks with no modifications to your existing code. You can just toss that class declaration in right before your actual import, and you should be good to go. Just remember to use your new class to insert the object, like:
ImportedPerson.new( person_attributes )
sizeof(texts)
on my system evaluated to 96: the number of bytes required for the array and its string instances.
As mentioned elsewhere, the sizeof(texts)/sizeof(texts[0])
would give the value of 3 you were expecting.
Setting these (exactly like I have written) has served me when I needed it:
-moz-opacity: 0.70;
opacity:.70;
filter: alpha(opacity=70);
I use this one.^_^
// Save state
private Parcelable recyclerViewState;
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
// Restore state
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
It is simpler, hope it will help you!
The answer by Leos Literak is correct but now outdated, using one of the troublesome old date-time classes, java.sql.Timestamp
.
it is really a DATETIME in the DB
Nope, it is not. No such data type as DATETIME
in Oracle database.
I was looking for a getDateTime method.
Use java.time classes in JDBC 4.2 and later rather than troublesome legacy classes seen in your Question. In particular, rather than java.sql.TIMESTAMP
, use Instant
class for a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE
.
Contrived code snippet:
if(
JDBCType.valueOf(
myResultSetMetaData.getColumnType( … )
)
.equals( JDBCType.TIMESTAMP_WITH_TIMEZONE )
) {
Instant instant = myResultSet.getObject( … , Instant.class ) ;
}
Oddly enough, the JDBC 4.2 specification does not require support for the two most commonly used java.time classes, Instant
and ZonedDateTime
. So if your JDBC does not support the code seen above, use OffsetDateTime
instead.
OffsetDateTime offsetDateTime = myResultSet.getObject( … , OffsetDateTime.class ) ;
I would like to get the DATETIME column from an Oracle DB Table with JDBC.
According to this doc, there is no column data type DATETIME
in the Oracle database. That terminology seems to be Oracle’s word to refer to all their date-time types as a group.
I do not see the point of your code that detects the type and branches on which data-type. Generally, I think you should be crafting your code explicitly in the context of your particular table and particular business problem. Perhaps this would be useful in some kind of generic framework. If you insist, read on to learn about various types, and to learn about the extremely useful new java.time classes built into Java 8 and later that supplant the classes used in your Question.
valueToInsert = aDate.toString();
You appear to trying to exchange date-time values with your database as text, as String
objects. Don’t.
To exchange date-time values with your database, use date-time objects. Now in Java 8 and later, that means java.time objects, as discussed below.
You may be confusing three sets of date-time related data types:
The SQL standard defines five types:
DATE
TIME WITHOUT TIME ZONE
TIME WITH TIME ZONE
TIMESTAMP WITHOUT TIME ZONE
TIMESTAMP WITH TIME ZONE
DATE
TIME
or TIME WITHOUT TIME ZONE
TIME WITH TIME ZONE
(or TIMETZ
)TIMESTAMP
or TIMESTAMP WITHOUT TIME ZONE
TIMESTAMP WITH TIME ZONE
(or TIMESTAMPTZ
)Many database offer their own date-time related types. The proprietary types vary widely. Some are old, legacy types that should be avoided. Some are believed by the vendor to offer certain benefits; you decide whether to stick with the standard types only or not. Beware: Some proprietary types have a name conflicting with a standard type; I’m looking at you Oracle DATE
.
The Java platform's handles the internal details of date-time differently than does the SQL standard or specific databases. The job of a JDBC driver is to mediate between these differences, to act as a bridge, translating the types and their actual implemented data values as needed. The java.sql.* package is that bridge.
Prior to Java 8, the JDBC spec defined 3 types for date-time work. The first two are hacks as before Version 8, Java lacked any classes to represent a date-only or time-only value.
So that answers your question regarding no "getDateTime" method in the ResultSet interface. That interface offers getter methods for the three bridging data types defined in JDBC:
getDate
for java.sql.DategetTime
for java.sql.TimegetTimestamp
for java.sql.TimestampNote that the first lack any concept of time zone or offset-from-UTC. The last one, java.sql.Timestamp
is always in UTC despite what its toString
method tells you.
You should avoid those poorly-designed JDBC classes listed above. They are supplanted by the java.time types.
java.sql.Date
, use LocalDate
. Suits SQL-standard DATE
type.java.sql.Time
, use LocalTime
. Suits SQL-standard TIME WITHOUT TIME ZONE
type.java.sql.Timestamp
, use Instant
. Suits SQL-standard TIMESTAMP WITH TIME ZONE
type. As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. Use setObject
/getObject
methods.
Insert/update.
myPreparedStatement.setObject( … , instant ) ;
Retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
If you want to see the moment of an Instant
as viewed through the wall-clock time used by the people of a particular region (a time zone) rather than as UTC, adjust by applying a ZoneId
to get a ZonedDateTime
object.
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;
The resulting ZonedDateTime
object is the same moment, the same simultaneous point on the timeline. A new day dawns earlier to the east, so the date and time-of-day will differ. For example, a few minutes after midnight in New Zealand is still “yesterday” in UTC.
You can apply yet another time zone to either the Instant
or ZonedDateTime
to see the same simultaneous moment through yet another wall-clock time used by people in some other region.
ZoneId zMontréal = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtMontréal = zdtAuckland.withZoneSameInstant( zMontréal ) ; // Or, for the same effect: instant.atZone( zMontréal )
So now we have three objects (instant
, zdtAuckland
, zMontréal
) all representing the same moment, same point on the timeline.
To get back to the code in Question about detecting the data-type of the databases: (a) not my field of expertise, (b) I would avoid this as mentioned up top, and (c) if you insist on this, beware that as of Java 8 and later, the java.sql.Types
class is outmoded. That class is now replaced by a proper Java Enum
of JDBCType
that implements the new interface SQLType
. See this Answer to a related Question.
This change is listed in JDBC Maintenance Release 4.2, sections 3 & 4. To quote:
Addition of the java.sql.JDBCType Enum
An Enum used to identify generic SQL Types, called JDBC Types. The intent is to use JDBCType in place of the constants defined in Types.java.
The enum has the same values as the old class, but now provides type-safety.
A note about syntax: In modern Java, you can use a switch
on an Enum
object. So no need to use cascading if-then statements as seen in your Question. The one catch is that the enum object’s name must be used unqualified when switching for some obscure technical reason, so you must do your switch
on TIMESTAMP_WITH_TIMEZONE
rather than the qualified JDBCType.TIMESTAMP_WITH_TIMEZONE
. Use a static import
statement.
So, all that is to say that I guess (I’ve not tried yet) you can do something like the following code example.
final int columnType = myResultSetMetaData.getColumnType( … ) ;
final JDBCType jdbcType = JDBCType.valueOf( columnType ) ;
switch( jdbcType ) {
case DATE : // FYI: Qualified type name `JDBCType.DATE` not allowed in a switch, because of an obscure technical issue. Use a `static import` statement.
…
break ;
case TIMESTAMP_WITH_TIMEZONE :
…
break ;
default :
…
break ;
}
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. This section left intact as history.
Prior to Java 8 (java.time.* package), the date-time classes bundled with java (java.util.Date & Calendar, java.text.SimpleDateFormat) are notoriously troublesome, confusing, and flawed.
A better practice is to take what your JDBC driver gives you and from that create Joda-Time objects, or in Java 8, java.time.* package. Eventually, you should see new JDBC drivers that automatically use the new java.time.* classes. Until then some methods have been added to classes such as java.sql.Timestamp to interject with java.time such as toInstant
and fromInstant
.
As for the latter part of the question, rendering a String… A formatter object should be used to generate a string value.
The old-fashioned way is with java.text.SimpleDateFormat. Not recommended.
Joda-Time provide various built-in formatters, and you may also define your own. But for writing logs or reports as you mentioned, the best choice may be ISO 8601 format. That format happens to be the default used by Joda-Time and java.time.
//java.sql.Timestamp timestamp = resultSet.getTimestamp(i);
// Or, fake it
// long m = DateTime.now().getMillis();
// java.sql.Timestamp timestamp = new java.sql.Timestamp( m );
//DateTime dateTimeUtc = new DateTime( timestamp.getTime(), DateTimeZone.UTC );
DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC ); // Defaults to now, this moment.
// Convert as needed for presentation to user in local time zone.
DateTimeZone timeZone = DateTimeZone.forID("Europe/Paris");
DateTime dateTimeZoned = dateTimeUtc.toDateTime( timeZone );
Dump to console…
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeZoned: " + dateTimeZoned );
When run…
dateTimeUtc: 2014-01-16T22:48:46.840Z
dateTimeZoned: 2014-01-16T23:48:46.840+01:00
Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.
If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.
<form class='frmUpload'>
<input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>
<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>
<div id='imgTwoForJPG'></div>
<script>
window.picUpload = function(frmData) {
console.log("picUpload ran: " + frmData);
var allObjtProperties = '';
for (objProprty in frmData) {
console.log(objProprty + " : " + frmData[objProprty]);
allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};
document.getElementById('allImgProperties').innerHTML = allObjtProperties;
var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");
var img = new Image;
img.src = URL.createObjectURL(frmData);
console.log('img: ' + img);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
var wdthHghtRatio = picHeight/picWidth;
console.log('wdthHghtRatio: ' + wdthHghtRatio);
if (Number(picWidth) > 400) {
var newHeight = Math.round(Number(400) * wdthHghtRatio);
} else {
return false;
};
document.getElementById('cnvsForFormat').height = newHeight;
console.log('width: 400 h: ' + newHeight);
//You must change the width and height settings in order to decrease the image size, but
//it needs to be proportional to the original dimensions.
console.log('This is BEFORE the DRAW IMAGE');
ctx.drawImage(img,0,0, 400, newHeight);
console.log('THIS IS AFTER THE DRAW IMAGE!');
//Even if original image is jpeg, getting data out of the canvas will default to png if not specified
var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
//The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};
</script>
Here is a jsFiddle:
jsFiddle Pick, display, get properties, and Re-size an image file
In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.
A fast and simple solution without any 3rd party includes.
public static String strJoin(String[] aArr, String sSep) {
StringBuilder sbStr = new StringBuilder();
for (int i = 0, il = aArr.length; i < il; i++) {
if (i > 0)
sbStr.append(sSep);
sbStr.append(aArr[i]);
}
return sbStr.toString();
}
in bootstrap 3.0.3 you can do it by modifying the popover class
.popover {
min-width: 200px;
max-width: 400px;
}
I'm having the same warnings. I'm not sure it's a matter of 32 vs 64 bits. Just loaded the new symbols and some problems were solved, but the ones regarding OpenCV still persist. This is an extract of the output with solved vs unsolved issue:
'OpenCV_helloworld.exe': Loaded 'C:\OpenCV2.2\bin\opencv_imgproc220d.dll', Cannot find or open the PDB file
'OpenCV_helloworld.exe': Loaded 'C:\WINDOWS\system32\imm32.dll', Symbols loaded (source information stripped).
The code is exiting 0 in case someone will ask.
The program '[4424] OpenCV_helloworld.exe: Native' has exited with code 0 (0x0).
Basically, you only need junit.jar on the classpath - and here's a quick way to do it:
Make sure you have a source folder (e.g. test
) marked as a Test Root.
Create a test, for example like this:
public class MyClassTest {
@Test
public void testSomething() {
}
}
Since you haven't configured junit.jar (yet), the @Test
annotation will be marked as an error (red), hit f2 to navigate to it.
Hit alt-enter and choose Add junit.jar to the classpath
There, you're done! Right-click on your test and choose Run 'MyClassTest' to run it and see the test results.
Maven Note: Altervatively, if you're using maven, at step 4 you can instead choose the option Add Maven Dependency..., go to the Search for artifact pane, type junit
and take whichever version (e.g. 4.8 or 4.9).
This referes to http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx , http://winrtstoragehelper.codeplex.com/ , Windows 8 app store and .net 4.5
Here is my angle on this:
The async/await language feature makes many things fairly easy but it also introduces a scenario that was rarely encounter before it was so easy to use async calls: reentrance.
This is especially true for event handlers, because for many events you don't have any clue about whats happening after you return from the event handler. One thing that might actually happen is, that the async method you are awaiting in the first event handler, gets called from another event handler still on the same thread.
Here is a real scenario I came across in a windows 8 App store app: My app has two frames: coming into and leaving from a frame I want to load/safe some data to file/storage. OnNavigatedTo/From events are used for the saving and loading. The saving and loading is done by some async utility function (like http://winrtstoragehelper.codeplex.com/). When navigating from frame 1 to frame 2 or in the other direction, the async load and safe operations are called and awaited. The event handlers become async returning void => they cant be awaited.
However, the first file open operation (lets says: inside a save function) of the utility is async too and so the first await returns control to the framework, which sometime later calls the other utility (load) via the second event handler. The load now tries to open the same file and if the file is open by now for the save operation, fails with an ACCESSDENIED exception.
A minimum solution for me is to secure the file access via a using and an AsyncLock.
private static readonly AsyncLock m_lock = new AsyncLock();
...
using (await m_lock.LockAsync())
{
file = await folder.GetFileAsync(fileName);
IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result)
{
return (T)serializer.Deserialize(inStream);
}
}
Please note that his lock basically locks down all file operation for the utility with just one lock, which is unnecessarily strong but works fine for my scenario.
Here is my test project: a windows 8 app store app with some test calls for the original version from http://winrtstoragehelper.codeplex.com/ and my modified version that uses the AsyncLock from Stephen Toub http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx.
May I also suggest this link: http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx
@Override
protected void onPause() {
super.onPause();
System.exit(0);
}
In case you are using quite popular in Spring Boot environment Kubernetes (K8S) or OpenShift, there's a possibility to store and retrieve application properties on runtime. This technique called secrets. In your configuration yaml file for Kubernetes or OpenShift you declare variable and placeholder for it, and on K8S\OpenShift side declare actual value which corresponds to this placeholder. For implementation details, see: K8S: https://kubernetes.io/docs/concepts/configuration/secret/ OpenShift: https://docs.openshift.com/container-platform/3.11/dev_guide/secrets.html
Today, in Office 365, Excel has so called 'array functions'.
The filter
function does exactly what you want. No need to use CTRL+SHIFT+ENTER
anymore, a simple enter
will suffice.
In Office 365, your problem would be simply solved by using:
=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)
I got this exception, when I tried to open Progress Dialog under Cordova Plugin by using below two cases,
new ProgressDialog(this.cordova.getActivity().getParent());
new ProgressDialog(this.cordova.getActivity().getApplicationContext());
Later changed like this,
new ProgressDialog(this.cordova.getActivity());
Its working fine for me.
The full URL is available as request.url
, and the query string is available as request.query_string.decode()
.
Here's an example:
from flask import request
@app.route('/adhoc_test/')
def adhoc_test():
return request.query_string
To access an individual known param passed in the query string, you can use request.args.get('param')
. This is the "right" way to do it, as far as I know.
ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.
Use below date function to get current time in MySQL format/(As requested on question also)
echo date("Y-m-d H:i:s", time());
Couple of things to try...
Comment out the second "Set NewBook" line of code...
You already have an object reference to the workbook.
Do your SaveAs after copying the sheets.
If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.
Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.
If you want to audit a client application name along with each failed login, you can use an Extended Events session.
To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/
CharSequence s = DateFormat.getDateInstance().format("MMMM d, yyyy ");
You need an instance first
If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting
[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread
Try to put ulimit -s unlimited
into /etc/init.d/httpd
. This does not require a server reboot.
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{ // Do stuff here
}
if(stop == true)
or
if(stop)
= is for assignment.
== is for checking condition.
if(stop = true)
It will assign true to stop and evaluates if(true). So it will always execute the code inside if because stop will always being assigned with true.
one solution could be to find a way of pulling the numbers from the string and placing them in a column of just numbers the using the =MEDIAN() function giving the new number column as the range
For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this
to a Groovy method as parameter context
from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."
(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)
Copy servlet-api.jar from your tomcat server lib folder.
Paste it to WEB-INF > lib
folder
Error was solved!!!
I needed this for SQL Server. Here it is:
UPDATE user_account
SET student_education_facility_id = cnt.education_facility_id
from (
SELECT user_account_id,education_facility_id
FROM user_account
WHERE user_type = 'ROLE_TEACHER'
) as cnt
WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id
I think it works with other RDBMSes (please confirm). I like the syntax because it's extensible.
The format I needed was this actually:
UPDATE table1
SET f1 = cnt.computed_column
from (
SELECT id,computed_column --can be any complex subquery
FROM table1
) as cnt
WHERE cnt.id = table1.id
Instead of having two arrays of Strings, have one array of a custom class which contains your two strings.
TextMate is a great editor, and there is a way to replicate some of the functionality in GEdit. Check the article out here: http://rubymm.blogspot.com/2007/08/make-gedit-behave-roughly-like-textmate.html to modify GEdit to behave like TextMate.
None of the answers above worked for me. In the end I figured out it was an configuration error (I used the android SDK and not Java SDK for compilation).
Got to [Right Click on Project] --> Open Module Settings --> Module --> [Dependendecies] and make sure you have configured and selected the Java SDK (not the android java sdk)
It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.
There is no documented /prompt parameter for SETX as there is for SET.
If you need to prompt for an environment variable that will survive reboots, you can use SETX to store it.
A variable created by SETX won't be usable until you restart the command prompt. Neatly, however, you can SETX a variable that has already been SET, even if it has the same name.
This works for me in Windows 8.1 Pro:
set /p UserInfo= "What is your name? "
setx UserInfo "%UserInfo%"
(The quotation marks around the existing variable are necessary.)
This procedure allows you to use the temporary SET-created variable during the current session and will allow you to reuse the SETX-created variable upon reboot of the computer or restart of the CMD prompt.
(Edited to format code paragraphs properly.)
You missed the closing tag for the input fields, and you can choose any one of the events, ex: onload, onclick etc.
(a) Onload event:
<script type="text/javascript">
$(document).ready(function(){
$('#frm1').submit();
});
</script>
(b) Onclick Event:
<form name="frm1" id="frm1" action="../somePage" method="post">
Please Waite...
<input type="hidden" name="uname" id="uname" value=<?php echo $uname;?> />
<input type="hidden" name="price" id="price" value=<?php echo $price;?> />
<input type="text" name="submit" id="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').click(function(){
$('#frm1').submit();
});
</script>
You could host password in a repository and then just hide the page behind hidden address, that is derived from that password. This is not a very secure way, but it is simple.
$request->validate([
'phone' => 'numeric|required',
'body' => 'required',
]);
In Access, you will probably find a Join is quicker unless your tables are very small:
SELECT DISTINCT Table1.Column1
FROM Table1
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1
WHERE Table2.Column1 Is Null
This will exclude from the list all records with a match in Table2.
If you are using Java 8 then you can do this easier with CompletableFuture and CompletableFuture.allOf, which applies the callback only after all supplied CompletableFutures are done.
// Waits for *all* futures to complete and returns a list of results.
// If *any* future completes exceptionally then the resulting future will also complete exceptionally.
public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);
return CompletableFuture.allOf(cfs)
.thenApply(ignored -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList())
);
}
Here is the complete code, import pfx, add iis website, add ssl binding:
$SiteName = "MySite"
$HostName = "localhost"
$CertificatePassword = '1234'
$SiteFolder = Join-Path -Path 'C:\inetpub\wwwroot' -ChildPath $SiteName
$certPath = 'c:\cert.pfx'
Write-Host 'Import pfx certificate' $certPath
$certRootStore = “LocalMachine”
$certStore = "My"
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath,$CertificatePassword,"Exportable,PersistKeySet")
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$store.Open('ReadWrite')
$store.Add($pfx)
$store.Close()
$certThumbprint = $pfx.Thumbprint
Write-Host 'Add website' $SiteName
New-WebSite -Name $SiteName -PhysicalPath $SiteFolder -Force
$IISSite = "IIS:\Sites\$SiteName"
Set-ItemProperty $IISSite -name Bindings -value @{protocol="https";bindingInformation="*:443:$HostName"}
if($applicationPool) { Set-ItemProperty $IISSite -name ApplicationPool -value $IISApplicationPool }
Write-Host 'Bind certificate with Thumbprint' $certThumbprint
$obj = get-webconfiguration "//sites/site[@name='$SiteName']"
$binding = $obj.bindings.Collection[0]
$method = $binding.Methods["AddSslCertificate"]
$methodInstance = $method.CreateInstance()
$methodInstance.Input.SetAttributeValue("certificateHash", $certThumbprint)
$methodInstance.Input.SetAttributeValue("certificateStoreName", $certStore)
$methodInstance.Execute()
For me, works this way: mvn -f /path/to/pom.xml [goals]
You can redirect stdout to /dev/null.
yum install nano > /dev/null
Or you can redirect both stdout and stderr,
yum install nano &> /dev/null
.
But if the program has a quiet option, that's even better.
Yes. In fact you should. If you're wondering if it creates a segmentation fault, it doesn't.
You should check out heroku_san, it solves this problem quite nicely.
For example, you could:
git checkout BRANCH
rake qa deploy
It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:
git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates
And of course you can make simpler rake tasks if you do something frequently.
The good part is we can make basic maths directly:
let nuts = 7_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h2>You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it, get ${nuts + nuts} nuts!!_x000D_
_x000D_
`
_x000D_
<div id="more"></div>
_x000D_
It became really useful in a factory function:
function nuts(it){_x000D_
return `_x000D_
You have ${it} nuts! <br>_x000D_
Cosinus of your nuts: ${Math.cos(it)} <br>_x000D_
Triple nuts: ${3 * it} <br>_x000D_
Your nuts encoded in BASE64:<br> ${btoa(it)}_x000D_
`_x000D_
}_x000D_
_x000D_
nut.oninput = (function(){_x000D_
out.innerHTML = nuts(nut.value)_x000D_
})
_x000D_
<h3>NUTS CALCULATOR_x000D_
<input type="number" id="nut">_x000D_
_x000D_
<div id="out"></div>
_x000D_
Although this question is being asked for 5 years ago. I just want to share my answer. Below is how I detect whether someone is clicked cancel and OK button in input box:
Public sName As String
Sub FillName()
sName = InputBox("Who is your name?")
' User is clicked cancel button
If StrPtr(sName) = False Then
MsgBox ("Please fill your name!")
Exit Sub
End If
' User is clicked OK button whether entering any data or without entering any datas
If sName = "" Then
' If sName string is empty
MsgBox ("Please fill your name!")
Else
' When sName string is filled
MsgBox ("Welcome " & sName & " and nice see you!")
End If
End Sub
It took far too long but I finally found this document on Migrating MSBuild-Integrated solutions to Automatic Package Restore and I was able to resolve the issue using the methods described here.
'.nuget'
solution directory along from the solutionnuget.targets
from your .csproj
or .vbproj
files. Though not officially supported, the document links to a PowerShell script if you have a lot of projects which need to be cleaned up. I manually edited mine by hand so I can't give any feedback regarding my experience with it.When editing your files by hand, here's what you'll be looking for:
Solution File (.sln)
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F4AEBB8B-A367-424E-8B14-F611C9667A85}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Project File (.csproj / .vbproj)
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
fscanf
- "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned."
So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF
.
You should check for EOF when you call fscanf
, not check the array slot for EOF.
Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:
var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;
db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}})
You can also use NumberLong.
You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)
$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
//Process your response
$("#ajaxLoader").hide();
});
If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-
$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
Using blockUI is similar for example with mark up like:-
<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
<p id="result"></p>
</div>
<div id="ajaxLoader" style="display:none">
<h2>Please wait</h2>
<p>I'm getting my AJAX on!</p>
</div>
And using jQuery:-
$(function() {
$("#jsonLink").click(function(e) {
$.post(this.href, function(result) {
$("#resultContainer").fadeIn();
$("#result").text(result.Answer);
}, "json");
return false;
});
$("#ajaxLoader").ajaxStart(function() {
$.blockUI({ message: $("#ajaxLoader") });
})
.ajaxStop(function() {
$.unblockUI();
});
});
Or use the FileInfo as suggested in In C# check that filename is possibly valid (not that it exists).
Run jupyter kernelspec list
to get the paths of all your kernels.
Then simply uninstall your unwanted-kernel
jupyter kernelspec uninstall unwanted-kernel
Old answer
Delete the folder corresponding to the kernel you want to remove.
The docs has a list of the common paths for kernels to be stored in: http://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.
Format(Now(), "yyyy-MM-dd hh:mm:ss")
You may want to be using the find
options :
http://docs.meteor.com/api/collections.html#Mongo-Collection-find
db.collection.find({}, {sort: {createdAt: -1}, skip:2, limit: 18}).fetch();
The reason it is throwing that exception is because you have the argument rb
, which opens the file in binary mode. Change that to r
, which will by default open the file in text mode.
Your code:
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
New code:
import csv
ifile = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
print (row)
Any time there's arguments over performance, you just need to write a small test so that you can use quantitative results to support your case.
Use the StopWatch class and repeat something a few million times, for accuracy. (This might be hard without a for loop):
using System.Diagnostics;
//...
Stopwatch sw = new Stopwatch()
sw.Start()
for(int i = 0; i < 1000000;i ++)
{
//do whatever it is you need to time
}
sw.Stop();
//print out sw.ElapsedMilliseconds
Fingers crossed the results of this show that the difference is negligible, and you might as well just do whatever results in the most maintainable code
Visit https://www.tutorialspoint.com/python/string_join.htm
s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))
ab cd ef
s="."
print(s.join(seq))
ab.cd.ef
when(
fooDao.getBar(
any(Bazoo.class)
)
).thenReturn(myFoo);
or (to avoid null
s):
when(
fooDao.getBar(
(Bazoo)notNull()
)
).thenReturn(myFoo);
Don't forget to import matchers (many others are available):
For Mockito 2.1.0 and newer:
import static org.mockito.ArgumentMatchers.*;
For older versions:
import static org.mockito.Matchers.*;
Had the same issue. It was a problem with udev rules. Tried a few of the rules mentioned above but didnot fix the issue. Found a set of rules here, https://github.com/M0Rf30/android-udev-rules. Followed the guide there and, voila, fixed.
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
A many to many relationship normally has a linking table. Consider this "link" as an entity in its own right and give it a unique id, then send that id in the delete request.
You would have a a REST resource URL like /user/role to handle operations on a user-role "link" entity.
You could utilize jQuery.filter() function to return elements from a subset of the matching elements.
var names = [_x000D_
{ name : "Joe", age:20, email: "[email protected]"},_x000D_
{ name : "Mike", age:50, email: "[email protected]"},_x000D_
{ name : "Joe", age:45, email: "[email protected]"}_x000D_
];_x000D_
_x000D_
_x000D_
var filteredNames = $(names).filter(function( idx ) {_x000D_
return names[idx].name === "Joe" && names[idx].age < 30;_x000D_
}); _x000D_
_x000D_
$(filteredNames).each(function(){_x000D_
$('#output').append(this.name);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="output"/>
_x000D_
Device: iPad Mini
OS: iOS 9 Beta 3
App downloaded from: Hockey App
Provisioning profile with Trust issues: Enterprise
In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.
Here are the steps that I followed:
That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)
You can get the full download here: http://download.microsoft.com/download/8/3/a/83aad8f9-38ba-4503-b3cd-ba28c360c27b/ENU/vcsetup.exe
Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.
You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?
The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).
So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:
$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('"$user_id.$password."')
)";
(I am assuming that you've properly escaped all those strings earlier in your code)
You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.
w.strip(',.').lower()
You can instruct curl to use the HTTP HEAD method via CURLOPT_NOBODY.
More or less
$ch = curl_init("http://www.example.com/favicon.ico");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);
Anyway, you only save the cost of the HTTP transfer, not the TCP connection establishment and closing. And being favicons small, you might not see much improvement.
Caching the result locally seems a good idea if it turns out to be too slow. HEAD checks the time of the file, and returns it in the headers. You can do like browsers and get the CURLINFO_FILETIME of the icon. In your cache you can store the URL => [ favicon, timestamp ]. You can then compare the timestamp and reload the favicon.
'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
Property Get Path()
Dim sTmp
If IsObject(Server) Then
'Classic ASP
Path = Server.MapPath("../")
ElseIf IsObject(WScript) Then
'Windows Scripting Host
Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
ElseIf IsObject(window) Then
'Internet Explorer HTML Application (HTA)
sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
End If
End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path
I did some searching, and I couldn't find anything concrete for a "on keyboard shown" or "on keyboard dismissed". See the official list of supported events. Also see Technical Note TN2262 for iPad. As you probably already know, there is a body event onorientationchange
you can wire up to detect landscape/portrait.
Similarly, but a wild guess... have you tried detecting resize? Viewport changes may trigger that event indirectly from the keyboard being shown / hidden.
window.addEventListener('resize', function() { alert(window.innerHeight); });
Which would simply alert the new height on any resize event....
While you cannot record tests using the Selenium IDE in Chrome (or any other browser other than FF), you can run them (from the IDE) in Chrome, IE and other browsers using the Webdriver playback feature of Selenium 2 IDE. Tests will need to be recorded and launched from FF - Chrome will launch before the first step of the test is executed. Instructions for setup and test execution are here and here. You will need to install Selenium 2 IDE (if you haven't already done so) and the Chrome Webdriver Server executable - both are available for download on the Selenium HQ website.
NOTE: If the above meets your needs, you may also want to consider just converting all your tests to Selenium Webdriver (which means they would be all code and no longer run from the Selenium IDE). This would be a better solution from the perspective of test maintenance and simplicity of execution. The Selenium documentation (on the Selenium website) has more information on the process to convert Selenium IDE tests to Webdriver.
From a performance point of view, I guess that a direct SQL query using the EXISTS command would be appropriate. See here for how to execute SQL directly in Entity Framework: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx
visibility:hidden
preserves the space; display:none
doesn't.
I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
It's not super clear above, but if you are receiving the request in PHP you can use:
$params = json_decode(file_get_contents('php://input'),true);
To access an array in PHP from an AngularJS POST.
Cardinality refers to the uniqueness of data contained in a column. If a column has a lot of duplicate data (e.g. a column that stores either "true" or "false"), it has low cardinality, but if the values are highly unique (e.g. Social Security numbers), it has high cardinality.
I had this same issue recently and none of the other fixes worked. I got it to show finally by switching to the "Services" tab, right-clicking on "Apache Tomcat or TomEE" and clicking "Restart".
If you get a model instance from the database, then calling the save method will always update that instance. For example:
t = TemperatureData.objects.get(id=1)
t.value = 999 # change field
t.save() # this will update only
If your goal is prevent any INSERTs, then you can override the save
method, test if the primary key exists and raise an exception. See the following for more detail:
NSMutableAttributedString *text = [self.myUILabel.attributedText mutableCopy];
[text addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, text.length)];
self.myUILabel.attributedText = text;
Exception clearly indicates the problem.
CompteDAOHib: No default constructor found
For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib
.
try this its work fine
document.getElementById('fileUpload').parentNode.innerHTML = document.getElementById('fileUpload').parentNode.innerHTML;
My version of the accepted answer as a function using DATEPART
, so I don't have to do a string comparison on the line with
DATENAME(dw, @StartDate) = 'Sunday'
Anyway, here's my business datediff function
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION BDATEDIFF
(
@startdate as DATETIME,
@enddate as DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @res int
SET @res = (DATEDIFF(dd, @startdate, @enddate) + 1)
-(DATEDIFF(wk, @startdate, @enddate) * 2)
-(CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END)
-(CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END)
RETURN @res
END
GO
Use this code it will help you.
<script>
InitializeDate();
</script>
<input type="text" id="txtFromDate" class="datepicker calendar-icon" placeholder="From Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
<input type="text" id="txtToDate" class="datepicker calendar-icon" placeholder="To Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
function InitializeDate() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
var ToDate = mm + '/' + dd + '/' + yyyy;
var FromDate = mm + '/01/' + yyyy;
$('#txtToDate').datepicker('setDate', ToDate);
$('#txtFromDate').datepicker('setDate', FromDate);
}
If this is all the object is going to store, then best literal would be
var top_brands = {
'Adidas' : 100,
'Nike' : 50
};
Then all you need is a for...in
loop.
for (var key in top_brands){
console.log(key, top_brands[key]);
}
from eclipse, you can select on the project, right click->team->upgrade
driver.close
and driver.quit
are two different methods for closing the browser session in Selenium WebDriver. Understanding both of them and knowing when to use each method is important in your test execution. Therefore, I have tried to shed some light on both of these methods.
driver.close
- This method closes the browser window on which the focus is set. Despite the familiar name for this method, WebDriver
does not implement the AutoCloseable
interface.
driver.quit
– This method basically calls driver.dispose
a now internal method which in turn closes all of the browser windows and ends the WebDriver session gracefully.
driver.dispose
- As mentioned previously, is an internal method of WebDriver which has been silently dropped according to another answer - Verification needed. This method really doesn't have a use-case in a normal test workflow as either of the previous methods should work for most use cases.
Explanation use case:
You should use driver.quit
whenever you want to end the program. It will close all opened browser windows and terminates the WebDriver session. If you do not use driver.quit
at the end of the program, the WebDriver session will not close properly and files would not be cleared from memory. This may result in memory leak errors.
The above explanation should explain the difference between driver.close
and driver.quit
methods in WebDriver. I hope you find it useful.
The following website has some good tips on selenium testing : Link
This checks the type of input arguments upon calling the function:
def func(inp1:int=0,inp2:str="*"):
for item in func.__annotations__.keys():
assert isinstance(locals()[item],func.__annotations__[item])
return (something)
first=7
second="$"
print(func(first,second))
Also check with second=9
(it must give assertion error)
You need to use .val()
for textarea as it is an element and not a wrapper. Try
$('textarea#message').val()
PROMPT> gem uninstall cocoapods
Select gem to uninstall:
1. cocoapods-0.32.1
2. cocoapods-0.33.1
3. cocoapods-0.36.0.beta.2
4. cocoapods-0.38.2
5. cocoapods-0.39.0
6. cocoapods-1.0.0
7. All versions
> 6
Successfully uninstalled cocoapods-1.0.0
PROMPT> gem install cocoapods -v 0.39.0
Successfully installed cocoapods-0.39.0
Parsing documentation for cocoapods-0.39.0
Done installing documentation for cocoapods after 1 seconds
1 gem installed
PROMPT> pod --version
0.39.0
PROMPT>
To update and/or enhance the answer by @Hans Passant I would separate the retrieval of the property into an extension method. This has the added benefit of removing the nasty magic string in the method GetProperty()
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
Your test is then reduced to two lines
var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));
Run Wamp services before Skype
Quit Skype >>> Run WAMP >>> Run Skype
As for the workaround (without using non-portable -P
), you can temporary replace a new-line character with the different one and change it back, e.g.:
grep -o "_foo_" <(paste -sd_ file) | tr -d '_'
Basically it's looking for exact match _foo_
where _
means \n
(so __
= \n\n
). You don't have to translate it back by tr '_' '\n'
, as each pattern would be printed in the new line anyway, so removing _
is enough.
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
You forgot to return the map. this code will resolve the issue.
In a webpage where I wanted a in image to scale with browser size change and remain at the top, next to a fixed div, all I had to do was use a single CSS line: overflow:hidden;
and it did the trick. The image scales perfectly.
What is especially nice is that this is pure css and will work even if Javascript is turned off.
CSS:
#ImageContainerDiv {
overflow: hidden;
}
HTML:
<div id="ImageContainerDiv">
<a href="URL goes here" target="_blank">
<img src="MapName.png" alt="Click to load map" />
</a>
</div>
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
Make sure you own root directory for npm so you don't get any errors when you install global packages without using sudo.
procedures:- in root directory
sudo chown -R yourUsername /usr/local/lib/node_modules
sudo chown -R yourUsername /usr/local/bin/
sudo chown -R yourUsername /usr/local/share/
So now with
npm i npm -g
you get no errors and no use of sudo here. but if you still get errors confirm node_modules is owned again
/usr/local/lib/
and make sure you own everything
ls -la
npm i -g nodemon
will work!
Its another way to declare the constructor. You can also use the class name, for ex:
class Cat
{
function Cat()
{
echo 'meow';
}
}
and
class Cat
{
function __construct()
{
echo 'meow';
}
}
Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:
$cat = new Cat();
Try this one: https://github.com/tantau-horia/jquery-SuperCookie
Quick Usage:
create - create cookie
check - check existance
verify - verify cookie value if JSON
check_index - verify if index exists in JSON
read_values - read cookie value as string
read_JSON - read cookie value as JSON object
read_value - read value of index stored in JSON object
replace_value - replace value from a specified index stored in JSON object
remove_value - remove value and index stored in JSON object
Just use:
$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");
Git 2.6 (Sept/Oct 2015) will add the option --name-only
to simplify the output of a git config -l
:
See commit a92330d, commit f225987, commit 9f1429d (20 Aug 2015) by Jeff King (peff
).
See commit ebca2d4 (20 Aug 2015), and commit 905f203, commit 578625f (10 Aug 2015) by SZEDER Gábor (szeder
).
(Merged by Junio C Hamano -- gitster
-- in commit fc9dfda, 31 Aug 2015)
config
: add '--name-only
' option to list only variable names'
git config
' can only show values or name-value pairs, so if a shell script needs the names of set config variables it has to run 'git config --list
' or '--get-regexp
' and parse the output to separate config variable names from their values.
However, such a parsing can't cope with multi-line values.Though '
git config
' can produce null-terminated output for newline-safe parsing, that's of no use in such a case, because shells can't cope with null characters.Even our own bash completion script suffers from these issues.
Help the completion script, and shell scripts in general, by introducing the '
--name-only
' option to modify the output of '--list
' and '--get-regexp
' to list only the names of config variables, so they don't have to perform error-prone post processing to separate variable names from their values anymore.
I'll add Android docs link to other answers.
https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape
It describes all attributes of the Shape Drawable and stroke
among them to set the border.
Example:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke android:width="1dp" android:color="#F00"/>
<solid android:color="#0000"/>
</shape>
Red border with transparent background.
The code of @ThePracticalOne is great for showing the usage except for one thing:
Somtimes the output would be incomplete.(session.recv_ready()
turns true after the if session.recv_ready():
while session.recv_stderr_ready()
and session.exit_status_ready()
turned true before entering next loop)
so my thinking is to retrieving the data when it is ready to exit the session.
while True:
if session.exit_status_ready():
while True:
while True:
print "try to recv stdout..."
ret = session.recv(nbytes)
if len(ret) == 0:
break
stdout_data.append(ret)
while True:
print "try to recv stderr..."
ret = session.recv_stderr(nbytes)
if len(ret) == 0:
break
stderr_data.append(ret)
break
I drilled down the formation of the drop down list instead of using @Html.DropDownList()
. This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:
<select id="NewsCategoriesID" name="NewsCategoriesID">
@foreach (SelectListItem option in ViewBag.NewsCategoriesID)
{
<option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>
}
</select>
Examples of all non-POD cases with static_assert
from C++11 to C++17 and POD effects
std::is_pod
was added in C++11, so let's consider that standard onwards for now.
std::is_pod
will be removed from C++20 as mentioned at https://stackoverflow.com/a/48435532/895245 , let's update this as support arrives for the replacements.
POD restrictions have become more and more relaxed as the standard evolved, I aim to cover all relaxations in the example through ifdefs.
libstdc++ has at tiny bit of testing at: https://github.com/gcc-mirror/gcc/blob/gcc-8_2_0-release/libstdc%2B%2B-v3/testsuite/20_util/is_pod/value.cc but it just too little. Maintainers: please merge this if you read this post. I'm lazy to check out all the C++ testsuite projects mentioned at: https://softwareengineering.stackexchange.com/questions/199708/is-there-a-compliance-test-for-c-compilers
#include <type_traits>
#include <array>
#include <vector>
int main() {
#if __cplusplus >= 201103L
// # Not POD
//
// Non-POD examples. Let's just walk all non-recursive non-POD branches of cppreference.
{
// Non-trivial implies non-POD.
// https://en.cppreference.com/w/cpp/named_req/TrivialType
{
// Has one or more default constructors, all of which are either
// trivial or deleted, and at least one of which is not deleted.
{
// Not trivial because we removed the default constructor
// by using our own custom non-default constructor.
{
struct C {
C(int) {}
};
static_assert(std::is_trivially_copyable<C>(), "");
static_assert(!std::is_trivial<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// No, this is not a default trivial constructor either:
// https://en.cppreference.com/w/cpp/language/default_constructor
//
// The constructor is not user-provided (i.e., is implicitly-defined or
// defaulted on its first declaration)
{
struct C {
C() {}
};
static_assert(std::is_trivially_copyable<C>(), "");
static_assert(!std::is_trivial<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
}
// Not trivial because not trivially copyable.
{
struct C {
C(C&) {}
};
static_assert(!std::is_trivially_copyable<C>(), "");
static_assert(!std::is_trivial<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
}
// Non-standard layout implies non-POD.
// https://en.cppreference.com/w/cpp/named_req/StandardLayoutType
{
// Non static members with different access control.
{
// i is public and j is private.
{
struct C {
public:
int i;
private:
int j;
};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// These have the same access control.
{
struct C {
private:
int i;
int j;
};
static_assert(std::is_standard_layout<C>(), "");
static_assert(std::is_pod<C>(), "");
struct D {
public:
int i;
int j;
};
static_assert(std::is_standard_layout<D>(), "");
static_assert(std::is_pod<D>(), "");
}
}
// Virtual function.
{
struct C {
virtual void f() = 0;
};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// Non-static member that is reference.
{
struct C {
int &i;
};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// Neither:
//
// - has no base classes with non-static data members, or
// - has no non-static data members in the most derived class
// and at most one base class with non-static data members
{
// Non POD because has two base classes with non-static data members.
{
struct Base1 {
int i;
};
struct Base2 {
int j;
};
struct C : Base1, Base2 {};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// POD: has just one base class with non-static member.
{
struct Base1 {
int i;
};
struct C : Base1 {};
static_assert(std::is_standard_layout<C>(), "");
static_assert(std::is_pod<C>(), "");
}
// Just one base class with non-static member: Base1, Base2 has none.
{
struct Base1 {
int i;
};
struct Base2 {};
struct C : Base1, Base2 {};
static_assert(std::is_standard_layout<C>(), "");
static_assert(std::is_pod<C>(), "");
}
}
// Base classes of the same type as the first non-static data member.
// TODO failing on GCC 8.1 -std=c++11, 14 and 17.
{
struct C {};
struct D : C {
C c;
};
//static_assert(!std::is_standard_layout<C>(), "");
//static_assert(!std::is_pod<C>(), "");
};
// C++14 standard layout new rules, yay!
{
// Has two (possibly indirect) base class subobjects of the same type.
// Here C has two base classes which are indirectly "Base".
//
// TODO failing on GCC 8.1 -std=c++11, 14 and 17.
// even though the example was copy pasted from cppreference.
{
struct Q {};
struct S : Q { };
struct T : Q { };
struct U : S, T { }; // not a standard-layout class: two base class subobjects of type Q
//static_assert(!std::is_standard_layout<U>(), "");
//static_assert(!std::is_pod<U>(), "");
}
// Has all non-static data members and bit-fields declared in the same class
// (either all in the derived or all in some base).
{
struct Base { int i; };
struct Middle : Base {};
struct C : Middle { int j; };
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// None of the base class subobjects has the same type as
// for non-union types, as the first non-static data member
//
// TODO: similar to the C++11 for which we could not make a proper example,
// but with recursivity added.
// TODO come up with an example that is POD in C++14 but not in C++11.
}
}
}
// # POD
//
// POD examples. Everything that does not fall neatly in the non-POD examples.
{
// Can't get more POD than this.
{
struct C {};
static_assert(std::is_pod<C>(), "");
static_assert(std::is_pod<int>(), "");
}
// Array of POD is POD.
{
struct C {};
static_assert(std::is_pod<C>(), "");
static_assert(std::is_pod<C[]>(), "");
}
// Private member: became POD in C++11
// https://stackoverflow.com/questions/4762788/can-a-class-with-all-private-members-be-a-pod-class/4762944#4762944
{
struct C {
private:
int i;
};
#if __cplusplus >= 201103L
static_assert(std::is_pod<C>(), "");
#else
static_assert(!std::is_pod<C>(), "");
#endif
}
// Most standard library containers are not POD because they are not trivial,
// which can be seen directly from their interface definition in the standard.
// https://stackoverflow.com/questions/27165436/pod-implications-for-a-struct-which-holds-an-standard-library-container
{
static_assert(!std::is_pod<std::vector<int>>(), "");
static_assert(!std::is_trivially_copyable<std::vector<int>>(), "");
// Some might be though:
// https://stackoverflow.com/questions/3674247/is-stdarrayt-s-guaranteed-to-be-pod-if-t-is-pod
static_assert(std::is_pod<std::array<int, 1>>(), "");
}
}
// # POD effects
//
// Now let's verify what effects does PODness have.
//
// Note that this is not easy to do automatically, since many of the
// failures are undefined behaviour.
//
// A good initial list can be found at:
// https://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special/4178176#4178176
{
struct Pod {
uint32_t i;
uint64_t j;
};
static_assert(std::is_pod<Pod>(), "");
struct NotPod {
NotPod(uint32_t i, uint64_t j) : i(i), j(j) {}
uint32_t i;
uint64_t j;
};
static_assert(!std::is_pod<NotPod>(), "");
// __attribute__((packed)) only works for POD, and is ignored for non-POD, and emits a warning
// https://stackoverflow.com/questions/35152877/ignoring-packed-attribute-because-of-unpacked-non-pod-field/52986680#52986680
{
struct C {
int i;
};
struct D : C {
int j;
};
struct E {
D d;
} /*__attribute__((packed))*/;
static_assert(std::is_pod<C>(), "");
static_assert(!std::is_pod<D>(), "");
static_assert(!std::is_pod<E>(), "");
}
}
#endif
}
Tested with:
for std in 11 14 17; do echo $std; g++-8 -Wall -Werror -Wextra -pedantic -std=c++$std pod.cpp; done
on Ubuntu 18.04, GCC 8.2.0.
We can check it by using !/[^a-zA-Z]/.test(e)
Just run snippet and check.
function handleValueChange() {
if (!/[^a-zA-Z]/.test(document.getElementById('textbox_id').value)) {
var x = document.getElementById('result');
x.innerHTML = 'String does not contain number';
} else {
var x = document.getElementById('result');
x.innerHTML = 'String does contains number';
}
}
_x000D_
input {
padding: 5px;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
_x000D_
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
I'm a google apps for business subscriber and I spend the last couple hours just dealing with this, even after having all the correct settings (smtp, port, enableSSL, etc). Here's what worked for me and the web sites that were throwing the 5.5.1 error when trying to send an email:
After doing this my email forms from the website were working again. Good luck!
I don't know if this applies in this case, but sometimes the file got deleted for unknown reasons, copying it again into the respective folder should resolve the problem.
awk -F "," '{print $0}' user.csv | sort -nk3 -t ','
This should work
Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):
function winHasJSON(){
json_data = JSON.stringify(obj);
// ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
winHasJSON();
} else {
$.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}
With jQuery it will be something like that:
$(document).ready(function() {
$('#yourDiv').on('mousedown', function(e) {
e.preventDefault();
});
});
In my case I wanted to disable the user from drop text in the inputs so I used "drop" instead "mousedown".
$(document).ready(function() {
$('input').on('drop', function(event) {
event.preventDefault();
});
});
Instead event.preventDefault() you can return false. Here's the difference.
And the code:
$(document).ready(function() {
$('input').on('drop', function() {
return false;
});
});
try this block of code if your .xml file has been generated somewhere in disk and if you have used List<T>
:
//deserialization
XmlSerializer xmlser = new XmlSerializer(typeof(List<Item>));
StreamReader srdr = new StreamReader(@"C:\serialize.xml");
List<Item> p = (List<Item>)xmlser.Deserialize(srdr);
srdr.Close();`
Note: C:\serialize.xml
is my .xml file's path. You can change it for your needs.
The following snippet will attempt to execute the "doStuff" function 2 seconds after the mouseDown event occurs in document.body. If the user lifts up the button, the mouseUp event will occur and cancel the delayed execution.
I'd advise using some method for cross-browser event attachment - setting the mousedown and mouseup properties explicitly was done to simplify the example.
function doStuff() {
// does something when mouse is down in body for longer than 2 seconds
}
var mousedownTimeout;
document.body.onmousedown = function() {
mousedownTimeout = window.setTimeout(doStuff, 2000);
}
document.body.onmouseup = function() {
window.clearTimeout(mousedownTimeout);
}
from __future__ import print_function
import os
from pil import Image
files = [
'1.png',
'2.png',
'3.png',
'4.png']
result = Image.new("RGB", (800, 800))
for index, file in enumerate(files):
path = os.path.expanduser(file)
img = Image.open(path)
img.thumbnail((400, 400), Image.ANTIALIAS)
x = index // 2 * 400
y = index % 2 * 400
w, h = img.size
result.paste(img, (x, y, x + w, y + h))
result.save(os.path.expanduser('output.jpg'))
If your requirements are to have no duplicates, you should be using a HashSet.
HashSet.Add will return false when the item already exists (if that even matters to you).
You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice
(GetHashCode
& Equals
).
FLAG_ACTIVITY_NEW_TASK is the problem here which initiates a new task .Just remove it & you are done.
Well I recommend you to read what every Flag does before working with them
Read this & Intent Flags here
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
Thanks for all the answers everyone! I have found a solution, turns out I didn't provide enough code in my question.
The problem was NOT with the click() function after all, but instead related to cas authentication used with my project. In Selenium IDE my login test executed a "open" command to the following location,
/cas/login?service=https%1F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security
That worked. I exported the test to Selenium webdriver which naturally preserved that location. The command in Selenium Webdriver was,
driver.get(baseUrl + "/cas/login?service=https%1A%2F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security");
For reasons I have yet to understand the above failed. When I changed it to,
driver.get(baseUrl + "MOREURL/");
The click command suddenly started to work... I will edit this answer if I can figure out why exactly this is.
Note: I obscured the URLs used above to protect my company's product.
Another workaround for those who don't need the entire shebang: use the switch
-DBOOST_ERROR_CODE_HEADER_ONLY
.
If you use CMake, it's add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)
.
There are 3 ways to do this:
Right-click on the Chart and click Select Data then edit the series names directly as shown below.
You can either specify the values directly e.g. Series 1
or specify a range e.g. =A2
Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically.
Similarly you can define the series names dynamically using VBA. A simple example below:
ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""
This will redefine the first series name. Just change the index from (1)
to e.g. (2)
and so on to change the following series names. What does the VBA above do? It sets the series name to Hello
as "=""Hello"""
translates to ="Hello"
("
have to be escaped by a preceding "
).
You can use FileReader
to read the Blob
as an ArrayBuffer
.
Here's a short example:
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);
Here's a longer example:
// ArrayBuffer -> Blob
var uint8Array = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob = new Blob([arrayBuffer]);
// Blob -> ArrayBuffer
var uint8ArrayNew = null;
var arrayBufferNew = null;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBufferNew = event.target.result;
uint8ArrayNew = new Uint8Array(arrayBufferNew);
// warn if read values are not the same as the original values
// arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
function arrayEqual(a, b) { return !(a<b || b<a); };
if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
console.warn("ArrayBuffer byteLength does not match");
if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read
This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.
Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/
Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result
versus this.result
Reference:
I found that for extremely large lists of files (>1e6), these answers were too slow. Here is a solution using parallel processing in python. I know, I know, this isn't linux... but nothing else here worked.
(This saved me hours)
# delete files
import os as os
import glob
import multiprocessing as mp
directory = r'your/directory'
os.chdir(directory)
files_names = [i for i in glob.glob('*.{}'.format('pdf'))]
# report errors from pool
def callback_error(result):
print('error', result)
# delete file using system command
def delete_files(file_name):
os.system('rm -rf ' + file_name)
pool = mp.Pool(12)
# or use pool = mp.Pool(mp.cpu_count())
if __name__ == '__main__':
for file_name in files_names:
print(file_name)
pool.apply_async(delete_files,[file_name], error_callback=callback_error)
It's not an issue related to authentication at the first step. Your import
is not working. So, try writing this on first line:
#!/usr/bin/python
and for the time being run using
python xx.py
For you here is one explanation:
>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>>
>>> print "%s" %xyz
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print "%s" %xyz
NameError: name 'xyz' is not defined
At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk
by default, not ~/.android-sdk-macosx
.
I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.
BrowserWindow
only has an effect on Windows and Linux platforms. you have to package the .icns for max
To set the icon on OS X using electron-packager
, set the icon using the --icon switch.
It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.
--icon
switch. Here is what you can do.
build
in your project directory and put the .icns
the icon in the directory as named icon.icns
.electron-builder --dir
.You will find your application icon will be automatically picked up from that directory location and used for an application while packaging.
Note: The given answer is for recent version of
electron-builder
and tested with electron-builder v21.2.0
1. Include the Open Graph XML namespace extension to your HTML declaration
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://ogp.me/ns/fb#">
2. Inside your <head></head>
use the following meta tag to define the image you want to use
<meta property="og:image" content="fully_qualified_image_url_here" />
Read more about open graph protocol here.
After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time
You need to enable these extensions in the php.ini file
Before:
;extension=pdo_mysql
;extension=mysqli
;extension=pdo_sqlite
;extension=sqlite3
After:
extension=pdo_mysql
extension=mysqli
extension=pdo_sqlite
extension=sqlite3
It is advisable that you also activate the fileinfo extension, many packages require this.
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
I would like to add something to the previous answers but since I don't have the rep to comment, I will just add an answer. This is directed towards android users which are programming in Java.
Per the post from RollingBoy, this code almost worked for me:
Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();
In my case, the waitFor() was not releasing because I was executing a statement with no return ("ip adddr flush eth0"). An easy way to fix this is to simply ensure you always return something in your statement. For me, that meant executing the following: "ip adddr flush eth0 && echo done". You can read the buffer all day, but if there is nothing ever returned, your thread will never release its wait.
Hope that helps someone!
You need to use quote marks.
font-family: "Comic Sans MS", cursive, sans-serif;
Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.
Try giving the folder(s) containing the CSV and Format File read permissions for ‘MSSQLSERVER’ user (or whatever user the SQL Server service is set to Log On As in Windows Services)
I think this confusing exception occurs when you use a variable in a lambda which is a null-reference at run-time. In your case, I would check if your variable calculationViewModel is a null-reference.
Something like:
public ActionResult MNPurchase()
{
CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];
if (calculationViewModel != null)
{
decimal OP = landTitleUnitOfWork.Sales.Find()
.Where(x => x.Min >= calculationViewModel.SalesPrice)
.FirstOrDefault()
.OP;
decimal MP = landTitleUnitOfWork.Sales.Find()
.Where(x => x.Min >= calculationViewModel.MortgageAmount)
.FirstOrDefault()
.MP;
calculationViewModel.LoanAmount = (OP + 100) - MP;
calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);
return View(calculationViewModel);
}
else
{
// Do something else...
}
}
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
You'll have to download the image firstly
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView
I had an issue with the same thing. ChromeOptions is very weird because it's not integrated with the desiredcapabilities like you would think. I forget the exact details, but basically ChromeOptions will reset to default certain values based on whether you did or did not pass a desired capabilities dict.
I did the following monkey-patch that allows me to specify my own dict without worrying about the complications of ChromeOptions
change the following code in /selenium/webdriver/chrome/webdriver.py:
def __init__(self, executable_path="chromedriver", port=0,
chrome_options=None, service_args=None,
desired_capabilities=None, service_log_path=None, skip_capabilities_update=False):
"""
Creates a new instance of the chrome driver.
Starts the service and then creates new instance of chrome driver.
:Args:
- executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
- port - port you would like the service to run, if left as 0, a free port will be found.
- desired_capabilities: Dictionary object with non-browser specific
capabilities only, such as "proxy" or "loggingPref".
- chrome_options: this takes an instance of ChromeOptions
"""
if chrome_options is None:
options = Options()
else:
options = chrome_options
if skip_capabilities_update:
pass
elif desired_capabilities is not None:
desired_capabilities.update(options.to_capabilities())
else:
desired_capabilities = options.to_capabilities()
self.service = Service(executable_path, port=port,
service_args=service_args, log_path=service_log_path)
self.service.start()
try:
RemoteWebDriver.__init__(self,
command_executor=self.service.service_url,
desired_capabilities=desired_capabilities)
except:
self.quit()
raise
self._is_remote = False
all that changed was the "skip_capabilities_update" kwarg. Now I just do this to set my own dict:
capabilities = dict( DesiredCapabilities.CHROME )
if not "chromeOptions" in capabilities:
capabilities['chromeOptions'] = {
'args' : [],
'binary' : "",
'extensions' : [],
'prefs' : {}
}
capabilities['proxy'] = {
'httpProxy' : "%s:%i" %(proxy_address, proxy_port),
'ftpProxy' : "%s:%i" %(proxy_address, proxy_port),
'sslProxy' : "%s:%i" %(proxy_address, proxy_port),
'noProxy' : None,
'proxyType' : "MANUAL",
'class' : "org.openqa.selenium.Proxy",
'autodetect' : False
}
driver = webdriver.Chrome( executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True )
Just do System.out.println(e.getActionCommand());
inside actionPerformed(ActionEvent e)
function. This will tell you which command is just performed.
or
if(e.getActionCommand().equals("Add")){
System.out.println("Add button pressed");
}
Use the concatenation operator +
, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;
Add this in manifest.
<service
android:name=".YourServiceName"
android:enabled="true"
android:exported="false" />
Add a service class.
public class YourServiceName extends Service {
@Override
public void onCreate() {
super.onCreate();
// Timer task makes your service will repeat after every 20 Sec.
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
// Add your code here.
}
});
}
};
//Starts after 20 sec and will repeat on every 20 sec of time interval.
timer.schedule(doAsynchronousTask, 20000,20000); // 20 sec timer
(enter your own time)
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
return START_STICKY;
}
}
this $('#checkboxId').is(':checked')
for verify if is checked
& this $("#checkboxId").prop('checked', true)
to check
& this $("#checkboxId").prop('checked', false)
to uncheck
$("#mydiv").css('top', 200);
$("#mydiv").css('left', 200);
After nearly two hours of debugging I have concluded that the best solution to this is to give the file name a different name to the class that it contains. For Example:
Before example.php contains:
<?php
class example {
}
Solution: rename the file to example.class.php (or something like that), or rename the class to example_class (or something like that)
Hope this helps.
For a more graceful way, try the following:
Caveat: I'm running Debian 7, not Ubuntu, though it is a Debian derivative
If you're running Tomcat as a service, you can get a list of all running services by typing:
sudo service --status-all
I'm running Tomcat 7, which is displayed as tomcat7 in said list. Then, to shut it down just type:
sudo service tomcat7 stop
Here is another one if you need window resize event:
class DivSize extends React.Component {
constructor(props) {
super(props)
this.state = {
width: 0,
height: 0
}
this.resizeHandler = this.resizeHandler.bind(this);
}
resizeHandler() {
const width = this.divElement.clientWidth;
const height = this.divElement.clientHeight;
this.setState({ width, height });
}
componentDidMount() {
this.resizeHandler();
window.addEventListener('resize', this.resizeHandler);
}
componentWillUnmount(){
window.removeEventListener('resize', this.resizeHandler);
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: widht: <b>{this.state.width}px</b>, height: <b>{this.state.height}px</b>
</div>
)
}
}
ReactDOM.render(<DivSize />, document.querySelector('#container'))
First you need to call setContentView(R.layout.main)
then all other initialization.
Please try below Code.
public class Trackfolio extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
@Override
public void onClick(View v) {
editText.getText().clear(); //or you can use editText.setText("");
}
}
We can just create directive like *ngIf
and call it *ngVar
ng-var.directive.ts
@Directive({
selector: '[ngVar]',
})
export class VarDirective {
@Input()
set ngVar(context: any) {
this.context.$implicit = this.context.ngVar = context;
this.updateView();
}
context: any = {};
constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {}
updateView() {
this.vcRef.clear();
this.vcRef.createEmbeddedView(this.templateRef, this.context);
}
}
with this *ngVar
directive we can use the following
<div *ngVar="false as variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="false; let variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="45 as variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="{ x: 4 } as variable">
<span>{{variable | json}}</span>
</div>
Plunker Example Angular4 ngVar
See also
Angular v4
1) div
+ ngIf
+ let
<div *ngIf="{ a: 1, b: 2 }; let variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
</div>
2) div
+ ngIf
+ as
view
<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
<span>{{variable.c}}</span>
</div>
component.ts
export class AppComponent {
x = 5;
}
3) If you don't want to create wrapper like div
you can use ng-container
view
<ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
<span>{{variable.c}}</span>
</ng-container>
As @Keith mentioned in comments
this will work in most cases but it is not a general solution since it relies on variable being truthy
See update for another approach.
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">_x000D_
_x000D_
<style>_x000D_
@import url(main.css);_x000D_
</style>_x000D_
_x000D_
<g>_x000D_
<path d="M28.44......./>_x000D_
</g>_x000D_
</svg>
_x000D_
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">_x000D_
_x000D_
<style>_x000D_
.socIcon g {fill:red;}_x000D_
</style>_x000D_
_x000D_
<g>_x000D_
<path d="M28.44......./>_x000D_
</g>_x000D_
</svg>
_x000D_
Note: External Styles will not work if you include SVG inside <img>
tag. It will work perfectly inside <div>
tag
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
This can also be caused if you include bootstrap.js
before jquery.js
.
Others might have the same problem I did.
Include jQuery
before bootstrap
.
ID=$(docker build -t creack/node .)
doesn't work for me since ID
will contain the output from the build.
SO I'm using this small BASH script:
#!/bin/bash
set -o pipefail
IMAGE=...your image name...
VERSION=...the version...
docker build -t ${IMAGE}:${VERSION} . | tee build.log || exit 1
ID=$(tail -1 build.log | awk '{print $3;}')
docker tag $ID ${IMAGE}:latest
docker images | grep ${IMAGE}
docker run --rm ${IMAGE}:latest /opt/java7/bin/java -version
Yes, if you redirect the output, it won't appear on the console. Use tee
.
ls 2>&1 | tee /tmp/ls.txt
Another feature is between:
Select * from table where date between '2009/01/30' and '2009/03/30'
Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:
void setup() {
// turn on Serial so we can see...
Serial.begin(9600);
// the culprit:
uint8_t my_str[6]; // an array big enough for a 5 character string
// give it something so we can see what it's doing
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // be sure to set the null terminator!!!
// can we see it?
Serial.println((char*)my_str);
// can we do logical operations with it as-is?
Serial.println((char*)my_str == 'Hello');
// okay, it can't; wrong data type (and no terminator!), so let's do this:
String str((char*)my_str);
// can we see it now?
Serial.println(str);
// make comparisons
Serial.println(str == 'Hello');
// one more time just because
Serial.println(str == "Hello");
// one last thing...!
Serial.println(sizeof(str));
}
void loop() {
// nothing
}
And we get:
Hello // as expected
0 // no surprise; wrong data type and no terminator in comparison value
Hello // also, as expected
1 // YAY!
1 // YAY!
6 // as expected
Hope this helps someone!
Since others are recommending installing things like freeware and PowerShell, you could also install Cygwin, which would give you access to many basic Unix commands like time:
abe@abe-PC:~$ time sleep 5
real 0m5.012s
user 0m0.000s
sys 0m0.000s
Not sure how much overhead Cygwin adds.
You can get it in the following manner:
NSInteger row;
NSArray *repeatPickerData;
UIPickerView *repeatPickerView;
row = [repeatPickerView selectedRowInComponent:0];
self.strPrintRepeat = [repeatPickerData objectAtIndex:row];
I did not find Haiku definition here. To be complete, Haiku-os definition is simple __HAIKU__
Swift 4.2
guard let someVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "someVC") as? someVC else {
return
}
someVC.modalPresentationStyle = .overCurrentContext
present(someVC, animated: true, completion: nil)