You could do it this way, which does not require EnableDelayedExpansion
:choosenamea
cls
set /a choosemname=%random%
if %choosemname% GTR %max% goto choosenameb
if %choosemname% LSS %min% goto choosenameb
goto gotnamenow
where max
is your max and min
is your minimum. This is not very efficient since might take a lot of rounds if your range is too small. Also, this will not work for numbers larger than 32767.
Using this CSS for my current site. It works perfect!
#sides{
margin:0;
}
#left{
float:left;
width:75%;
overflow:hidden;
}
#right{
float:left;
width:25%;
overflow:hidden;
}
It is impossible to safely escape a string without a DB connection. mysql_real_escape_string()
and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.
If you are only testing, then you may as well use mysql_escape_string()
, it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.
When calling a function that is declared with throws
in Swift, you must annotate the function call site with try
or try!
. For example, given a throwing function:
func willOnlyThrowIfTrue(value: Bool) throws {
if value { throw someError }
}
this function can be called like:
func foo(value: Bool) throws {
try willOnlyThrowIfTrue(value)
}
Here we annotate the call with try
, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws
, because this function could throw an exception (i.e., when willOnlyThrowIfTrue()
throws, then foo
will automatically rethrow the exception upwards.
If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!
.
func bar() {
try! willOnlyThrowIfTrue(false)
}
This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.
try!
is enforced at runtime: if you use try!
and the function does end up throwing, then your program's execution will be terminated with a runtime error.
Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()
), or sometimes via defer
ed code.
func baz(value: Bool) throws {
var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
var data = NSData(contentsOfFile:filePath)
try willOnlyThrowIfTrue(value)
// data and filePath automatically cleaned up, even when an exception occurs.
}
If for whatever reason you have clean up code that needs to run but isn't in a deinit()
function, you can use defer
.
func qux(value: Bool) throws {
defer {
print("this code runs when the function exits, even when it exits by an exception")
}
try willOnlyThrowIfTrue(value)
}
Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit()
or defer
. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.
Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.
Handling exceptions is done via catch
statements.
func quux(value: Bool) {
do {
try willOnlyThrowIfTrue(value)
} catch {
// handle error
}
}
You can have multiple catch statements, each catching a different kind of exception.
do {
try someFunctionThatThowsDifferentExceptions()
} catch MyErrorType.errorA {
// handle errorA
} catch MyErrorType.errorB {
// handle errorB
} catch {
// handle other errors
}
For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.
For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).
I faced same problem. This is what I did to resolve the issue.
You could use loc
to get series which satisfying your condition and then iloc
to get first element:
In [2]: df
Out[2]:
A B
0 p1 1
1 p1 2
2 p3 3
3 p2 4
In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2 p3
Name: A, dtype: object
In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'
So you didn't say you wanted the application to quit or exit abruptly, so as another option, perhaps just have the response loop end out elegantly. (I am assuming you have a while loop waiting for user instructions. This is some code from a project I just wrote today.
Console.WriteLine("College File Processor");
Console.WriteLine("*************************************");
Console.WriteLine("(H)elp");
Console.WriteLine("Process (W)orkouts");
Console.WriteLine("Process (I)nterviews");
Console.WriteLine("Process (P)ro Days");
Console.WriteLine("(S)tart Processing");
Console.WriteLine("E(x)it");
Console.WriteLine("*************************************");
string response = "";
string videotype = "";
bool starting = false;
bool exiting = false;
response = Console.ReadLine();
while ( response != "" )
{
switch ( response )
{
case "H":
case "h":
DisplayHelp();
break;
case "W":
case "w":
Console.WriteLine("Video Type set to Workout");
videotype = "W";
break;
case "I":
case "i":
Console.WriteLine("Video Type set to Interview");
videotype = "I";
break;
case "P":
case "p":
Console.WriteLine("Video Type set to Pro Day");
videotype = "P";
break;
case "S":
case "s":
if ( videotype == "" )
{
Console.WriteLine("Please Select Video Type Before Starting");
}
else
{
Console.WriteLine("Starting...");
starting = true;
}
break;
case "E":
case "e":
Console.WriteLine("Good Bye!");
System.Threading.Thread.Sleep(100);
exiting = true;
break;
}
if ( starting || exiting)
{
break;
}
else
{
response = Console.ReadLine();
}
}
if ( starting )
{
ProcessFiles();
}
The minimum requirements are based on the Express edition you're attempting to install:
Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8
It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.
The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach()
(because it is "iterable") which eliminates the need to maked iterated _fetch()
calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id']
)
The default is 20 minutes. http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.80).aspx
<sessionState
mode="[Off|InProc|StateServer|SQLServer|Custom]"
timeout="number of minutes"
cookieName="session identifier cookie name"
cookieless=
"[true|false|AutoDetect|UseCookies|UseUri|UseDeviceProfile]"
regenerateExpiredSessionId="[True|False]"
sqlConnectionString="sql connection string"
sqlCommandTimeout="number of seconds"
allowCustomSqlDatabase="[True|False]"
useHostingIdentity="[True|False]"
stateConnectionString="tcpip=server:port"
stateNetworkTimeout="number of seconds"
customProvider="custom provider name">
<providers>...</providers>
</sessionState>
The following is OK in HTML4, but not in XHTML. Check your editor.
<input type=button value="Submit" />
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
Using Java 8, you can do:
String str = "There 0 are 1 some -2-34 -numbers 567 here 890 .";
int[] ints = Arrays.stream(str.replaceAll("-", " -").split("[^-\\d]+"))
.filter(s -> !s.matches("-?"))
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
If you don't have negative numbers, you can get rid of the replaceAll
(and use !s.isEmpty()
in filter
), as that's only to properly split something like 2-34
(this can also be handled purely with regex in split
, but it's fairly complicated).
Arrays.stream
turns our String[]
into a Stream<String>
.
filter
gets rid of the leading and trailing empty strings as well as any -
that isn't part of a number.
mapToInt(Integer::parseInt).toArray()
calls parseInt
on each String
to give us an int[]
.
Alternatively, Java 9 has a Matcher.results method, which should allow for something like:
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There 0 are 1 some -2-34 -numbers 567 here 890 .");
int[] ints = m.results().map(MatchResults::group).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
As it stands, neither of these is a big improvement over just looping over the results with Pattern
/ Matcher
as shown in the other answers, but it should be simpler if you want to follow this up with more complex operations which are significantly simplified with the use of streams.
@people = qw( bob john linda );
$n = @people; # the number 3
Print " le number in the list is $n \n";
Expressions in Perl always return the appropriate value for their context. For example, how about the “name” * of an array. In a list context, it gives the list of elements. But in a scalar context, it returns the number of elements in the array:
If you're hosting website on a specific port in IIS like 4321 then you'd have to allow this port through Windows Firewall too. Here're the steps that I followed along with the imanabidi's answer to get it work for me:
Use git add -A
, this will include the deleted files.
Note: use git rm
for certain files.
Use this.
https://www.facebook.com/browse/?type=page_fans&page_id=<your page id>
It will return up to 500 of the most recent likes.
http://www.facebook.com/browse/?type=page_fans&page_id=<your page id>&start=400
Each page will give you 100 fans. Change start value to (0, 100, 200, 300, 400) to get the first 500. If start is >= 401, the page will be blank :(
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to
xr.parse( new InputSource( filename ));
works just fine.
So the problem is connected with the metadata errors of elcipse. Go to the metadata folder where this configuration is saved. For me one of the erorrs was that:
SEVERE: Error starting static Resources java.lang.IllegalArgumentException: Document base C:\Users\Cannibal\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FoodQuantityService does not exist or is not a readable directory
So go there is in the workspace of your eclipse it is different for all and delete all its content . My services was named FoodQuantityService so I deleted all files in org.eclipse.wst.server.core but before that delete your server configuration from Eclipse
Then create new configuration File->New->Other->Server select Tomcat and then projects which you want to be published. Start the server and everything will be ok.
The following answer is to merge data into same table
MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif')
WHEN NOT MATCHED THEN
INSERT ( d.USERS_ID, d.USER_NAME)
VALUES ('123','itszaif');
This command checks if USER_ID
and USER_NAME
are matched, if not matched then it will insert.
If you want to use the object of ith term and input it to another component in each iteration then:
<table class="table table-striped table-hover">
<tr>
<th> Blogs </th>
</tr>
<tr *ngFor="let blogEl of blogs">
<app-blog-item [blog]="blogEl"> </app-blog-item>
</tr>
</table>
Honestly, I have difficulty implementing it because there's barely any tutorials I've searched that displays writing the keys into the files. The accepted answer was "fine". But for me I had to improve it so that both keys gets saved into two separate files. I've written a helper class so y'all just gotta copy and paste it. Hope this helps lol.
using Microsoft.Win32;
using System;
using System.IO;
using System.Security.Cryptography;
namespace RsaCryptoExample
{
class RSAFileHelper
{
readonly string pubKeyPath = "public.key";//change as needed
readonly string priKeyPath = "private.key";//change as needed
public void MakeKey()
{
//lets take a new CSP with a new 2048 bit rsa key pair
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);
//how to get the private key
RSAParameters privKey = csp.ExportParameters(true);
//and the public key ...
RSAParameters pubKey = csp.ExportParameters(false);
//converting the public key into a string representation
string pubKeyString;
{
//we need some buffer
var sw = new StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, pubKey);
//get the string from the stream
pubKeyString = sw.ToString();
File.WriteAllText(pubKeyPath, pubKeyString);
}
string privKeyString;
{
//we need some buffer
var sw = new StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, privKey);
//get the string from the stream
privKeyString = sw.ToString();
File.WriteAllText(priKeyPath, privKeyString);
}
}
public void EncryptFile(string filePath)
{
//converting the public key into a string representation
string pubKeyString;
{
using (StreamReader reader = new StreamReader(pubKeyPath)){pubKeyString = reader.ReadToEnd();}
}
//get a stream from the string
var sr = new StringReader(pubKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters((RSAParameters)xs.Deserialize(sr));
byte[] bytesPlainTextData = File.ReadAllBytes(filePath);
//apply pkcs#1.5 padding and encrypt our data
var bytesCipherText = csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
string encryptedText = Convert.ToBase64String(bytesCipherText);
File.WriteAllText(filePath,encryptedText);
}
public void DecryptFile(string filePath)
{
//we want to decrypt, therefore we need a csp and load our private key
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
string privKeyString;
{
privKeyString = File.ReadAllText(priKeyPath);
//get a stream from the string
var sr = new StringReader(privKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
RSAParameters privKey = (RSAParameters)xs.Deserialize(sr);
csp.ImportParameters(privKey);
}
string encryptedText;
using (StreamReader reader = new StreamReader(filePath)) { encryptedText = reader.ReadToEnd(); }
byte[] bytesCipherText = Convert.FromBase64String(encryptedText);
//decrypt and strip pkcs#1.5 padding
byte[] bytesPlainTextData = csp.Decrypt(bytesCipherText, false);
//get our original plainText back...
File.WriteAllBytes(filePath, bytesPlainTextData);
}
}
}
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
Make sure your escaping the HTML characters
E.g.
// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
// Escape any html characters
echo htmlentities($_POST['contact_list']);
}
This would occur because of the angle brackets and the browser thinking they are tags.
You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:
You can get both the time and date by using the SYSTEMTIME
struct
. You also need to call one of two functions (either GetLocalTime()
or GetSystemTime()
) to fill out the struct.
GetLocalTime()
will give you the time and date specific to your time zone.
GetSystemTime()
will give you the time and date in UTC.
The SYSTEMTIME
struct
has the following members:
wYear
, wMonth
, wDayOfWeek
, wDay
, wHour
, wMinute
, wSecond
and wMilliseconds
You then need to just access the struct in the regular way
Actual example code:
#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)
int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)
SYSTEMTIME t; // Declare SYSTEMTIME struct
GetLocalTime(&t); // Fill out the struct so that it can be used
// Use GetSystemTime(&t) to get UTC time
printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order
return 0;
}
(Coded for simplicity and clarity, see the original answer for a better formatted method)
The output will be something like this:
Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572
Useful References:
All the WinAPI documentation (most already listed above):
An extremely good beginners tutorial on this subject by Zetcode:
Simple operations with datetime on Codeproject:
1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17
") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.
At Microsoft website, it shows that native OLEDB provider is applied to SQL server directly and another OLEDB provider called OLEDB Provider for ODBC to access other Database, such as Sysbase, DB2 etc. There are different kinds of component under OLEDB Provider. See Distributed Queries on MSDN for more.
You can use the sp_who
stored procedure.
Provides information about current users, sessions, and processes in an instance of the Microsoft SQL Server Database Engine. The information can be filtered to return only those processes that are not idle, that belong to a specific user, or that belong to a specific session.
Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:
var myMappings = [
{ title: "Name", width: "10%" },
{ title: "Phone", width: "10%" },
{ title: "Address", width: "50%" },
{ title: "Zip", width: "10%" },
{ title: "Comments", width: "20%" }
];
Then you could easily iterate through all your "columns" with a for loop:
for (var i = 0; i < myMappings.length; i += 1) {
// myMappings[i].title ...
// myMappings[i].width ...
}
There are at least two ways to do it:
Use nowrap attribute inside the "td" tag:
<th nowrap="nowrap">Really long column heading</th>
Use non-breakable spaces between your words:
<th>Really long column heading</th>
One suggestion in other answers is to use ax.set_axis_bgcolor("red")
. This however is deprecated, and doesn't work on MatPlotLib >= v2.0.
There is also the suggestion to use ax.patch.set_facecolor("red")
(works on both MatPlotLib v1.5 & v2.2). While this works fine, an even easier solution for v2.0+ is to use
ax.set_facecolor("red")
If this string is for presentation to the end user, you should use NSNumberFormatter
. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000
, but in Germany, that would be 10.000
.
It sounds like you want an image
button:
<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />
Alternatively, you can use CSS to make the existing submit
button use your image as its background.
In any case, you don't want a separate <img />
element on the page.
One thing that should be considered is licensing.
Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.
To quote the Sublime Text 2 website:
..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.
The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.
Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.
This licensing requirement is still correct as of Dec 2019.
A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
See Creating a shared and static library with the gnu compiler [gcc]
gcc -c -o out.o out.c
-c
means to create an intermediary object file, rather than an executable.
ar rcs libout.a out.o
This creates the static library. r
means to insert with replacement, c
means to create a new archive, and s
means to write an index. As always, see the man page for more info.
You need to read something about a JSP's lifecycle. Try this: http://en.wikipedia.org/wiki/File:JSPLife.png
JavaScript runs on the client, but in order to change the jsp, you need access to the server. This can be done through Ajax(http://en.wikipedia.org/wiki/Ajax_%28programming%29).
Here are some Ajax-related links: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
SELECT COUNT(1)
FROM FB
WHERE
Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'
If I were to paraphrase the question - is it possible to pick server context for query execution in the DDL - the answer is no. Only database context can be programmatically chosen with USE. (having already preselected the server context externally)
Linked server and OPEN QUERY can give access to the DDL but require somewhat a rewrite of your code to encapsulate as a string - making it difficult to develop/debug.
Alternately you could resort to an external driver program to pickup SQL files to send to the remote server via OPEN QUERY. However in most cases you might as well have connected to the server directly in the 1st place to evaluate the DDL.
First you must to set you app theme with "NoActionBar" like below
<!-- Application theme. -->
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar" />
Then add these lines in your fullscreen activity.
public class MainActiviy extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
It will hide actionbar/toolbar and also statusbar in your fullscreen activity
os.pardir
is a better way for ../
and more readable.
import os
print os.path.abspath(os.path.join(given_path, os.pardir))
This will return the parent path of the given_path
I suggest a custom alias on you .gitconfig
.
You have to way to do:
1) With git command:
git config --global alias.check-file <command>
2) Editing ~/.gitconfig
and add this line on alias section:
[alias]
check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi; }; f"
Once launched command (1) or saved file (2), on your workspace you can test it:
$ git check-file
$ Filename missing
$ git check-file README.md
$ File tracked
$ git check-file foo
$ File not tracked
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
open node.js command prompt
run this command
node -v
HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table>
for layouts for this very same reason.
If you have a numpy array you can do this:
import numpy as np
from matplotlib import pyplot as plt
data = np.array([
[1, 2],
[2, 3],
[3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()
I think this question needs an updated answer, because both PostgreSQL and SQLDeveloper have been updated several times since it was originally asked.
I've got a PostgreSQL instance running in Azure, with SSLMODE=Require. While I've been using DBeaverCE to access that instance and generate an ER Diagram, I've gotten really familiar with SQLDeveloper, which is now at v19.4.
The instructions about downloading the latest PostgreSQL JDBC driver and where to place it are correct. What has changed, though, is where to configure your DB access.
You'll find a file $HOME/.sqldeveloper/system19.4.0.354.1759/o.jdeveloper.db.connection.19.3.0.354.1759/connections.json
:
{
"connections": [
{
"name": "connection-name-goes-here",
"type": "jdbc",
"info": {
"customUrl": "jdbc:postgresql://your-postgresql-host:5432/DBNAME?sslmode=require",
"hostname": "your-postgresql-host",
"driver": "org.postgresql.Driver",
"subtype": "SDPostgreSQL",
"port": "5432",
"SavePassword": "false",
"RaptorConnectionType": "SDPostgreSQL",
"user": "your_admin_user",
"sslmode": "require"
}
}
]
}
You can use this connection with both Data Modeller and the admin functionality of SQLDeveloper. Specifying all the port, dbname and sslmode in the customUrl are required because SQLDeveloper isn't including the sslmode in what it sends via JDBC, so you have to construct it by hand.
Expanding lolo's answer from above, here is a little more automation if you have to include a lot of files. Use this JS code:
$(function () {
var includes = $('[data-include]')
$.each(includes, function () {
var file = 'views/' + $(this).data('include') + '.html'
$(this).load(file)
})
})
And then to include something in the html:
<div data-include="header"></div>
<div data-include="footer"></div>
Which would include the file views/header.html
and views/footer.html
.
Make sure you have more slots for private images.
In my case I converted a user into an organization and it lost it's one free private image, so previous pushes that worked, no longer worked.
Folks -
After looking at these and other solutions, I tried a number of them out using a snippet of code originally from W3Schools as a base. You can find what works in the following. Each of the items commented out work as well and are that way to allow you to experiment simply by removing individual comments. To be clear, it is the "eyecolor" parameter that is not being defined.
function person(firstname, lastname, age, eyecolor)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
// if(null==eyecolor)
// this.eyecolor = "unknown1";
//if(typeof(eyecolor)==='undefined')
// this.eyecolor = "unknown2";
// if(!eyecolor)
// this.eyecolor = "unknown3";
this.eyecolor = this.eyecolor || "unknown4";
}
var myFather = new person("John", "Doe", 60);
var myMother = new person("Sally", "Rally", 48, "green");
var elem = document.getElementById("demo");
elem.innerHTML = "My father " +
myFather.firstname + " " +
myFather.lastname + " is " +
myFather.age + " with " +
myFather.eyecolor + " eyes.<br/>" +
"My mother " +
myMother.firstname + " " +
myMother.lastname + " is " +
myMother.age + " with " +
myMother.eyecolor + " eyes.";
Another option is to check for regular expression match on the command output.
For example:
[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"
The accepted answer will give a false positive if the input is a number plus text, because "stol" will convert the firsts digits and ignore the rest.
I like the following version the most, since it's a nice one-liner that doesn't need to define a function and you can just copy and paste wherever you need it.
#include <string>
...
std::string s;
bool has_only_digits = (s.find_first_not_of( "0123456789" ) == std::string::npos);
EDIT: if you like this implementation but you do want to use it as a function, then this should do:
bool has_only_digits(const string s){
return s.find_first_not_of( "0123456789" ) == string::npos;
}
Take the time to scan through the SystemParameters members.
VirtualScreenWidth
VirtualScreenHeight
These even take into account the relative positions of the screens.
Only tested with two monitors.
This workflow works best for me:
git checkout -b develop
...make some changes...
...notice master has been updated...
...commit changes to develop...
git checkout master
git pull
...bring those changes back into develop...
git checkout develop
git rebase master
...make some more changes...
...commit them to develop...
...merge them into master...
git checkout master
git pull
git merge develop
Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0
first, then cd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.
Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0
will change both the drive and directory :)
Hope this helps someone.
In older versions you could use attr
. As of jQuery 1.6 you should use prop
instead:
$("#target :input").prop("disabled", true);
To disable all form elements inside 'target'. See :input
:
Matches all input, textarea, select and button elements.
If you only want the <input>
elements:
$("#target input").prop("disabled", true);
Regular expressions are overkill for this situation. You can use the String.IndexOfAny()
method in combination with Path.GetInvalidPathChars()
and Path.GetInvalidFileNameChars()
.
Also note that both Path.GetInvalidXXX()
methods clone an internal array and return the clone. So if you're going to be doing this a lot (thousands and thousands of times) you can cache a copy of the invalid chars array for reuse.
One thing I didn't try was editing /etc/udev/rules.d/70-android.rules. Is that likely to be the issue?
Any particular reason why you didn't do that? To answer the question - YES! The udev rules are what informs Ubuntu what your device is and allows user-space tools to therefore access it.
You will not be able to use adb without correctly following the instructions.
With that in mind however, you don't say what version of Ubuntu you're using but I had issues with 10.10 - let me know if you need me to post the contents of my rules file.
Don't worry about running adb via sudo, you don't need it. The MODE="0666"
from the udev rule allows you to access the device as any user.
EDIT:
Don't forget to reload the rules:
sudo udevadm control --reload-rules
EDIT #2:
As @Jesse Glick correctly points out, if adb is already running in daemon mode, you'll also need to restart it for this to work:
sudo adb kill-server
I've used sudo here, since that will guarantee that adb will be killed , and it's the officially supported method to stop the server. It will be automatically restarted the next time adb is used, but this time with the correct environment.
You can use ngShow.
<li ng-show="!events.length">No events</li>
See example.
Or you can use ngHide
<li ng-hide="events.length">No events</li>
See example.
For object you can test Object.keys.
JMX now uses port 7199 instead of port 8080 (as of Cassandra 0.8.xx).
This is configurable in your cassandra-env.sh file, but the default is 7199.
It's not free or open source. But you can give Intellij Idea's SWING GUI designer a try.
It's in your home folder but it's hidden by default.
Typing the below commands in the terminal made it visible for me (only the .m2
folder that is, not all the other hidden folders).
> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2
openssl s_client
instead of curl
.-msg
does the trick!-debug
helps to see what actually travels over the socket.-status
OCSP stapling should be standard nowadays.openssl s_client -connect example.com:443 -tls1_2 -status -msg -debug -CAfile <path to trusted root ca pem> -key <path to client private key pem> -cert <path to client cert pem>
Other useful switches
-tlsextdebug
-prexit
-state
Please try Npcap: https://github.com/nmap/npcap, it is based on WinPcap and supports loopback traffic capturing on Windows. Npcap is a subproject of Nmap (http://nmap.org/), so please report any issues on Nmap's development list (http://seclists.org/nmap-dev/).
This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:
Press the Windows + R keys to open the Run dialog, type
eventvwr.msc
, and press Enter.If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.
Do either step 5 or 6 below for what shutdown events you would like to see.
To See the Dates and Times of All User Shut Downs of the Computer
A) In Event sources, click/tap on the drop down arrow and check the
USER32
box.B) In the All Event IDs field, type
1074
, then click/tap on OK.C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.
D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.
E) Go to step 7.
To See the Dates and Times of All Unexpected Shut Downs of the Computer
A) In the All Event IDs field, type
6008
, then click/tap on OK.B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.
To create AAR
while creating follow below steps.
File->New->New Module->Android Library and create
.
To generate AAR
Go to gradle at top right pane in android studio follow below steps.
Gradle->Drop down library name -> tasks-> build-> assemble or assemble release
AAR will be generated in build/outputs/aar/
But if we want AAR to get generated in specific folder in project directory with name you want, modify your app level build.gradle
like below
defaultConfig {
minSdkVersion 26
targetSdkVersion 28
versionCode System.getenv("BUILD_NUMBER") as Integer ?: 1
versionName "0.0.${versionCode}"
libraryVariants.all { variant ->
variant.outputs.all { output ->
outputFileName = "/../../../../release/" + ("your_recommended_name.aar")
}
}
}
Now it will create folder with name "release" in project directory which will be having AAR.
To import "aar" into project,check below link.
How to manually include external aar package using new Gradle Android Build System
This happened to me once after I merged a pull request on Bitbucket.
I just had to do:
git fetch
My problem was solved. I hope this helps!!!
The method is implicitly defined (i.e. generated by the compiler).
From the JLS:
In addition, if
E
is the name of anenum
type, then that type has the following implicitly declaredstatic
methods:/** * Returns an array containing the constants of this enum * type, in the order they're declared. This method may be * used to iterate over the constants as follows: * * for(E c : E.values()) * System.out.println(c); * * @return an array containing the constants of this enum * type, in the order they're declared */ public static E[] values(); /** * Returns the enum constant of this type with the specified * name. * The string must match exactly an identifier used to declare * an enum constant in this type. (Extraneous whitespace * characters are not permitted.) * * @return the enum constant with the specified name * @throws IllegalArgumentException if this enum type has no * constant with the specified name */ public static E valueOf(String name);
IN='[email protected];[email protected];Charlie Brown <[email protected];!"#$%&/()[]{}*? are no problem;simple is beautiful :-)'
set -f
oldifs="$IFS"
IFS=';'; arrayIN=($IN)
IFS="$oldifs"
for i in "${arrayIN[@]}"; do
echo "$i"
done
set +f
Output:
[email protected]
[email protected]
Charlie Brown <[email protected]
!"#$%&/()[]{}*? are no problem
simple is beautiful :-)
Explanation: Simple assignment using parenthesis () converts semicolon separated list into an array provided you have correct IFS while doing that. Standard FOR loop handles individual items in that array as usual. Notice that the list given for IN variable must be "hard" quoted, that is, with single ticks.
IFS must be saved and restored since Bash does not treat an assignment the same way as a command. An alternate workaround is to wrap the assignment inside a function and call that function with a modified IFS. In that case separate saving/restoring of IFS is not needed. Thanks for "Bize" for pointing that out.
I had got this error, Linux system(Ubuntu) and This might happen when you run :
npm install
1) If the project is not present in your localdisk/computer, copy it to your computer and try again. So you get the permission to access folder (Just make sure you have access permission).
2) If you still get some warnings or errors, run:
npm audit fix
This will solve vulnerabilities in your dependencies and can help you fix a vulnerability by providing simple-to-run npm commands and recommendations for further troubleshooting.
Hope it helps!
I was using to many await, so i was not getting response , i converted in to sync call its started working
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(URL);
var response = client.GetAsync(URL).Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.
It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
I think this is an update. I was unable to install rJava (on Windows) until I installed the JDK, as per Javac is not found and javac not working in windows command prompt. The message I was getting was
'javac' is not recognized as an internal or external command, operable program or batch file.
The JDK includes the JRE, and according to https://cran.r-project.org/web/packages/rJava/index.html the current version (0.9-7 published 2015-Jul-29) of rJava
SystemRequirements: Java JDK 1.2 or higher (for JRI/REngine JDK 1.4 or higher), GNU make
So there you are: if rJava won't install because it can't find javac, and you have the JRE installed, then try the JDK. Also, make sure that JAVA_HOME
points to the JDK and not the JRE.
As Edan Maor explained, the quick and dirty way to do it (for [utc-16] encoded .xml files), which you should not do for the resons Edam Maor explained, can done with the following python 2.7 code in case time constraints do not allow you to learn (propper) XML parses.
Assuming you want to:
It worked in python 2.7 modifying an .xml file named "b.xml" located in folder "a", where "a" was located in the "working folder" of python. It outputs the new modified file as "c.xml" in folder "a", without yielding encoding errors (for me) in further use outside of python 2.7.
pattern = '<Author>'
subst = ' <Author>' + domain + '\\' + user_name + '</Author>'
line_index =0 #set line count to 0 before starting
file = io.open('a/b.xml', 'r', encoding='utf-16')
lines = file.readlines()
outFile = open('a/c.xml', 'w')
for line in lines[0:len(lines)]:
line_index =line_index +1
if line_index == len(lines):
#1. & 2. delete last line and adding another line in its place not writing it
outFile.writelines("Write extra line here" + '\n')
# 4. Close root tag:
outFile.writelines("</phonebook>") # as in:
#http://tizag.com/xmlTutorial/xmldocument.php
else:
#3. Substitue a line if it finds the following substring in a line:
pattern = '<Author>'
subst = ' <Author>' + domain + '\\' + user_name + '</Author>'
if pattern in line:
line = subst
print line
outFile.writelines(line)#just writing/copying all the lines from the original xml except for the last.
If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:
CSS:
.main_container{
position: relative;
width: 500px;
height: 300px;
background-color: #cccccc;
}
.center_horizontally{
position: absolute;
width: 100px;
height: 100px;
background-color: green;
left: 50%;
top: 0;
transform: translate(-50%,0);
}
.center_vertically{
position: absolute;
top: 50%;
left: 0;
width: 100px;
height: 100px;
background-color: blue;
transform: translate(0,-50%);
}
.center{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
transform: translate(-50%,-50%);
}
HTML:
<div class="main_container">
<div class="center_horizontally"></div>
<div class="center_vertically"></div>
<div class="center"></div>
</div>
</div
Things seem to have changed since Angular 2.0.0
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) {
return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
The .next()
function will be called on your subscriber.
There are two ways to exit a method early (without quitting the program):
return
keyword.Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
Specifically about your code:
You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:
if (textBox1.Text == String.Empty)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
}
return; // Are you sure you want the return to be here??
If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.
Environment.Newline
instead of "\r\n"
.from urllib import request
def get(url):
with request.urlopen(url) as r:
return r.read()
def download(url, file=None):
if not file:
file = url.split('/')[-1]
with open(file, 'wb') as f:
f.write(get(url))
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
1 returns the current physical directory of the file (e.g. aspx) being executedServer.MapPath("..")
returns the parent directoryServer.MapPath("~")
returns the physical path to the root of the applicationServer.MapPath("/")
returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)An example:
Let's say you pointed a web site application (http://www.example.com/
) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath()
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".")
1 returns D:\WebApps\shop\products
Server.MapPath("..")
returns D:\WebApps\shop
Server.MapPath("~")
returns D:\WebApps\shop
Server.MapPath("/")
returns C:\Inetpub\wwwroot
Server.MapPath("/shop")
returns D:\WebApps\shop
If Path starts with either a forward slash (/
) or backward slash (\
), the MapPath()
returns a path as if Path was a full, virtual path.
If Path doesn't start with a slash, the MapPath()
returns a path relative to the directory of the request being processed.
Note: in C#, @
is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.If you are building a windows app try to build as x64 instead of Any CPU. It should work fine.
Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:
select * from
(
select object_name objname, object_type, 'my object' details, 1 resolveOrder
from user_objects
where object_type not like 'SYNONYM'
union all
select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
from user_synonyms
union all
select synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
The compile()
method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int)
to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher()
method, and the only way to get ahold of the Pattern object is through the compile()
method. Then there's the find()
method which, unlike matches()
, is not duplicated in the String or Pattern classes.
The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches()
method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:
for (String s : myStringList) {
if ( s.matches("\\d+") ) {
doSomething();
}
}
...is exactly equivalent to this:
for (String s : myStringList) {
if ( Pattern.compile("\\d+").matcher(s).matches() ) {
doSomething();
}
}
Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
if ( m.reset(s).matches() ) {
doSomething();
}
}
If you're familiar with .NET regexes, you may be wondering if Java's compile()
method is related to .NET's RegexOptions.Compiled
modifier; the answer is no. Java's Pattern.compile()
method is merely equivalent to .NET's Regex constructor. When you specify the Compiled
option:
Regex r = new Regex(@"\d+", RegexOptions.Compiled);
...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String)
and one you create explicitly with Pattern#compile(String)
.
(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches()
, not when you call a Regex constructor directly. ref)
input = document.getElementById("the_number_input")
input.addEventListener("mousewheel", function(event){ this.blur() })
For jQuery example and a cross-browser solution see related question:
The better pattern is to create a standalone BroadcastReceiver
. This insures that your app can respond to the broadcast, whether or not the Service
is running. In fact, using this pattern may remove the need for a constant-running Service
altogether.
Register the BroadcastReceiver
in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent
(Bundle
) to the Service
, and respond to it in onStartCommand()
.
Eg:
public class FooReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}
If you are using
android:layout_width="match_parent"
Use wrap_content and it will only show the set numStars :)
android:layout_width="wrap_content"
If you add a $scope.$apply();
right after $scope.pluginsDisplayed.splice(index,1);
then it works.
I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.
I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (http://avinash.me/losh, source http://github.com/hardfire/losh) based on AngularJS. It is not very clean, but it might be of help.
You may also do the following in Python 3.6.1
from Object import Object as Parent
and your class definition to:
class Visitor(Parent):
In Pycharm Just use Shift+Tab to move a block of code left.
Found the solution from here
This gets the last second of the previous day:
DateAdd("s",-1,DateAdd("d",1,Today())
This returns the last second of the previous week:
=dateadd("d", -Weekday(Now), (DateAdd("s",-1,DateAdd("d",1,Today()))))
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"
you can also try this in sql-server !!
select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city
or try using sum,union
select sum(total) as mytotal,city
from
(
select * from cash union
select * from cheque
) as vij
group by city
<div class="small hidden-xs">
Some Content Here
</div>
This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.
This answer satisfies the question in the OP title (which is how I found this Q/A).
`n
is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n
(carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:
(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
//
is unconditionally "flooring division", e.g:
>>> 4.0//1.5
2.0
As you see, even though both operands are float
s, //
still floors -- so you always know securely what it's going to do.
Single /
may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:
$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667
As you see, single /
may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q
flag...;-).
So, if and when you know you want flooring, always use //
, which guarantees it. If and when you know you don't want flooring, slap a float()
around other operand and use /
. Any other combination, and you're at the mercy of version, imports, and flags!-)
To permanently set the language syntax:
open settings.json
file
*) format all txt files with javascript formatting
"files.associations": {
"*.txt": "javascript"
}
*) format all unsaved files (untitled-1 etc) to javascript:
"files.associations": {
"untitled-*": "javascript"
}
You can declare SqlConnection
and SqlCommand
instances at global level so that you can use it through out the class. Connection string is in Web.Config
.
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
Now you can use the below method to pass values to Stored Procedure and get the DataSet
.
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
The following is the sample of connection string in config file
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
While Niemeyer's answer is a more correct answer to the question, you could also do the following:
<div>
<input data-bind="value: VMA.name" />
</div>
<div>
<input data-bind="value: VMB.name" />
</div>
<script type="text/javascript">
var viewModels = {
VMA: {name: ko.observable("Bob")},
VMB: {name: ko.observable("Ted")}
};
ko.applyBindings(viewModels);
</script>
This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:
<div>
<input data-bind="value: VMA.name() + ' and ' + VMB.name()" />
</div>
From here: http://www.anddev.org/working_with_files-t115.html
//Writing a file...
try {
// catches IOException below
final String TESTSTRING = new String("Hello Android");
/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(TESTSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
//Reading the file back...
/* We have to use the openFileInput()-method
* the ActivityContext provides.
* Again for security reasons with
* openFileInput(...) */
FileInputStream fIn = openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
/* Prepare a char-Array that will
* hold the chars we read back in. */
char[] inputBuffer = new char[TESTSTRING.length()];
// Fill the Buffer with data from the file
isr.read(inputBuffer);
// Transform the chars to a String
String readString = new String(inputBuffer);
// Check if we read back the same chars that we had written out
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading stuff", "success = " + isTheSame);
} catch (IOException ioe)
{ioe.printStackTrace();}
My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.
To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.
To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:
ciphertext = ( plaintext^e ) mod n
To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:
plaintext = ( ciphertext^d ) mod n
To generate private (d,n) key using openssl you can use the following command:
openssl genrsa -out private.pem 1024
To generate public (e,n) key from the private key using openssl you can use the following command:
openssl rsa -in private.pem -out public.pem -pubout
To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):
openssl rsa -in private.pem -text -noout | less
modulus - n
privateExponent - d
publicExponent - e
prime1 - p
prime2 - q
exponent1 - d mod (p-1)
exponent2 - d mod (q-1)
coefficient - (q^-1) mod p
Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.
Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:
# Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der
# Print private.der private key contents as binary stream
xxd -p private.der
# Now compare the output of the above command with output
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less
This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.
To see the contents of the public.pem public RSA key run the following (output truncated to labels here):
openssl rsa -in public.pem -text -pubin -noout
Modulus - n
Exponent (public) - e
No surprises here. It's just (n, e) pair, as promised.
Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.
I answered my problem with a default width for all columns and cells, like below:
int width = 15; // Where width is number of caracters
sheet.setDefaultColumnWidth(width);
well, another way is that use cors proxy, you just need to add https://cors-anywhere.herokuapp.com/ before your URL.so your URL will be like https://cors-anywhere.herokuapp.com/http://ajax.googleapis.com/ajax/services/feed/load.
The proxy server receives the http://ajax.googleapis.com/ajax/services/feed/load from the URL above. Then it makes the request to get that server’s response. And finally, the proxy applies the
Access-Control-Allow-Origin: *
to that original response.
This solution is great because it works in both development and production. In summary, you’re taking advantage of the fact that the same-origin policy is only implemented in browser-to-server communication. Which means it doesn’t have to be enforced in server-to-server communication!
you can read more about the solution here on Medium 3 Ways to Fix the CORS Error
You can use ternary operator as follows:
smallest=(a<b)?((a<c)?a:c):((b<c)?b:c);
Which takes only one assignment and minimum two comparisons.
But I think that these statements would not have any effect on execution time, your initial logic will take same time as of mine and all of others.
The easiest thing to do is putting a div
with the following CSS in the body:
#hideAll
{
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
background-color: white;
z-index: 99; /* Higher than anything else in the document */
}
(Note that position: fixed
won't work in IE6 - I know of no sure-fire way of doing this in that browser)
Add the DIV like so (directly after the opening body
tag):
<div style="display: none" id="hideAll"> </div>
show the DIV directly after :
<script type="text/javascript">
document.getElementById("hideAll").style.display = "block";
</script>
and hide it onload
:
window.onload = function()
{ document.getElementById("hideAll").style.display = "none"; }
or using jQuery
$(window).load(function() { document.getElementById("hideAll").style.display = "none"; });
this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.
You might also consider running the (non-python) program xls2csv. Feed it an xls file, and you should get back a csv.
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.:
break;
case R.id.:
break;
default:
break;
}
}
Using negate
from purrr
also does the trick quickly and neatly:
`%not_in%` <- purrr::negate(`%in%`)
Then usage is, for example,
c("cat", "dog") %not_in% c("dog", "mouse")
This type of behavior is usually desired while implementing drag-drop behavior on an html page. The solution below was tested on IE 8.0.6, FireFox 3.6.6, Opera 10.53, and Safari 4 on an MS Windows XP machine.
First a little function from Peter-Paul Koch; cross browser event handler:
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}
And then use this method to attach an event handler to the document objects mouseout event:
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
// stop your drag event here
// for now we can just use an alert
alert("left window");
}
});
Finally, here is an html page with the script embedded for debugging:
<html>
<head>
<script type="text/javascript">
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}
addEvent(window,"load",function(e) {
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
// stop your drag event here
// for now we can just use an alert
alert("left window");
}
});
});
</script>
</head>
<body></body>
</html>
If you google. "Count down for loop python" you get these, which are pretty accurate.
how to loop down in python list (countdown)
Loop backwards using indices in Python?
I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.
.loader{_x000D_
position: fixed;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
z-index: 9999;_x000D_
background: url('//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif') _x000D_
50% 50% no-repeat rgb(249,249,249);_x000D_
}
_x000D_
<div class="loader"></div>
_x000D_
Please set the request Content Type before you read the response stream;
request.ContentType = "text/xml";
The attributes
property contains them all:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
What you can also do is extending .attr
so that you can call it like .attr()
to get a plain object of all attributes:
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
Usage:
var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }
Unfortunately I don't have enough reputation to comment or vote on the current answers to I've had to write my own.
Originally the OP's question said "variable" rather than "parameter", which got very confusing, especially as this was the number one link in google for searching how to test for blank variables. Since my original answer, Stephan has edited the original question to use the correct terminology, but rather than deleting my answer I decided to leave it to help clear up any confusion, especially in case google is still sending people here for variables too:
%1 IS NOT A VARABLE! IT IS A COMMAND LINE PARAMETER.
Very important distinction. A single percent sign with a number after it refers to a command line parameter not a variable.
Variables are set using the set command, and are recalled using 2 percent signs - one before and one after. For example %myvar%
To test for an empty variable you use the "if not defined" syntax (commands explicitly for variables do not require any percent signs), for example:
set myvar1=foo
if not defined myvar1 echo You won't see this because %myvar1% is defined.
if not defined myvar2 echo You will see this because %myvar2% isn't defined.
(If you want to test command line parameters then I recommend referring to jamesdlin's answer.)
Code Formatting Shortcut:
Visual Studio Code on Windows - Shift + Alt + F
Visual Studio Code on MacOS - Shift + Option + F
Visual Studio Code on Ubuntu - Ctrl + Shift + I
You can also customize this shortcut using a preference setting if needed.
Code Formatting While Saving the File:
Visual Studio Code allows the user to customize the default settings.
If you want to auto format your content while saving, add the below code snippet in the work space settings of Visual Studio Code.
Menu File → Preferences → Workspace Settings
{
// Controls if the editor should automatically format the line after typing
"beautify.onSave": true,
"editor.formatOnSave": true,
// You can auto format any files based on the file extensions type.
"beautify.JSfiles": [
"js",
"json",
"jsbeautifyrc",
"jshintrc",
"ts"
]
}
Note: now you can auto format TypeScript files. Check my update.
Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt")
. The only drawback is that this call requires root privileges on OSX.
Try the following:
ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
AGSM's answer shows a convenient way of solving this problem using the python-dateutil
package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this:
from datetime import date
def add_years(d, years):
"""Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
try:
return d.replace(year = d.year + years)
except ValueError:
return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
If you want the other possibility (changing February 29 to February 28) then the last line should be changed to:
return d + (date(d.year + years, 3, 1) - date(d.year, 3, 1))
Yes, this is impossible to modify the title of it. If you still want to have your own title, you can try to use other pop-up windows instead.
Not very simple but:
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]
Also handles the case for multiples in the 'subtrahend':
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]
EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.
b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }
Put it in a lambda if needed:
subtract = lambda do |minuend, subtrahend|
subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end
then:
subtract.call a, [1,1,3]
Even if the hash is not for security, you can use sha instead of md5. In my opinion, the people should forget about md5 for now, it's in the past!
The normal nodejs sha256 is deprecated. So, you have two alternatives for now:
var shajs = require('sha.js') - https://www.npmjs.com/package/sha.js (used by Browserify)
var hash = require('hash.js') - https://github.com/indutny/hash.js
I prefer using shajs
instead of hash
, because I consider sha the best hash function nowadays and you don't need a different hash function for now. So to get some hash in hex you should do something like the following:
sha256.update('hello').digest('hex')
You can not modify the host file in the image using echo
in RUN
step because docker daemon will maintain the file(/etc/hosts) and its content(hosts entry) when you start a container from the image.
However following can be used to achieve the same:
ENTRYPOINT ["/bin/sh", "-c" , "echo 192.168.254.10 database-server >> /etc/hosts && echo 192.168.239.62 redis-ms-server >> /etc/hosts && exec java -jar ./botblocker.jar " ]
Key to notice here is the use of exec
command as docker documentation suggests. Use of exec will make the java command as PID 1 for the container. Docker interrupts will only respond to that.
See https://docs.docker.com/engine/reference/builder/#entrypoint
I resolved this issue. In my case my application pool was stopped. After little bit of Googling i found out that application pool was running under some user identity and password was changed for that user. After updating password it starts working fine.
Preferences -> Remote Systems -> Files -> Show hidden files
(make sure this is checked)
If you have a class for each of your input box, then you can do it as
var checked = []
$('input.Booking').each(function ()
{
checked.push($(this).val());
});
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
Follow below steps:
1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.
2 )Go to Solution Explorer, click show All Files icon.
3) Go to App_Data, right click and delete all ".mdf" files for this project.
4) Delete Migrations folder by right click and delete.
5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.
6) Go to Package Manager Console in Visual Studio and type:
Enable-Migrations -Force
Add-Migration init
Update-Database
7) Run your application
Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.
ConcurrentLinkedQueue means no locks are taken (i.e. no synchronized(this) or Lock.lock calls). It will use a CAS - Compare and Swap operation during modifications to see if the head/tail node is still the same as when it started. If so, the operation succeeds. If the head/tail node is different, it will spin around and try again.
LinkedBlockingQueue will take a lock before any modification. So your offer calls would block until they get the lock. You can use the offer overload that takes a TimeUnit to say you are only willing to wait X amount of time before abandoning the add (usually good for message type queues where the message is stale after X number of milliseconds).
Fairness means that the Lock implementation will keep the threads ordered. Meaning if Thread A enters and then Thread B enters, Thread A will get the lock first. With no fairness, it is undefined really what happens. It will most likely be the next thread that gets scheduled.
As for which one to use, it depends. I tend to use ConcurrentLinkedQueue because the time it takes my producers to get work to put onto the queue is diverse. I don't have a lot of producers producing at the exact same moment. But the consumer side is more complicated because poll won't go into a nice sleep state. You have to handle that yourself.
Wow, I found yet another case for this problem. None of the above worked. Eventually I used python's ability to introspect what was being loaded. For python 2.7 this means:
import imp
imp.find_module("cv2")
This turned up a completely unexpected "cv2.pyd" file in an Anaconda DLL directory that wasn't touched by multiple uninstall/install attempts. Python was looking there first and not finding my good installation. I deleted that cv2.pyd file and tried imp.find_module("cv2") again and python immediately found the right file and cv2 started working.
So if none of the other solutions work for you, make sure you use python introspection to see what file python is trying to load.
Another example based off the original source, with a sample tree structure already in place (easier to see how it works IMO) and a filter to search the tree:
For beginners: To create your .bash_profile
file in your home directory on MacOS, run:
nano ~/.bash_profile
Then you can paste in the following:
https://gist.github.com/mocon/0baf15e62163a07cb957888559d1b054
As you can see, it includes some example aliases and an environment variable at the bottom.
One you're done making your changes, follow the instructions at the bottom of the Nano editor window to WriteOut (Ctrl-O
) and Exit (Ctrl-X
). Then quit your Terminal and reopen it, and you will be able to use your newly defined aliases and environment variables.
Java includes a scripting language extension package starting with version 6.
See the Rhino project documentation for embedding a JavaScript interpreter in Java.
[Edit]
Here is a small example of how you can expose Java objects to your interpreted script:
public class JS {
public static void main(String args[]) throws Exception {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("stdout", System.out);
js.eval("stdout.println(Math.cos(Math.PI));");
// Prints "-1.0" to the standard output stream.
}
}
I have solved it as follow.
import $ from 'jquery';
(function () {
// ... code let script = $(..)
})();
Just to propose a sed
alternative. :) To skip first one million lines, try |sed '1,1000000d'
.
Example:
$ perl -wle 'print for (1..1_000_005)'|sed '1,1000000d'
1000001
1000002
1000003
1000004
1000005
you can use this.finish() if you want to close current activity.
this.finish()
Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
List<Integer> arrlst = Arrays.asList(arr);
System.out.println(arrlst.lastIndexOf(1));
A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).
More info on default primitive values here.
I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.
<a name='fb_share' type='button_count' href='http://www.facebook.com/sharer.php?appId={YOUR APP ID}&link=<?php the_permalink() ?>' rel='nofollow'>Share</a><script src='http://static.ak.fbcdn.net/connect.php/js/FB.Share' type='text/javascript'></script>
use pandas vectorized string methods; as in the documentation:
these methods exclude missing/NA values automatically
.str.lower()
is the very first example there;
>>> df['x'].str.lower()
0 one
1 two
2 NaN
Name: x, dtype: object
Now the following wont help you with files that are already cached, but moving forward, you can use the following to easily force a request to get something new, without changing the actual filename.
# Rewrite all requests for JS and CSS files to files of the same name, without
# any numbers in them. This lets the JS and CSS be force out of cache easily
# by putting a number at the end of the filename
# e.g. a request for static/js/site-52.js will get the file static/js/site.js instead.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^static/(js|css)/([a-z]+)-([0-9]+)\.(js|css)$ /site/$1/$2.$4 [R=302,NC,L]
</IfModule>
Of course, the higher up in your folder structure you do this type of approach, the more you kick things out of cache with a simple change.
So for example, if you store the entire css and javascript of your site in one main folder
/assets/js
/assets/css
/assets/...
Then you can could start referencing it as "assets-XXX" in your html, and use a rule like so to kick all assets content out of cache.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^assets-([a-z0-9]+)/(.*) /$2 [R=302,NC,L]
</IfModule>
Note that if you do go with this, after you have it working, change the 302 to a 301, and then caching will kick in. When it's a 302 it wont cache at the browser level because it's a temporary redirect. If you do it this way, then you could bump up the expiry default time to 30 days for all assets, since you can easily kick things out of cache by simply changing the folder name in the login page.
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault A2592000
</IfModule>
Just use this:
var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);
Easy way to get random number in ruby is,
def random
(1..10).to_a.sample.to_s
end
The most elegant way to find percentages across columns or index is to use pd.crosstab
.
Sample Data
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]})
The output dataframe is like this
print(df)
state office_id sales
0 CA 1 764505
1 WA 2 313980
2 CO 3 558645
3 AZ 4 883433
4 CA 5 301244
5 WA 6 752009
6 CO 1 457208
7 AZ 2 259657
8 CA 3 584471
9 WA 4 122358
10 CO 5 721845
11 AZ 6 136928
Just specify the index, columns and the values to aggregate. The normalize keyword will calculate % across index or columns depending upon the context.
result = pd.crosstab(index=df['state'],
columns=df['office_id'],
values=df['sales'],
aggfunc='sum',
normalize='index').applymap('{:.2f}%'.format)
print(result)
office_id 1 2 3 4 5 6
state
AZ 0.00% 0.20% 0.00% 0.69% 0.00% 0.11%
CA 0.46% 0.00% 0.35% 0.00% 0.18% 0.00%
CO 0.26% 0.00% 0.32% 0.00% 0.42% 0.00%
WA 0.00% 0.26% 0.00% 0.10% 0.00% 0.63%
You are looking for 2 options to java
:
Put them in your command line invocation of the java
executable, like this:
java -Xms512M -Xmx1024M my.package.MainClass
Keep in mind that you may want the starting and max heap sizes to be the same, depending on the application, as it avoids resizing the heap during runtime (which can take up time in applications that need to be responsive). Resizing the heap can entail moving a lot of objects around and redoing bookkeeping.
For every-day projects, make them whatever you think is good enough. Profile for help.
Finding the duplicates in a String
:
public class a36 {
public static void main(String[] args) {
String a = "Gini Rani";
fix(a);
}//main
public static void fix(String a ){
Map<Character ,Integer> map = new HashMap<>();
for (int i = 0; i <a.length() ; i++ ) {
char ch = a.charAt(i);
map.put(ch , map.getOrDefault(ch,0) +1 );
}//for
List<Character> list = new ArrayList<>();
Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();
for ( Map.Entry<Character ,Integer> entry : entrySet) {
list.add( entry.getKey() );
System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() );
}//for
System.out.println("Duplicate elements => " + list);
}//fix
}
public class a37 {
public static void main(String[] args) {
String aa = "Protijayi Gini";
String[] stringarray = aa.split("");
Map<String , Long> map = Arrays.stream(stringarray)
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
map.forEach( (k, v) -> System.out.println(k + " : "+ v) );
}
}
Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified. (Using your example) Placing the second div inside the first div, would have rendered a result...example below...
<div id="working">
<div id="not-working"></div>
</div>
The second div would be 30% of the first div's height.
I had a similar problem when I rearranged the folder structure of a project. I tried all the hints given in this thread but none of them worked. After checking further I discovered that I forgot to copy an important hidden file over to the new directory. That was
.angular-cli.json
from the root directory of the @angular/cli project. After I copied that file over all was running as expected.
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
Receiver:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
Linking with a library that defines the missing symbol (-lboost_system
) is the obvious solution, but in the particular case of Boost.System, a misfeature in the original design makes it use boost::system::generic_category()
and boost::system::system_category()
needlessly. Compiling with the flag -DBOOST_SYSTEM_NO_DEPRECATED
disables that code and lets a number of programs compile without requiring -lboost_system
(that link is of course still needed if you explicitly use some of the library's features).
Starting from Boost 1.66 and this commit, this behavior is now the default, so hopefully fewer and fewer users should need this answer.
As noticed by @AndrewMarshall, an alternative is to define BOOST_ERROR_CODE_HEADER_ONLY
which enables a header-only version of the code. This was discouraged by Boost as it can break some functionality. However, since 1.69, header-only seems to have become the default, supposedly making this question obsolete.
user@M063:/var/www/html/app/.git/objects$ sudo chmod 777 -R .git/objects
user@M063:/var/www/html/app/.git/objects$ sudo chown -R user:user .git/objects/
foreach ($array as $value)
{
if(!isset($counter))
{
$counter = 0;
}
$counter++;
}
//Sorry if the code isn't shown correctly. :P
//I like this version more, because the counter variable is IN the foreach, and not above.
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
The /
operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
Should be fine!
This piece of code fixed for me!
Modified code of @JohnnyCoder
HTML:
<video id="captureVideoId" muted width="1280" height="768"></video>
<video controls id="recordedVideoId" muted width="1280"
style="display:none;" height="768"></video>
JS:
var recordedVideo = document.querySelector('video#recordedVideoId');
var superBuffer = new Blob(recordedBlobs, { type: 'video/webm' });
recordedVideo.src = window.URL.createObjectURL(superBuffer);
// workaround for non-seekable video taken from
// https://bugs.chromium.org/p/chromium/issues/detail?id=642012#c23
recordedVideo.addEventListener('loadedmetadata', function () {
if (recordedVideo.duration === Infinity) {
recordedVideo.currentTime = 1e101;
recordedVideo.ontimeupdate = function () {
recordedVideo.currentTime = 0;
recordedVideo.ontimeupdate = function () {
delete recordedVideo.ontimeupdate;
var isPlaying = recordedVideo.currentTime > 0 &&
!recordedVideo.paused && !recordedVideo.ended &&
recordedVideo.readyState > 2;
if (isPlaying) {
recordedVideo.play();
}
};
};
}
});
In my case I had difficulties with the posted answers. I ended up using the following:
ALTER TABLE table_name CHANGE COLUMN column_name column_name VARCHAR(200) NOT NULL DEFAULT '';
Change VARCHAR(200)
to your datatype, and optionally change the default value.
If you don't have a default value you're going to have a problem making this change, as default would be null creating a conflict.
I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.
@Directive({
selector: "[tabindex]"
})
export class TabindexDirective {
constructor(private elementHost: ElementRef) {}
@HostListener("focus")
setInputFocus(): void {
this.elementHost.nativeElement.classList.add("has-focus");
}
@HostListener("blur")
setInputFocusOut(): void {
this.elementHost.nativeElement.classList.remove("has-focus");
}
}
All answers are awesome and explained everything very well
but I just want to point out different way for passing args to main method
in visual studio
like this image
and happy knowing secrets
You can use std::numeric_limits
which is defined in <limits>
to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a -
in front for negative infinity).
#include <limits>
//...
std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();
As noted in the comments, min()
returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.
There is of course the std::max_element
and min_element functions (defined in <algorithm>
) which may be a better choice for finding the largest or smallest value in an array.
My mistake, I shouldn't have used a method inside a LINQ query.
Correct code:
using Microsoft.AspNet.Identity;
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
DATABASE
MongoDB states a nice example:
To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:
use myDB
use myNewDB
Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases
COLLECTIONS
Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.
Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"
>No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
firstname). This one is up for debate according to a few people
around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
readability of your collection name by adding underscores or
camelCasing your collection name is probably too long or should use
periods as appropriate which is the standard for collection
categorization.Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.
Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html
For collections I'm following these suggested patterns until I find official MongoDB documentation.
If you don't have another time interval bigger than days:
int days = (int) (milliseconds / (1000*60*60*24));
If you have weeks too:
int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));
It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.
What Tyler Rinker says is correct:
AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0
will do just this.
What you are originally doing is that you are taking from airquality
all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.
SELECT name,
type
FROM dbo.sysobjects
WHERE (type = 'P')
Here would be an option:
+(int)getId{
static int id;
//Do anything you need to update the ID here
return id;
}
Note that this method will be the only method to access id, so you will have to update it somehow in this code.
hasOwnProperty() is a nice property to validate object keys. Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true
You could do this:
import re
import string
set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
for x in set1:
x.replace('.good',' ')
x.replace('.bad',' ')
x = re.sub('\.good$', '', x)
x = re.sub('\.bad$', '', x)
print(x)
The answer is NEVER! (unless you really know what you're doing)
9/10 times the solution can be resolved with a proper understanding of encoding/decoding.
1/10 people have an incorrectly defined locale or environment and need to set:
PYTHONIOENCODING="UTF-8"
in their environment to fix console printing problems.
(struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:sys.setdefaultencoding("utf-8")
str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC")
In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
(My console is configured as UTF-8, so "€" = '\xe2\x82\xac'
, hence exception on \xe2
)
or
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into codesys.setdefaultencoding("utf-8")
also has a side effect of appearing to fix sys.setdefaultencoding("utf-8")
sys.stdout.encoding
, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING
to fix the console encoding.
Example:
$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()
$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€
People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError
exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.
From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/
def welcome_message(byte_string):
try:
return u"%s runs your business" % byte_string
except UnicodeError:
return u"%s runs your business" % unicode(byte_string,
encoding=detect_encoding(byte_string))
print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))
Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.
Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.
While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte
For Linux
Check you have installed latest version of chrome brwoser-> chromium-browser -version
If not, install latest version of chrome sudo apt-get install chromium-browser
get appropriate version of chrome driver from here
Unzip the chromedriver.zip
Move the file to /usr/bin
directory sudo mv chromedriver /usr/bin
Goto /usr/bin
directory cd /usr/bin
Now, you would need to run something like sudo chmod a+x chromedriver
to mark it executable.
finally you can execute the code.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.google.com")
print driver.page_source.encode('utf-8')
driver.quit()
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
It's possible to do this without using extra JS code using the data-collapse and data-target attributes on the a link.
e.g.
<a class="btn" data-toggle="collapse" data-target="#viewdetails">View details »</a>
I solved it with just using the +foo, to convert the string.
Keep in mind it's not great for readability (dirty fix).
console.log( +'1' )
// 1 (int)
In 24 october 2016 Taylor Otwell the Author of Laravel announced on is Twitter
"utf8mb4" will be the default MySQL character set in Laravel 5.4 for better emoji support. Taylor Otwell Twitter Post
which before version 5.4 the character set was utf8
During this century many web app, include chat or some kind platform to allow their users to converses, and many people like to use emoji or smiley. and this are some kind of super characters that require more spaces to be store and that is only possible using utf8mb4
as the charset. That is the reason why they migrate to utf8mb4
just for space purpose.
if you look up in the Illuminate\Database\Schema\Builder
class you will see that the $defaultStringLength
is set to 255, and to modify that you can procede through the Schema
Facade and call the defaultStringLength
method and pass the new length.
to perform that change call that method within your AppServiceProvider
class which is under the app\providers subdirectory like this
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// all other code ...
Schema::defaultStringLength(191);
}
// and all other code goes here
}
I will suggest to use 191 as the value just because MySQL support 767 bytes, and because 767 / 4
which is the number of byte take by each multibyte character you will get 191
.
You can learn more here The utf8mb4 Character Set (4-Byte UTF-8 Unicode Encoding) Limits on Table Column Count and Row Size
Your old version of the app that you are installing has dependent libraries / jars that have been changed. I ran into this issue when updating other jar files that my app was refrencing.
You will need to Uninstall your old version and then you should have no more issues...
Settings-->Applications-->Manage Applications-->[Find and Uninstall your App]
INSTALL_FAILED_DEXOPT errors should not erupt. Like
[2011-06-14 01:23:40 - ProtectYourself] Installing ProtectYourself.apk...
[2011-06-14 01:24:26 - ProtectYourself] Installation error: INSTALL_FAILED_DEXOPT
[2011-06-14 01:24:26 - ProtectYourself] Please check logcat output for more details.
[2011-06-14 01:24:26 - ProtectYourself] Launch canceled!
Whoo hoo.
[vrk:Cloud ID="cTags" runat="server" DataTextField="Tag" DataWeightField="Total"
Width="100%" DataHrefField="Tag" DataHrefFormatString="~/tags.aspx?tag={0}"]
[/vrk:Cloud]
[!--if anybody would like to change the control's color contact with FLORJON--]
I was going to try something like this:
[Range(typeof(decimal), ((double)0).ToString(), ((double)decimal.MaxValue).ToString(), ErrorMessage = "Amount must be greater than or equal to zero.")]
The problem with doing this, though, is that the compiler wants a constant expression, which disallows ((double)0).ToString()
. The compiler will take
[Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")]
I composed this for my own use-case (es5 environment), thought this might be useful for someone, so here it is:
function deepCompare(obj1, obj2) {
var diffObj = Array.isArray(obj2) ? [] : {}
Object.getOwnPropertyNames(obj2).forEach(function(prop) {
if (typeof obj2[prop] === 'object') {
diffObj[prop] = deepCompare(obj1[prop], obj2[prop])
// if it's an array with only length property => empty array => delete
// or if it's an object with no own properties => delete
if (Array.isArray(diffObj[prop]) && Object.getOwnPropertyNames(diffObj[prop]).length === 1 || Object.getOwnPropertyNames(diffObj[prop]).length === 0) {
delete diffObj[prop]
}
} else if(obj1[prop] !== obj2[prop]) {
diffObj[prop] = obj2[prop]
}
});
return diffObj
}
This might be not really efficient, but will output an object with only different props based on second Obj.
We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.
You can install Guzzle through composer
composer require guzzlehttp/guzzle:~6.0
Or you can specify Guzzle as a dependency in your project's existing composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
Example code in laravel 5 using Guzzle as shown below,
use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
$client = new Client();
$res = $client->request('POST', 'https://url_to_the_api', [
'form_params' => [
'client_id' => 'test_id',
'secret' => 'test_secret',
]
]);
echo $res->getStatusCode();
// 200
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- core CSS -->
<link href="http://webdesign9.in/css/bootstrap.min.css" rel="stylesheet">
<link href="http://webdesign9.in/css/font-awesome.min.css" rel="stylesheet">
<link href="http://webdesign9.in/css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body class="homepage">
<header id="header">
<nav class="navbar navbar-inverse" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" title="Web Design Company in Mumbai" href="index.php"><img src="images/logo.png" alt="The Best Web Design Company in Mumbai" /></a>
</div>
<div class="collapse navbar-collapse navbar-right">
<ul class="nav navbar-nav">
<li class="active"><a href="index.php">Home</a></li>
<li><a href="about.php">About Us</a></li>
<li><a href="services.php">Services</a></li>
<li><a href="term-condition.php">Terms & Condition</a></li></li>
<li><a href="contact.php">Contact</a></li>
</ul>
</div>
</div><!--/.container-->
</nav><!--/nav-->
</header><!--/header-->
<script src="http://webdesign9.in/js/jquery.js"></script>
<script src="http://webdesign9.in/js/bootstrap.min.js"></script>
</body>
</html>
What about /disable
, and /enable
switch for a /change
command?
schtasks.exe /change /s <machine name> /tn <task name> /disable
schtasks.exe /change /s <machine name> /tn <task name> /enable
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
You could use cut
df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf),
labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
set.seed(24)
df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
I had the same problem of @rutherford, today the new phpMyAdmin's 3.4.11.1 GUI is different, so I figure out it's better if someone improves the answers with updated info.
Full mysql logs can be found in:
"Status"->"Binary Log"
This is the answer, doesn't matter if you're using MAMP, XAMPP, LAMP, etc.
For Show Current Date and Time on Textview
/// For Show Date
String currentDateString = DateFormat.getDateInstance().format(new Date());
// textView is the TextView view that should display it
textViewdate.setText(currentDateString);
/// For Show Time
String currentTimeString = DateFormat.getTimeInstance().format(new Date());
// textView is the TextView view that should display it
textViewtime.setText(currentTimeString);
Check full Code Android – Display the current date and time in an Android Studio Example with source code
In your application android manifest file, under the application tag you can try several of these themes.
Replace
<application
android:theme="@style/AppTheme" >
with different themes defined by the android system. They can be like:-
android:theme="@android:style/Theme.Black"
android:theme="@android:style/Theme.DeviceDefault"
android:theme="@android:style/Theme.DeviceDefault.Dialog"
android:theme="@android:style/Theme.Holo"
android:theme="@android:style/Theme.Translucent"
Each of these themes will have a different effect on your application like the DeviceDefault.Dialog will make your application look like a dialog box. You should try more of these. You can have a look from the android sdk or simply use auto complete in Eclipse IDE to explore the various available options.
A correct way to define your own theme would be to edit the styles.xml
file present in the resources folder of your application.
SELECT object_definition (OBJECT_ID(N'dbo.vEmployee'))
@kris-van-bael
For those having issues with selection highlight for the top and bottom row where the background rectangle shows up on selection you need to set the selector for your listview to transparent color.
listView.setSelector(R.color.transparent);
In color.xml just add the following -
<color name="transparent">#00000000</color>
You can use select into inside of a PLSQL block such as below.
Declare
l_variable assignment%rowtype
begin
select *
into l_variable
from assignment;
exception
when no_data_found then
dbms_output.put_line('No record avialable')
when too_many_rows then
dbms_output.put_line('Too many rows')
end;
This code will only work when there is exactly 1 row in assignment. Usually you will use this kind of code to select a specific row identified by a key number.
Declare
l_variable assignment%rowtype
begin
select *
into l_variable
from assignment
where ID=<my id number>;
exception
when no_data_found then
dbms_output.put_line('No record avialable')
when too_many_rows then
dbms_output.put_line('Too many rows')
end;
Regex for integer and floating point numbers:
^[+-]?\d*\.\d+$|^[+-]?\d+(\.\d*)?$
A number can start with a period (without leading digits(s)), and a number can end with a period (without trailing digits(s)). Above regex will recognize both as correct numbers.
A . (period) itself without any digits is not a correct number. That's why we need two regex parts there (separated with a "|").
Hope this helps.
This can also happen if CMAKE_FIND_ROOT_PATH
is set as different from BOOST_ROOT
.
I faced the same issue that in spite of setting BOOST_ROOT
, I was getting the error.
But for cross compiling for ARM I was using Toolchain-android.cmake in which I had (for some reason):
set(BOOST_ROOT "/home/.../boost")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --sysroot=${SYSROOT}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --sysroot=${SYSROOT} -I${SYSROOT}/include/libcxx")
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
set(CMAKE_FIND_ROOT_PATH "${SYSROOT}")
CMAKE_FIND_ROOT_PATH
seems to be overriding BOOST_ROOT
which was causing the issue.