The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.
You don't want to include cpp
files. You want to include header files.
The header file should just have the class definition. The corresponding cpp
file, which you will compile separately, will have the function definition.
fun.hpp:
#include <iostream>
class classA {
friend void funct();
public:
classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
int propa;
int propb;
void outfun(){
std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
}
};
fun.cpp:
#include "fun.hpp"
using namespace std;
void funct(){
cout<<"enter funct"<<endl;
classA tmp(1,2);
tmp.outfun();
cout<<"exit funct"<<endl;
}
mainfile.cpp:
#include <iostream>
#include "fun.hpp"
using namespace std;
int main(int nargin,char* varargin[]) {
cout<<"call funct"<<endl;
funct();
cout<<"exit main"<<endl;
return 0;
}
Note that it is generally recommended to avoid using namespace std
in header files.
The answer to the question is not deleting the rows from a table but it is the the tempDB space that is being taken up due to an active transaction. this happens mostly when there is a merge (upsert) is being run where we try to insert update and delete the transactions. The only option is is to make sure the DB is set to simple recovery model and also increase the file to the maximum space (Add an other file group). Although this has its own advantages and disadvantages these are the only options.
The other option that you have is to split the merge(upsert) into two operations. one that does the insert and the other that does the update and delete.
onSaveInstanceState()
is a method used to store data before pausing the activity.Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.
onRestoreInstanceState()
is method used to retrieve that data back.Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).
Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause()
method of Activity as a bundle & in onResume()
method call the onRestoreInstanceState()
method .
Please see :
How to use onSavedInstanceState example please
http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/
I received this error when I had a config file with <?php
on the second line instead of the first.
A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.
Indeed we use a custom Application Pool with a specific Identity to meet our needs.
In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings... The Application Pool was "DefaultAppPool" instead of our custom Application Pool.
Setting the correct application pool solved the problem.
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:@"value3" forKey:@"key3"];
...then store it to a file
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:@"key1"];
...check if a key exists
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
What about this regex: \\[^\\]+$
Regex isn't needed, nor is plugins
if (isNaN($('#Field').val() / 1) == false) {
your code here
}
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
Assuming that your script is named x.php, try this
<?php
function display($s) {
echo $s;
}
?>
<html>
<body>
<form method="post" action="x.php">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
display();
}
?>
</body>
</html>
What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.
Either break your files up into smaller parts, like setting the error levels in one file and then include
ing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.
Because the target of the link matches the name of the iframe, the link will open in the iframe. Try this:
<iframe src="http://stackoverflow.com/" name="iframe_a">
<p>Your browser does not support iframes.</p>
</iframe>
<a href="http://www.cnn.com" target="iframe_a">www.cnn.com</a>
Here is a function that does the job quite well. I could not get the Best Answer above to work.
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
Then to access it, create the variable like so:
var results = $.getValues("url string");
Try
SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
group_concat(li.percentage ORDER BY li.percentage)
FROM table_views li
GROUP BY client_id
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat
Here is a function to convert UNICODE (ISO_8859_1) to UTF-8
public static String String_ISO_8859_1To_UTF_8(String strISO_8859_1) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strISO_8859_1.length(); i++) {
final char ch = strISO_8859_1.charAt(i);
if (ch <= 127)
{
stringBuilder.append(ch);
}
else
{
stringBuilder.append(String.format("%02x", (int)ch));
}
}
String s = stringBuilder.toString();
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
String strUTF_8 =new String(data, StandardCharsets.UTF_8);
return strUTF_8;
}
TEST
String strA_ISO_8859_1_i = new String("??????".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
System.out.println("ISO_8859_1 strA est = "+ strA_ISO_8859_1_i + "\n String_ISO_8859_1To_UTF_8 = " + String_ISO_8859_1To_UTF_8(strA_ISO_8859_1_i));
RESULT
ISO_8859_1 strA est = اÙغÙا٠String_ISO_8859_1To_UTF_8 = ??????
The answer for git branch -r --contains <commit>
works well for normal remote branches, but if the commit is only in the hidden head
namespace that GitHub creates for PRs, you'll need a few more steps.
Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r
doesn't know about PR #42 because refs like refs/pull/42/head
aren't listed as a remote branch by default.
In .git/config
for the [remote "origin"]
section add a new line:
fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
(This gist has more context.)
Then when you git fetch
you'll get all the PR branches, and when you run git branch -r --contains <commit>
you'll see origin/pr/42
contains the commit.
I would suggest using the functions below since the ones mentioned by @bigh_29 transforms my guids into new ones (for reasons I don't understand). Also, these are a little bit faster in the tests I did on my tables. https://gist.github.com/damienb/159151
DELIMITER |
CREATE FUNCTION uuid_from_bin(b BINARY(16))
RETURNS CHAR(36) DETERMINISTIC
BEGIN
DECLARE hex CHAR(32);
SET hex = HEX(b);
RETURN LOWER(CONCAT(LEFT(hex, 8), '-', MID(hex, 9,4), '-', MID(hex, 13,4), '-', MID(hex, 17,4), '-', RIGHT(hex, 12)));
END
|
CREATE FUNCTION uuid_to_bin(s CHAR(36))
RETURNS BINARY(16) DETERMINISTIC
RETURN UNHEX(CONCAT(LEFT(s, 8), MID(s, 10, 4), MID(s, 15, 4), MID(s, 20, 4), RIGHT(s, 12)))
|
DELIMITER ;
The problem with the accepted answer is that it now depends on the caller for the object to be properly validated. I would either remove the RangeAttribute and do the range validation inside the Validate method or I would create a custom attribute subclassing RangeAttribute that takes the name of the required property as an argument on the constructor.
For example:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class RangeIfTrueAttribute : RangeAttribute
{
private readonly string _NameOfBoolProp;
public RangeIfTrueAttribute(string nameOfBoolProp, int min, int max) : base(min, max)
{
_NameOfBoolProp = nameOfBoolProp;
}
public RangeIfTrueAttribute(string nameOfBoolProp, double min, double max) : base(min, max)
{
_NameOfBoolProp = nameOfBoolProp;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_NameOfBoolProp);
if (property == null)
return new ValidationResult($"{_NameOfBoolProp} not found");
var boolVal = property.GetValue(validationContext.ObjectInstance, null);
if (boolVal == null || boolVal.GetType() != typeof(bool))
return new ValidationResult($"{_NameOfBoolProp} not boolean");
if ((bool)boolVal)
{
return base.IsValid(value, validationContext);
}
return null;
}
}
My guess is that the directory ~/bin/sbt/bin is not in your PATH.
To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:
./sbt
This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example). Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command... Or one that executes 'rm -rf .'...
That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository.
One way we do this in our application is using IDisposable and then with using(){}
blocks to ensure the cursor is reset when done.
public class OverrideCursor : IDisposable
{
public OverrideCursor(Cursor changeToCursor)
{
Mouse.OverrideCursor = changeToCursor;
}
#region IDisposable Members
public void Dispose()
{
Mouse.OverrideCursor = null;
}
#endregion
}
and then in your code:
using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
// Do work...
}
The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.
Update
To prevent the cursor flickering you can do:
public class OverrideCursor : IDisposable
{
static Stack<Cursor> s_Stack = new Stack<Cursor>();
public OverrideCursor(Cursor changeToCursor)
{
s_Stack.Push(changeToCursor);
if (Mouse.OverrideCursor != changeToCursor)
Mouse.OverrideCursor = changeToCursor;
}
public void Dispose()
{
s_Stack.Pop();
Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;
if (cursor != Mouse.OverrideCursor)
Mouse.OverrideCursor = cursor;
}
}
You just need:
if (!empty($_POST['search_term']) && !empty($_POST['postcode']))
isset && !empty
is redundant.
std::map
takes up to four template type arguments, the third one being a comparator. E.g.:
struct cmpByStringLength {
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// ...
std::map<std::string, std::string, cmpByStringLength> myMap;
Alternatively you could also pass a comparator to map
s constructor.
Note however that when comparing by length you can only have one string of each length in the map as a key.
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
Explanation of stereotypes :
@Service
- Annotate all your service classes with @Service. This layer knows the unit of work. All your business logic will be in Service classes. Generally methods of service layer are covered under transaction. You can make multiple DAO calls from service method, if one transaction fails all transactions should rollback.@Repository
- Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.@Component
- Annotate your other components (for example REST resource classes) with component stereotype.@Autowired
- Let Spring auto-wire other beans into your classes using @Autowired annotation. @Component
is a generic stereotype for any Spring-managed component. @Repository
, @Service
, and @Controller
are specializations of @Component
for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
Originally answered here.
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
Small addition to @user995502's answer on how to run the program.
g++ player.cpp main.cpp -o main.out && ./main.out
This function will be used get the data from url in form of HttpResponse object.
public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}
Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.
String jsonString =
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/ blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
jsonElementForJavaObject, JsonJavaModel.class);
This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:
public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel> {
@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
JsonDeserializationContext arg2) throws JsonParseException {
final JsonJavaModel jsonJavaModel= new JsonJavaModel();
JsonObject object = json.getAsJsonObject();
try {
jsonJavaModel.content = object.get("Content").getAsString()
jsonJavaModel.title = object.get("Title").getAsString()
} catch (Exception e) {
e.printStackTrace();
}
return jsonJavaModel;
}
Include Gson library and org.apache.http.util.EntityUtils;
Try this:
var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();
Possible duplicate with: How do I use jQuery to ignore case when selecting
The Magic
field of the IMAGE_OPTIONAL_HEADER
(though there is nothing optional about the header in Windows executable images (DLL/EXE files)) will tell you the architecture of the PE.
Here's an example of grabbing the architecture from a file.
public static ushort GetImageArchitecture(string filepath) {
using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
using (var reader = new System.IO.BinaryReader(stream)) {
//check the MZ signature to ensure it's a valid Portable Executable image
if (reader.ReadUInt16() != 23117)
throw new BadImageFormatException("Not a valid Portable Executable image", filepath);
// seek to, and read, e_lfanew then advance the stream to there (start of NT header)
stream.Seek(0x3A, System.IO.SeekOrigin.Current);
stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);
// Ensure the NT header is valid by checking the "PE\0\0" signature
if (reader.ReadUInt32() != 17744)
throw new BadImageFormatException("Not a valid Portable Executable image", filepath);
// seek past the file header, then read the magic number from the optional header
stream.Seek(20, System.IO.SeekOrigin.Current);
return reader.ReadUInt16();
}
}
The only two architecture constants at the moment are:
0x10b - PE32
0x20b - PE32+
Cheers
UPDATE
It's been a while since I posted this answer, yet I still see that it gets a few upvotes now and again so I figured it was worth updating. I wrote a way to get the architecture of a Portable Executable
image, which also checks to see if it was compiled as AnyCPU
. Unfortunately the answer is in C++, but it shouldn't be too hard to port to C# if you have a few minutes to look up the structures in WinNT.h
. If people are interested I'll write a port in C#, but unless people actually want it I wont spend much time stressing about it.
#include <Windows.h>
#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))
typedef enum _pe_architecture {
PE_ARCHITECTURE_UNKNOWN = 0x0000,
PE_ARCHITECTURE_ANYCPU = 0x0001,
PE_ARCHITECTURE_X86 = 0x010B,
PE_ARCHITECTURE_x64 = 0x020B
} PE_ARCHITECTURE;
LPVOID GetOffsetFromRva(IMAGE_DOS_HEADER *pDos, IMAGE_NT_HEADERS *pNt, DWORD rva) {
IMAGE_SECTION_HEADER *pSecHd = IMAGE_FIRST_SECTION(pNt);
for(unsigned long i = 0; i < pNt->FileHeader.NumberOfSections; ++i, ++pSecHd) {
// Lookup which section contains this RVA so we can translate the VA to a file offset
if (rva >= pSecHd->VirtualAddress && rva < (pSecHd->VirtualAddress + pSecHd->Misc.VirtualSize)) {
DWORD delta = pSecHd->VirtualAddress - pSecHd->PointerToRawData;
return (LPVOID)MKPTR(pDos, rva - delta);
}
}
return NULL;
}
PE_ARCHITECTURE GetImageArchitecture(void *pImageBase) {
// Parse and validate the DOS header
IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)pImageBase;
if (IsBadReadPtr(pDosHd, sizeof(pDosHd->e_magic)) || pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
return PE_ARCHITECTURE_UNKNOWN;
// Parse and validate the NT header
IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
if (IsBadReadPtr(pNtHd, sizeof(pNtHd->Signature)) || pNtHd->Signature != IMAGE_NT_SIGNATURE)
return PE_ARCHITECTURE_UNKNOWN;
// First, naive, check based on the 'Magic' number in the Optional Header.
PE_ARCHITECTURE architecture = (PE_ARCHITECTURE)pNtHd->OptionalHeader.Magic;
// If the architecture is x86, there is still a possibility that the image is 'AnyCPU'
if (architecture == PE_ARCHITECTURE_X86) {
IMAGE_DATA_DIRECTORY comDirectory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
if (comDirectory.Size) {
IMAGE_COR20_HEADER *pClrHd = (IMAGE_COR20_HEADER*)GetOffsetFromRva(pDosHd, pNtHd, comDirectory.VirtualAddress);
// Check to see if the CLR header contains the 32BITONLY flag, if not then the image is actually AnyCpu
if ((pClrHd->Flags & COMIMAGE_FLAGS_32BITREQUIRED) == 0)
architecture = PE_ARCHITECTURE_ANYCPU;
}
}
return architecture;
}
The function accepts a pointer to an in-memory PE image (so you can choose your poison on how to get it their; memory-mapping or reading the whole thing into memory...whatever).
I tried all solution here and in other posts, but nothing helped.
The only answer helped me:
Adding [FromBody] attribute before decleration of parameter in function signature:
[Route("MyFunc")]
public string MyFunc([FromBody] string[] obj)
An alternative problem may be your internet connection. Obvious maybe, but took me a few minutes to figure out my wifi was down :)
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
Start with the triangle...
*
**
***
****
representing 1+2+3+4 so far. Cut the triangle in half along one dimension...
*
**
* **
** **
Rotate the smaller part 180 degrees, and stick it on top of the bigger part...
**
*
*
**
**
**
Close the gap to get a rectangle.
At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.
Whatever the base of the triangle, the width of your rectangle is (base / 2)
and the height is (base + 1)
, giving ((base + 1) * base) / 2
.
However, my base
is your n-1
, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.
Here is the documentation on the drawer and it appears that you can configure it to pull out from the left or right.
Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right. (Or start/end on platform versions that support layout direction.)
http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html
The offending lines are the following:
MaxConnections=90
InitialConnections=80
You can increase the values to allow more connections.
My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...
=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")
Advisably sheets to be adjacent to avoid unanticipated results.
Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)
Dim sStarSheet As String, sEndSheet As String, sAddress As String
Dim lColonPos As Long, lExclaPos As Long, cnt As Long
lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets
sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name
sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address
cnt = 0
For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
Next
CountIf3D = cnt
End Function
Network tracing also available for next objects (see article on msdn)
Put next lines of code to the configuration file
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="includehex" maxdatasize="1024">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Cache">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Http">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.WebSockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Cache" value="Verbose"/>
<add name="System.Net.Http" value="Verbose"/>
<add name="System.Net.Sockets" value="Verbose"/>
<add name="System.Net.WebSockets" value="Verbose"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log"
/>
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
data attributes are commonly used for a variety of interactions. Typically via javascript. They do not affect anything regarding site behavior and stand as a convenient method to pass data for whatever purpose needed. Here is an article that may clear things up:
http://ejohn.org/blog/html-5-data-attributes/
You can create a data attribute by prefixing data-
to any standard attribute safe string (alphanumeric with no spaces or special characters). For example, data-id
or in this case data-reactid
1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:
$ git push
Username for 'https://github.com': # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token
Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line
import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
componentDidMount(){
document.title = "dfsdfsdfsd"
}
render(){
return(
<b> test </b>
)
}
}
ReactDOM.render(
<Doc />,
document.getElementById('container')
);
This works for me.
Edit: If you're using webpack-dev-server set inline to true
You can change your code to this:
$where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
$this->db
->select('*')
->from('library')
->where('library.rating >=', $form['slider'])
->where('library.votes >=', '1000')
->where('library.language !=', 'German')
->where($where_au)
->where('library.release_year >=', $year_start)
->where('library.release_year <=', $year_end)
->join('rating_repo', 'library.id = rating_repo.id');
Tip: to watch the generated query you can use
echo $this->db->last_query(); die();
import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date
> True
Assuming you're using Microsoft SQL Server Management Studio
URL Encoding the data works as well for me
For example
var data = '<b>Hello</b>'
In Browser call encodeURIComponent(data) before posting
On Server call HttpUtility.UrlDecode(received_data) to decode
That way you can control exactly which fields area allowed to have html
;(function ($) {
$.fn.bootselect = function (options) {
this.each(function () {
var os = jQuery(this).find('option');
var parent = this.parentElement;
var css = jQuery(this).attr('class').split('input').join('btn').split('form-control').join('');
var vHtml = jQuery(this).find('option[value="' + jQuery(this).val() + '"]').html();
var html = '<div class="btn-group" role="group">' + '<button type="button" data-toggle="dropdown" value="1" class="btn btn-default ' + css + ' dropdown-toggle">' +
vHtml + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">';
var i = 0;
while (i < os.length) {
html += '<li><a href="#" data-value="' + jQuery(os[i]).val() + '" html-attr="' + jQuery(os[i]).html() + '">' + jQuery(os[i]).html() + '</a></li>';
i++;
}
html += '</ul>' + '</div>';
var that = this;
jQuery(parent).append(html);
jQuery(parent).find('ul.dropdown-menu > li > a').on('click', function () {
jQuery(parent).find('button.btn').html(jQuery(this).html() + '<span class="caret"></span>');
jQuery(that).find('option[value="' + jQuery(this).attr('data-value') + '"]')[0].selected = true;
jQuery(that).trigger('change');
});
jQuery(this).hide();
});
};
}(jQuery));
jQuery('.bootstrap-select').bootselect();
Notice: This is for MySQLdb module in Python.
For a SELECT
statement, there shouldn't be an exception for an empty recordset. Just an empty list ([]
) for cursor.fetchall()
and None
for cursor.fetchone()
.
For any other statement, e.g. INSERT
or UPDATE
, that doesn't return a recordset, you can neither call fetchall()
nor fetchone()
on the cursor. Otherwise, an exception will be raised.
There's one way to distinguish between the above two types of cursors:
def yield_data(cursor):
while True:
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT, yield data
yield cursor.fetchall()
# Or yield column names with
# yield [col[0] for col in cursor.description]
# Go to the next recordset
if not cursor.nextset():
# End of recordsets
return
Regex is compiled so for speed create it once and reuse it.
The new takes longer than the IsMatch.
This only checks for all digits.
It does not check for range.
If you need to test range then TryParse is the way to go.
private static Regex regexInt = new Regex("^\\d+$");
static bool CheckReg(string value)
{
return regexInt.IsMatch(value);
}
I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/
Make sure your django session backend is configured properly in settings.py. Then try this,
class CustomMiddleware(object):
def process_request(self,request:HttpRequest):
get_token(request)
Add this middleware in settings.py
under MIDDLEWARE_CLASSES
or MIDDLEWARE
depending on the django version
get_token - Returns the CSRF token required for a POST form. The token is an alphanumeric value. A new token is created if one is not already set.
For newbies like me, who end up on this question: This error also happens if you attempt to call .select2() on an element retrieved using pure javascript and not using jQuery.
This fails with the "select2 is not a function" error:
document.getElementById('e9').select2();
This works:
$("#e9").select2();
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
Sorry for answering again on that question... I needed to embed the image.
I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.
Sourcecode of the screenshot:
@Override
protected void onDraw( Canvas canvas ) {
for( int i = 0; i < 20; i++ ) {
int startSize = 10;
int curSize = i + startSize;
paint.setTextSize( curSize );
String text = i + startSize + " - " + TEXT_SNIPPET;
Rect bounds = new Rect();
paint.getTextBounds( text, 0, text.length(), bounds );
float top = STEP_DISTANCE * i + curSize;
bounds.top += top;
bounds.bottom += top;
canvas.drawRect( bounds, bgPaint );
canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
}
}
I had this problem and i searched for it then i made my own method using some java keywords just need to pass String variable as parameter and get output as proper titled String.
public class Main
{
public static void main (String[]args)
{
String st = "pARVeEN sISHOsIYA";
String mainn = getTitleCase (st);
System.out.println (mainn);
}
public static String getTitleCase(String input)
{
StringBuilder titleCase = new StringBuilder (input.length());
boolean hadSpace = false;
for (char c:input.toCharArray ()){
if(Character.isSpaceChar(c)){
hadSpace = true;
titleCase.append (c);
continue;
}
if(hadSpace){
hadSpace = false;
c = Character.toUpperCase(c);
titleCase.append (c);
}else{
c = Character.toLowerCase(c);
titleCase.append (c);
}
}
String temp=titleCase.toString ();
StringBuilder titleCase1 = new StringBuilder (temp.length ());
int num=1;
for (char c:temp.toCharArray ())
{ if(num==1)
c = Character.toUpperCase(c);
titleCase1.append (c);
num=0;
}
return titleCase1.toString ();
}
}
Just so you can find it next time, here is how you search for the enumerable Linq extensions. The methods are static methods of Enumerable, thus Enumerable.Any, Enumerable.Where and Enumerable.Exists.
As the third returns no usable result, I found that you meant List.Exists, thus:
I also recommend hookedonlinq.com as this is has very comprehensive and clear guides, as well clear explanations of the behavior of Linq methods in relation to deferness and lazyness.
I want to make sure this is out there, because it's so hard to get right:
using System.Runtime.InteropServices; //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid =
((GuidAttribute)Assembly.GetExecutingAssembly().
GetCustomAttributes(typeof(GuidAttribute), false).
GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );
// Need a place to store a return value in Mutex() constructor call
bool createdNew;
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule =
new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
, null)
, MutexRights.FullControl
, AccessControlType.Allow
);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact that the mutex was abandoned in another process,
// it will still get acquired
hasHandle = true;
}
// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statement
if(hasHandle)
mutex.ReleaseMutex();
}
}
}
Single line works just fine:
<a href="http://example.com/"
onclick="return confirm('Please click on OK to continue.');">click me</a>
Adding another line with a different link on the same page works fine too:
<a href="http://stackoverflow.com/"
onclick="return confirm('Click on another OK to continue.');">another link</a>
Try
myString = 'abcabc'
myString.find('a')
This will give you the index!!!
According to MySQL documentation, you should be able to just enclose that datetime string in single quotes, ('YYYY-MM-DD HH:MM:SS') and it should work. Look here: Date and Time Literals
So, in your case, the command should be as follows:
UPDATE products SET former_date='2011-12-18 13:17:17' WHERE id=1
This is different for each browser, in IE and windows you need to create what they call a pluggable protocol handler.
The basic steps are as follows:
See About Asynchronous Pluggable Protocols on MSDN for more details on the windows side. There is also a sample in the windows SDK.
A quick google also showed this article on codeproject: http://www.codeproject.com/KB/IP/DataProtocol.aspx.
Finally, as a security guy I have to point out that this code needs to be battle hardened. It's at a high risk because to do it reliably you can't do it in managed code and have to do it in C++ (I suppose you could use VB6). You should consider whether you really need to do this and if you do, design it carefully and code it securely. An attacker can easily control the content that gets passed to you by simply including a link on a page. For example if you have a simple buffer overflow then nobody better do this: <a href="custom:foooo{insert long string for buffer overflow here}"> Click me for free porn</a>
Strongly consider using strsafe and the new secure CRT methods included in the VC8 and above compilers. See http://blogs.msdn.com/michael_howard/archive/2006/02/27/540123.aspx if you have no idea what I'm talking about.
watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.
You can set read watchpoints on memory locations:
gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions:
gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.
So you have to expand them yourself:
gdb$ print $ebx
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()
Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.
gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.
One option would be:
SET SERVEROUTPUT ON
EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));
The first solution is to use the java.util.Random
class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
<form onsubmit="alert(this.submitted); return false;">
<input onclick="this.form.submitted=this.value;" type="submit" value="Yes" />
<input onclick="this.form.submitted=this.value;" type="submit" value="No" />
</form>
jsfiddle for the same
Here are some things you can do with UILabel
and its borders.
Here is the code for those labels:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label5: UILabel!
@IBOutlet weak var label6: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// label 1
label1.layer.borderWidth = 1.0
// label 2
label2.layer.borderWidth = 5.0
label2.layer.borderColor = UIColor.blue.cgColor
// label 3
label3.layer.borderWidth = 2.0
label3.layer.cornerRadius = 8
// label 4
label4.backgroundColor = UIColor.cyan
// label 5
label5.backgroundColor = UIColor.red
label5.layer.cornerRadius = 8
label5.layer.masksToBounds = true
// label 6
label6.layer.borderWidth = 2.0
label6.layer.cornerRadius = 8
label6.backgroundColor = UIColor.yellow
label6.layer.masksToBounds = true
}
}
Note that in Swift there is no need to import QuartzCore
.
See also
Yes, define log4j.configuration
property
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
Note, that property value must be a URL.
For more read section 'Default Initialization Procedure' in Log4j manual.
There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.
app.get('/category', function(req, res) {
var string = encodeURIComponent('something that would break');
res.redirect('/?valid=' + string);
});
You can snag that in your other route by getting the parameters sent by using req.query
.
app.get('/', function(req, res) {
var passedVariable = req.query.valid;
// Do something with variable
});
For more dynamic way you can use the url
core module to generate the query string for you:
const url = require('url');
app.get('/category', function(req, res) {
res.redirect(url.format({
pathname:"/",
query: {
"a": 1,
"b": 2,
"valid":"your string here"
}
}));
});
So if you want to redirect all req query string variables you can simply do
res.redirect(url.format({
pathname:"/",
query:req.query,
});
});
And if you are using Node >= 7.x you can also use the querystring
core module
const querystring = require('querystring');
app.get('/category', function(req, res) {
const query = querystring.stringify({
"a": 1,
"b": 2,
"valid":"your string here"
});
res.redirect('/?' + query);
});
Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:
app.get('/category', function(req, res) {
req.session.valid = true;
res.redirect('/');
});
And later on after the redirect...
app.get('/', function(req, res) {
var passedVariable = req.session.valid;
req.session.valid = null; // resets session variable
// Do something
});
There is also the option of using an old feature of Express, req.flash
. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.
Hopefully that will give you a general idea how to pass information around in an Express application.
You can use the <pre>
tag with innerHTML. The HTML <pre>
element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre
as a selector in your CSS file and style it as desired.
Ex:
var a = '<pre>something something</pre>';
document.body.innerHTML = a;
Try
apt-get -d install <packages>
It is documented in man apt-get
.
Just for clarification; the downloaded packages are located in the apt package cache at
/var/cache/apt/archives
The volume it's on is mounted noexec
.
I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.
public static void main(String... args) throws IOException {
final int runs = 5 * 1000 * 1000;
final ServerSocket ss = new ServerSocket(0);
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket serverConn = ss.accept();
String line = "Hello World!\n";
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
for (int count = 0; count < runs; count++)
br.write(line);
serverConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Socket conn = new Socket("localhost", ss.getLocalPort());
long start = System.nanoTime();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
List<String> responseData = new ArrayList<String>();
while ((line = in.readLine()) != null) {
responseData.add(line);
}
long time = System.nanoTime() - start;
System.out.println("Average time to read a line was " + time / runs + " ns.");
conn.close();
ss.close();
}
prints
Average time to read a line was 158 ns.
If you want to build a StringBuilder, keeping newlines I would suggets the following approach.
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
Still prints
Average time to read a line was 159 ns.
In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.
I think you are trying to toggle the disabled state, in witch case you should use this (from this question):
$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });
It's two steps but I like to do it this way:
First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight
touch -t 0810010000 /tmp/t
Now we can find all files that are newer or older than the above file (going by file modified date. You can also use -anewer for accessed and -cnewer file status changed).
find / -newer /tmp/t
find / -not -newer /tmp/t
You could also look at files between certain dates by creating two files with touch
touch -t 0810010000 /tmp/t1
touch -t 0810011000 /tmp/t2
This will find files between the two dates & times
find / -newer /tmp/t1 -and -not -newer /tmp/t2
Here is my recursive approach:
function visit(object) {
if (isIterable(object)) {
forEachIn(object, function (accessor, child) {
visit(child);
});
}
else {
var value = object;
console.log(value);
}
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
Use title attribute instead of alt
<img
height="90"
width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg12.gif"
title="Image Not Found"
/>
As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.
If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)
AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));
Please note that I'm using ProfileCredentialsProvider
so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.
I figured out that this behaves like a mousedown event:
button:active:hover {}
I realize this is years late, but I thought I could expand on Conor's answer and add a little bit more to the discussion.
Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?
Step 1: Client > Signing up
Before anything else, the user has to sign up. The client posts a HTTP request to the server containing his/her username and password.
Step 2: Server > Handling sign up
The server receives this request and hashes the password before storing the username and password in your database. This way, if someone gains access to your database they won't see your users' actual passwords.
Step 3: Client > User login
Now your user logs in. He/she provides their username/password and again, this is posted as a HTTP request to the server.
Step 4: Server > Validating login
The server looks up the username in the database, hashes the supplied login password, and compares it to the previously hashed password in the database. If it doesn't check out, we may deny them access by sending a 401 status code and ending the request.
Step 5: Server > Generating access token
If everything checks out, we're going to create an access token, which uniquely identifies the user's session. Still in the server, we do two things with the access token:
Henceforth, the cookies will be attached to every request (and response) made between the client and server.
Step 6: Client > Making page requests
Back on the client side, we are now logged in. Every time the client makes a request for a page that requires authorization (i.e. they need to be logged in), the server obtains the access token from the cookie and checks it against the one in the database associated with that user. If it checks out, access is granted.
This should get you started. Be sure to clear the cookies upon logout!
set -x
is fine.
Another way to print each executed command is to use trap
with DEBUG
.
Put this line at the beginning of your script :
trap 'echo "# $BASH_COMMAND"' DEBUG
You can find a lot of other trap
usages here.
This is a dated question but I found an alternate solution to share right from the bootstrap github page. The documentation has not been updated and there are other questions on SO asking for the same solution albeit on slightly different questions. This solution is not specific to your case but as you can see the solution is the <div class="container">
right after <nav class="navbar navbar-default navbar-fixed-top">
but can also be replaced with <div class="container-fluid"
as needed.
<!DOCTYPE html>
<html>
<head>
<title>Navbar right padding broken </title>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-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 href="#/" class="navbar-brand">Hello</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<div class="btn-group navbar-btn" role="group" aria-label="...">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modalLogin">Se connecter</button>
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modalSignin">Créer un compte</button>
</div>
</li>
</ul>
</div>
</div>
</nav>
</body>
</html>
The solution was found on a fiddle on this page: https://github.com/twbs/bootstrap/issues/18362
and is listed as a won't fix in V3.
Change the file phpmyadmin.conf on c:/wamp64/alias/phpmyadmin.conf
php_admin_value upload_max_filesize 512M
php_admin_value post_max_size 512M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360
It's very important you increase the time to 5000 or higher, Thus, the process will not stop when you are uploading a large file.
That works for me.
Surprisingly, I found that none of the answers posted here so far correctly deal with all possible scenarios (e.g., nested dicts, nested lists, None values, etc).
This solution should work across all scenarios:
def flatten_json(json):
def process_value(keys, value, flattened):
if isinstance(value, dict):
for key in value.keys():
process_value(keys + [key], value[key], flattened)
elif isinstance(value, list):
for idx, v in enumerate(value):
process_value(keys + [str(idx)], v, flattened)
else:
flattened['__'.join(keys)] = value
flattened = {}
for key in json.keys():
process_value([key], json[key], flattened)
return flattened
I do it with boolean = !boolean;
You can use index arrays, simply pass your ind_pos
as an index argument as below:
a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])
print(a[ind_pos])
# [88,85,16]
Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).
By using pandas
:
df.time_diff.quantile([0.25,0.5,0.75])
Out[793]:
0.25 0.483333
0.50 0.500000
0.75 0.516667
Name: time_diff, dtype: float64
Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's
As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:
Web Development:
You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.
Data Analysis:
Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.
Machine Learning:
What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.
Computer Vision:
You can do many interesting things such as Face detection, Color detection while using Opencv and Python.
Internet Of Things With Raspberry Pi:
Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!
Game Development:
Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.
Web Scraping:
If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.
Writing Scripts:
If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.
Browser Automation:
Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.
GUI Development:
Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.
Rapid Prototyping:
Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.
Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.
I hope it doesn't get deprecated. While writing <? blah code ?>
is fairly unnecessary and confusable with XHTML, <?=
isn't, for obvious reasons. Unfortunately I don't use it, because short_open_tag seems to be disabled more and more.
Update: I do use <?=
again now, because it is enabled by default with PHP 5.4.0.
See http://php.net/manual/en/language.basic-syntax.phptags.php
People say that Ruby is slow because they compare Ruby programs to programs written in other languages. Maybe the programs you write don't need to be faster. Maybe for the programs you write Ruby isn't the bottleneck that's slowing things down.
Ruby 2.1 compared to Javascript V8
If the table content is too wide (as in this example), there's nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can't.
Some ways you can alter content to make a table more narrow:
white-space: nowrap
on any of the content (or the old nowrap
attribute,
, a nobr
element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down.If the table is too wide but you don't see a good reason for it (the content isn't that wide, etc.), you'll have to provide more information about how you're styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.
try this
$('#element').on('scroll touchmove mousewheel', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
If u r using these methods for initialization then use constructors of class A and pass super keyword inside the constructor of class B.
Or if you want to call a method of super class from the subclass method then you have to use super keyword inside the subclass method like : super.myMethod();
Try request.setAttribute("param",value);
. It worked fine for me.
Please find this code sample:
private void sanitizePrice(ServletRequest request){
if(request.getParameterValues ("price") != null){
String price[] = request.getParameterValues ("price");
for(int i=0;i<price.length;i++){
price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
System.out.println(price[i]);
}
request.setAttribute("price", price);
//request.getParameter("numOfBooks").re
}
}
When I run your program, it doesn't even get me to the point where I can enter the second date.
This is simpler and less error prone.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test001 {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");
System.out.println("Insert first date : ");
Date dt1 = sdf.parse(br.readLine().trim());
System.out.println("Insert second date : ");
Date dt2 = sdf.parse(br.readLine().trim());
long diff = dt2.getTime() - dt1.getTime();
System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);
if (br != null) {
br.close();
}
}
}
You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.
function safePromise(promise) {
return promise.then(data => [ data ]).catch(error => [ null, error ]);
}
Use it like this in ES7 and in an async function:
async function checkItem() {
const [ item, error ] = await safePromise(getItem(id));
if (error) { return null; } // handle error and return
return item; // no error so safe to use item
}
To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset()
syntax. E.g. for the data-frame
df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)
to remove just the a
column you could do
Data <- subset( Data, select = -a )
and to remove the b
and d
columns you could do
Data <- subset( Data, select = -c(d, b ) )
You can remove all columns between d
and b
with:
Data <- subset( Data, select = -c( d : b )
As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset
documentation:
Warning:
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.
you are missing the "btn btn-navbar" section. For example:
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
Take a look to navbar documentation in:
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Another method I sometime use is:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.
I`ve been looking for something like this for ages... So i hope this helps someone!
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
namespace User
{
public static class UserValidation
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonProviders : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
enum LogonTypes : uint
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkCleartext = 8,
NewCredentials = 9
}
public const int ERROR_PASSWORD_MUST_CHANGE = 1907;
public const int ERROR_LOGON_FAILURE = 1326;
public const int ERROR_ACCOUNT_RESTRICTION = 1327;
public const int ERROR_ACCOUNT_DISABLED = 1331;
public const int ERROR_INVALID_LOGON_HOURS = 1328;
public const int ERROR_NO_LOGON_SERVERS = 1311;
public const int ERROR_INVALID_WORKSTATION = 1329;
public const int ERROR_ACCOUNT_LOCKED_OUT = 1909; //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
public const int ERROR_ACCOUNT_EXPIRED = 1793;
public const int ERROR_PASSWORD_EXPIRED = 1330;
public static int CheckUserLogon(string username, string password, string domain_fqdn)
{
int errorCode = 0;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
{
if (!pc.ValidateCredentials(username, password))
{
IntPtr token = new IntPtr();
try
{
if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
{
errorCode = Marshal.GetLastWin32Error();
}
}
catch (Exception)
{
throw;
}
finally
{
CloseHandle(token);
}
}
}
return errorCode;
}
}
I think this is what you want...
Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"
For Each WS In Application.ActiveWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
' about overwriting the original file.
End Sub
If you want an 2d array of integers, which elements are allocated sequentially in memory, you must declare it like
int (*intPtr)[n] = new int[x][n]
where instead of x you can write any dimension, but n must be the same in two places. Example
int (*intPtr)[8] = new int[75][8];
intPtr[5][5] = 6;
cout<<intPtr[0][45]<<endl;
must print 6.
You want style image and Nav with float to each other then use like this
ol.widgets ul
{
list-style-image:url('some-img.gif');
}
ol.widgets ul li
{
float:left;
}
To make it short, it means that you lacked some "dependencies" for the libraries you wanted to use. Before trying to use any kind of library, first it is suggested to look up whether it needs another library in python "family". What do I mean?
Downloading "dlls" is something that I avoid. I had the same problem with another library "kivy". The problem occurred when I wanted to use Python 3.4v instead of 3.5 Everything was working correctly in 3.5 but I just wanted to use the stable version for kivy which is 3.4 as they officially "advise". So, I switched to 3.4 but then I had the very same "dll" error saying lots of things are missing. So I checked the website and learned that I needed to install extra "dependencies" from the official website of kivy, then the problem got solved.
sometimes will b usable this line on any layout or components.
android:background="?attr/selectableItemBackground"
Like as.
<RelativeLayout
android:id="@+id/relative_ticket_checkin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="?attr/selectableItemBackground">
Try Toad for MySQL - its free and its great.
Shows the Computer Name, Use a Button to call it
Dim strHostName As String
strHostName = System.Net.Dns.GetHostName(). MsgBox(strHostName)
Shows the User Name, Use a Button to call it
If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then
Dim parts() As String = Split(My.User.Name, "\") Dim username As String = parts(1) MsgBox(username) End If
For IP Address its little complicated, But I try to explain as much as I can. First write the next code, before Form1_Load but after import section
Public Class Form1
Dim mem As String Private Sub GetIPAddress() Dim strHostName As String Dim strIPAddress As String strHostName = System.Net.Dns.GetHostName() strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString() mem = strIPAddress MessageBox.Show("IP Address: " & strIPAddress) End Sub
Then in Form1_Load Section just call it
GetIPAddress()
Result: On form load it will show a msgbox along with the IP address, for put into Label1.text or some where else play with the code.
initialize the Session class in the constructor of controller using
$this->load->library('session');
for example :
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->model('user_activity','',TRUE);
$this->load->library('session');
}
Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.
Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal
' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
If Input < 0 Then Input = 0
if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.
End Function
I like Dave Everitt's answer with the « line-height » but it only works by specifying the « height » and then we have to add « !important » to line-height ...
.cercle {
font-size: 2em;
width: 2em;
height: 2em;
text-align: center;
line-height: 2em!important;
background: #666;
color: #fff;
border-radius: 2em;
}
You have to turn off the graphics hot keys that flip the screen. If you're on Windows, you need to right click on the Windows desktop and select "Graphics Properties..." (or something similar depending on your version of Windows). This will bring up a screen where you can manage graphics and display options, look for a place where you can disable hot keys, sometimes it's hidden under something like "Options and Support". Turn off the CTRL + ALT + ? and CTRL + ALT + ? hotkeys (alternatively you can just disable all graphics hot keys if you're not using them).
In my case none of the above is worked. So After trying lot of solutions i found below one and it worked for me
import java.util.Scanner;
import java.util.Date;
public class Practice
{
public static void main(String[] args)
{
Date d=new Date();
int year=d.getYear();
int currentYear=year+1900;
System.out.println(currentYear);
}
}
The easiest method is to use the slice
method of the string, which allows negative positions (corresponding to offsets from the end of the string):
const s = "your string";
const withoutLastFourChars = s.slice(0, -4);
If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s
is guaranteed to contain at least one underscore):
const s = "your_string";_x000D_
const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));_x000D_
console.log(withoutLastChunk);
_x000D_
Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises
HTML
<select
ng-model="cboPais"
ng-options="item.strPais for item in geoPaises"
></select>
JavaScript
$http.get(strUrl2).success(function (response) {
if (response.length > 0) {
$scope.geoPaises = response; //Data source
nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
if (nIndex >= 0) {
$scope.cboPais = response[nIndex]; //if index of array was found
} else {
$scope.cboPais = response[0]; //select the first element of array
}
$scope.geo_getDepartamentos();
}
}
I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...
git add <your different stuff>
git commit --amend --author="author name <[email protected]>"-m "new message"
https://docs.python.org/library/os.html
To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.
Your code should be contain WHILE
before group by
and having
:
SELECT Email, COUNT(*)
FROM user_log
WHILE Email IS NOT NULL
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC
If you want to show it as a full screen popup, then you don't even need an xml layout. Here's how do do it in Kotlin.
val inputArray: Array<String> = arrayOf("Item 1","Item 2")
val alt_bld = AlertDialog.Builder(context);
alt_bld.setTitle("Items:")
alt_bld.setSingleChoiceItems(inputArray, -1) { dialog, which ->
if(which == 0){
//Item 1 Selected
}
else if(which == 1){
//Item 2 Selected
}
dialog.dismiss();
}
val alert11 = alt_bld.create()
alert11.show()
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
What about:
$('#play').click(function() {_x000D_
const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");_x000D_
audio.play();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
I like the clean look of this code... gleaned from a discussion here: http://www.scala-lang.org/old/node/4380
object ArgParser {
val usage = """
Usage: parser [-v] [-f file] [-s sopt] ...
Where: -v Run verbosely
-f F Set input file to F
-s S Set Show option to S
"""
var filename: String = ""
var showme: String = ""
var debug: Boolean = false
val unknown = "(^-[^\\s])".r
val pf: PartialFunction[List[String], List[String]] = {
case "-v" :: tail => debug = true; tail
case "-f" :: (arg: String) :: tail => filename = arg; tail
case "-s" :: (arg: String) :: tail => showme = arg; tail
case unknown(bad) :: tail => die("unknown argument " + bad + "\n" + usage)
}
def main(args: Array[String]) {
// if there are required args:
if (args.length == 0) die()
val arglist = args.toList
val remainingopts = parseArgs(arglist,pf)
println("debug=" + debug)
println("showme=" + showme)
println("filename=" + filename)
println("remainingopts=" + remainingopts)
}
def parseArgs(args: List[String], pf: PartialFunction[List[String], List[String]]): List[String] = args match {
case Nil => Nil
case _ => if (pf isDefinedAt args) parseArgs(pf(args),pf) else args.head :: parseArgs(args.tail,pf)
}
def die(msg: String = usage) = {
println(msg)
sys.exit(1)
}
}
If I'm right, it's just because you are missing the cd
command. Try c:\Users\Jonathan\cd .m2/
.
You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.
You can use following libs:
Update after 3 years (2013):
Update after 4 years (2014):
For some hosting accounts, I'm on Ultimate Classic Linux, the file name you need to use is .user.ini.
There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it
--Version 2
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s
on p.ProductID = s.ProdctId
I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.
Error :
Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at hudson.Proc$LocalProc.<init>(Proc.java:250)
at hudson.Proc$LocalProc.<init>(Proc.java:219)
at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
at hudson.Launcher$ProcStarter.start(Launcher.java:455)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
at hudson.model.Build$BuildExecution.build(Build.java:206)
at hudson.model.Build$BuildExecution.doRun(Build.java:163)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1853)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Solution :
1 - Install Cygwin and note the directory where it gets installed.
It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.
2 - Tell Jenkins where sh.exe is located.
Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.
That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.
<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
if (strlen($string) > 25) {
$trimstring = substr($string, 0, 25). ' <a href="#">readmore...</a>';
} else {
$trimstring = $string;
}
echo $trimstring;
//Output : Lorem Ipsum is simply dum [readmore...][1]
?>
Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector
inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')
This works for me:
Create a new shell file job. So let's say:
touch job.sh
and add command to run python script (you can even add command line arguments to that python, I usually predefine my command line arguments).
chmod +x job.sh
Inside job.sh
add the following py files, let's say:
python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file.py"
python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"
Done with python_file.py
Done with python_file1.py
I use this usually when I have to run multiple python files with different arguments, pre defined.
Note: Just a quick heads up on what's going on here:
python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" .
python python_file.py
, plain and simple.
Next up, the >> will print and store the output of this .py file in the testpy-output.txt file. Its been little late but please take it from me...
In the editor(New Query) by select the database object it can be a table too, if we use the Shortcut Key Alt+F1 we will get all the information of the object and I think will solve your problem as well.
<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>
<!--Insert more code here-->
<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">
Next time you ask a question here, include more detail and what you have tried.
Lots of good info here already, but to be succinct. This works for me...
import React, {Component} from 'react';
import _ from 'lodash';
class MyComponent extends Component{
constructor(props){
super(props);
this.handleChange = _.debounce(this.handleChange.bind(this),700);
};
Maybe you can wrap the PowerShell invocation in a .bat
file like so:
rem ps.bat
@echo off
powershell.exe -command "%*"
If you then placed this file under a folder in your PATH
, you could call PowerShell scripts like this:
ps foo 1 2 3
Quoting can get a little messy, though:
ps write-host """hello from cmd!""" -foregroundcolor green
That's because itoa
isn't a standard function. Try snprintf
instead.
char str[LEN];
snprintf(str, LEN, "%d", 42);
If you can use the Apache Commons library, then Commons-Lang StringUtils
has a method called isAlphanumeric()
that does what you're looking for.
You have to remove the borders and add a background image on the input.
.imgClass {
background-image: url(path to image) no-repeat;
width: 186px;
height: 53px;
border: none;
}
It should be good now, normally.
Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.
import subprocess
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(200, 240):
ip="10.2.7.{0}".format(n)
result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip, "inactive"
else:
print ip, "active"
Just change the ip= for your scheme and the xrange for the hosts.
without using regex, using isdigit() built-in function, only works if starting part is text and latter part is number
def text_num_split(item):
for index, letter in enumerate(item, 0):
if letter.isdigit():
return [item[:index],item[index:]]
print(text_num_split("foobar12345"))
OUTPUT :
['foobar', '12345']
section {
position: relative;
width: 50%;
border: 1px solid;
}
h1 {
display: inline;
}
div {
position: relative;
float:right;
top: 0;
right: 0;
}
Bootstrap 4 requires you to target the li
item for active classes. In order to do that you have to find the parent of the a
. The 'hitbox' of the a
is as big as the li
but due to bubbeling of event in JS it will give you back the a
event. So you have to manually add it to its parent.
//set active navigation after click
$(".nav-link").on("click", (event) => {
$(".navbar-nav").find(".active").removeClass('active');
$(event.target).parent().addClass('active');
});
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
Refer Link: blogspot.in
<?php
$args = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args );
?>
This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products
There is always intval() - Not sure if this is what you were looking for...
example: -
$floatValue = 4.5;
echo intval($floatValue); // Returns 4
It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.
Here is some documentation for this: - http://php.net/manual/en/function.intval.php
Here is a (non-idiomatic) Scala version of the smoothed z-score algorithm:
/**
* Smoothed zero-score alogrithm shamelessly copied from https://stackoverflow.com/a/22640362/6029703
* Uses a rolling mean and a rolling deviation (separate) to identify peaks in a vector
*
* @param y - The input vector to analyze
* @param lag - The lag of the moving window (i.e. how big the window is)
* @param threshold - The z-score at which the algorithm signals (i.e. how many standard deviations away from the moving mean a peak (or signal) is)
* @param influence - The influence (between 0 and 1) of new signals on the mean and standard deviation (how much a peak (or signal) should affect other values near it)
* @return - The calculated averages (avgFilter) and deviations (stdFilter), and the signals (signals)
*/
private def smoothedZScore(y: Seq[Double], lag: Int, threshold: Double, influence: Double): Seq[Int] = {
val stats = new SummaryStatistics()
// the results (peaks, 1 or -1) of our algorithm
val signals = mutable.ArrayBuffer.fill(y.length)(0)
// filter out the signals (peaks) from our original list (using influence arg)
val filteredY = y.to[mutable.ArrayBuffer]
// the current average of the rolling window
val avgFilter = mutable.ArrayBuffer.fill(y.length)(0d)
// the current standard deviation of the rolling window
val stdFilter = mutable.ArrayBuffer.fill(y.length)(0d)
// init avgFilter and stdFilter
y.take(lag).foreach(s => stats.addValue(s))
avgFilter(lag - 1) = stats.getMean
stdFilter(lag - 1) = Math.sqrt(stats.getPopulationVariance) // getStandardDeviation() uses sample variance (not what we want)
// loop input starting at end of rolling window
y.zipWithIndex.slice(lag, y.length - 1).foreach {
case (s: Double, i: Int) =>
// if the distance between the current value and average is enough standard deviations (threshold) away
if (Math.abs(s - avgFilter(i - 1)) > threshold * stdFilter(i - 1)) {
// this is a signal (i.e. peak), determine if it is a positive or negative signal
signals(i) = if (s > avgFilter(i - 1)) 1 else -1
// filter this signal out using influence
filteredY(i) = (influence * s) + ((1 - influence) * filteredY(i - 1))
} else {
// ensure this signal remains a zero
signals(i) = 0
// ensure this value is not filtered
filteredY(i) = s
}
// update rolling average and deviation
stats.clear()
filteredY.slice(i - lag, i).foreach(s => stats.addValue(s))
avgFilter(i) = stats.getMean
stdFilter(i) = Math.sqrt(stats.getPopulationVariance) // getStandardDeviation() uses sample variance (not what we want)
}
println(y.length)
println(signals.length)
println(signals)
signals.zipWithIndex.foreach {
case(x: Int, idx: Int) =>
if (x == 1) {
println(idx + " " + y(idx))
}
}
val data =
y.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> s, "name" -> "y", "row" -> "data") } ++
avgFilter.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> s, "name" -> "avgFilter", "row" -> "data") } ++
avgFilter.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> (s - threshold * stdFilter(i)), "name" -> "lower", "row" -> "data") } ++
avgFilter.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> (s + threshold * stdFilter(i)), "name" -> "upper", "row" -> "data") } ++
signals.zipWithIndex.map { case (s: Int, i: Int) => Map("x" -> i, "y" -> s, "name" -> "signal", "row" -> "signal") }
Vegas("Smoothed Z")
.withData(data)
.mark(Line)
.encodeX("x", Quant)
.encodeY("y", Quant)
.encodeColor(
field="name",
dataType=Nominal
)
.encodeRow("row", Ordinal)
.show
return signals
}
Here's a test that returns the same results as the Python and Groovy versions:
val y = List(1d, 1d, 1.1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 1d,
1d, 1d, 1.1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d, 1.1d, 1d, 0.8d, 0.9d, 1d, 1.2d, 0.9d, 1d,
1d, 1.1d, 1.2d, 1d, 1.5d, 1d, 3d, 2d, 5d, 3d, 2d, 1d, 1d, 1d, 0.9d, 1d,
1d, 3d, 2.6d, 4d, 3d, 3.2d, 2d, 1d, 1d, 0.8d, 4d, 4d, 2d, 2.5d, 1d, 1d, 1d)
val lag = 30
val threshold = 5d
val influence = 0d
smoothedZScore(y, lag, threshold, influence)
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
I took Jeet's answer and adapted it to Windows (thanks to this answer):
FOR /F %x IN ('"git rev-list --all"') DO @git grep <regex> %x > out.txt
Note that for me, for some reason, the actual commit that deleted this regex did not appear in the output of the command, but rather one commit prior to it.
The good option is to use AdminClient as below before starting to produce or consume the messages
private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;
try (AdminClient client = AdminClient.create(properties)) {
client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
} catch (ExecutionException ex) {
LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
return;
}
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
There are a few points to consider.
A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:
>>> text = u'‘'
>>> print repr(text)
u'\u2018'
Now if you simply want to print the unicode string prettily, just use unicode's encode
method:
>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this
To make sure that every line from any file would be read as unicode, you'd better use the codecs.open
function instead of just open
, which allows you to specify file's encoding:
>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this
Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:
HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie")
More info can be found here.
In my case I had to modify Response Cookie in Application_EndRequest method in Global.asax. If Cookie doesn't exist I don't touch it:
string name = "myCookie";
HttpContext context = ((HttpApplication)sender).Context;
HttpCookie cookie = null;
if (context.Response.Cookies.AllKeys.Contains(name))
{
cookie = context.Response.Cookies[name];
}
if (cookie != null)
{
// update response cookie
}
Perl can be used for this, even on exotic platforms like AIX. Example:
#!/usr/bin/perl -w
use strict;
use Time::HiRes qw(gettimeofday);
my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime ($t_sec);
printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;
In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.
[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true
You can Use <ng-container>
and <ng-template>
for Achieve This
<ng-container *ngIf="isValid; then template1 else template2"></ng-container>
<ng-template #template1>
<div>Template 1 contains</div>
</ng-template>
<ng-template #template2>
<div>Template 2 contains </div>
</ng-template>
You can find the Stackblitz Live demo below
Hope This will helps ... !!!
select * from
(SELECT MEMBSHIP_ID
FROM user_payment WHERE user_id=1
order by paym_date desc)
where rownum=1;
Use sql
from sql
:
spool output of this to a file:
select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';
spoolfile will have something like this:
alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;
To get the correct orientation on app start you have to check it in viewDidLayoutSubviews()
. Other methods described here won't work.
Here's an example how to do it:
var mFirstStart = true
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if (mFirstStart) {
mFirstStart = false
detectOrientation()
}
}
func detectOrientation() {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
// do your stuff here for landscape
} else {
print("Portrait")
// do your stuff here for portrait
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
detectOrientation()
}
This will work always, on app first start, and if rotating while the app is running.
This answer is to give a better understanding of this warning
Deprecation warning is caused when you use moment to create time object, var today = moment();
.
If this warning is okay with you then I have a simpler method.
Don't use date
object from js
use moment
instead. For example use moment()
to get the current date.
Or convert the js
date object to moment
date. You can simply do that specifying the format of your js
date object.
ie, moment("js date", "js date format");
eg:
moment("2014 04 25", "YYYY MM DD");
(BUT YOU CAN ONLY USE THIS METHOD UNTIL IT'S DEPRECIATED, this may be depreciated from moment
in the future)
Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:
http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.
Specifically for java web start set the environment variable:
JAVAWS_VM_ARGS
and for applets:
_JPI_VM_OPTIONS
e.g.
_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true
Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.
I had this issue as well. I tried the above methods and none seemed to work, however something that did work (somehow, not sure if it was just a freak thing or it is actually a way to do it) was:
As most of the answers are using to Express, bodyParser, connect; where multipart is deprecated. There is a secure way to send post multipart objects easily.
Multer can be used as replacement for connect.multipart().
To install the package
$ npm install multer
Load it in your app:
var multer = require('multer');
And then, add it in the middleware stack along with the other form parsing middleware.
app.use(express.json());
app.use(express.urlencoded());
app.use(multer({ dest: './uploads/' }));
connect.json() handles application/json
connect.urlencoded() handles application/x-www-form-urlencoded
multer() handles multipart/form-data
As of right now ES6 import, export is always compiled to CommonJS, so there is no benefit using one or other. Although usage of ES6 is recommended since it should be advantageous when native support from browsers released. The reason being, you can import partials from one file while with CommonJS you have to require all of the file.
ES6 → import, export default, export
CommonJS → require, module.exports, exports.foo
Below is common usage of those.
ES6 export default
// hello.js
function hello() {
return 'hello'
}
export default hello
// app.js
import hello from './hello'
hello() // returns hello
ES6 export multiple and import multiple
// hello.js
function hello1() {
return 'hello1'
}
function hello2() {
return 'hello2'
}
export { hello1, hello2 }
// app.js
import { hello1, hello2 } from './hello'
hello1() // returns hello1
hello2() // returns hello2
CommonJS module.exports
// hello.js
function hello() {
return 'hello'
}
module.exports = hello
// app.js
const hello = require('./hello')
hello() // returns hello
CommonJS module.exports multiple
// hello.js
function hello1() {
return 'hello1'
}
function hello2() {
return 'hello2'
}
module.exports = {
hello1,
hello2
}
// app.js
const hello = require('./hello')
hello.hello1() // returns hello1
hello.hello2() // returns hello2
In Swift 5 apple has introduces Raw Strings using # symbols.
Example:
print(#"My name is "XXX" and I'm "28"."#)
let name = "XXX"
print(#"My name is \#(name)."#)
symbol # is necessary after \. A regular \(name) will be interpreted as characters in the string.
It is 2019, and here is what is working -
despite advice here and there, what I found on the internet halfway documented is using setuptools_scm
, passed as options to setuptools.setup
. This will include any data files that are versioned on your VCS, be it git or any other, to the wheel package, and will make "pip install" from the git repository to bring those files along.
So, I just added these two lines to the setup call on "setup.py". No extra installs or import required:
setup_requires=['setuptools_scm'],
include_package_data=True,
No need to manually list package_data, or in a MANIFEST.in file - if it is versioned, it is included in the package. The docs on "setuptools_scm" put emphasis on creating a version number from the commit position, and disregard the really important part of adding the data files. (I can't care less if my intermediate wheel file is named "*0.2.2.dev45+g3495a1f" or will use the hardcoded version number "0.3.0dev0" I've typed in - but leaving crucial files for the program to work behind is somewhat important)
Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.
Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...
I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.
When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...
Class under test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClassWithSomeLogging {
private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);
public void doStuff(boolean b) {
if(b) {
LOG.info("true");
} else {
LOG.info("false");
}
}
}
Test
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {
private static Logger mockLOG;
@BeforeClass
public static void setup() {
mockStatic(LoggerFactory.class);
mockLOG = mock(Logger.class);
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
}
@Test
public void testIt() {
MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
myClassWithSomeLogging.doStuff(true);
verify(mockLOG, times(1)).info("true");
}
@Test
public void testIt2() {
MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
myClassWithSomeLogging.doStuff(false);
verify(mockLOG, times(1)).info("false");
}
@AfterClass
public static void verifyStatic() {
verify(mockLOG, times(1)).info("true");
verify(mockLOG, times(1)).info("false");
verify(mockLOG, times(2)).info(anyString());
}
}
Note
If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true");
- rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....
After a lot of time spent trying all these technique in a Dialog, I finally had this idea : attach the theme to the Dialog itself and not to the TextInputLayout.
<style name="AppTheme_Dialog" parent="Theme.AppCompat.Dialog">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorWhite</item>
<item name="colorAccent">@color/colorPrimary</item>
</style>
inside onCreate :
public class myDialog extends Dialog {
private Activity activity;
private someVars;
public PopupFeedBack(Activity activity){
super(activity, R.style.AppTheme_Dialog);
setContentView(R.layout.myView);
....}}
cheers :)
Both answers given worked for the problem I stated -- Thanks!
In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.
Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.
I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self
import java.io.*;
import java.util.Date;
public class StringTest{
public static void main( String[] args ){
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for( i = 0; i< 100000; i++){
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for( i = 0; i<100000; i++){
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
Running the above for different N shows that both behave linearly, but String.format
is 5-30 times slower.
The reason is that in the current implementation String.format
first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append
directly.
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
_x000D_
private router = ActivatedRoute;_x000D_
_x000D_
constructor(r: ActivatedRoute) {_x000D_
this.router =r;_x000D_
}_x000D_
_x000D_
onSuccess() {_x000D_
this.router.navigate(['/user_invitation'],_x000D_
{queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
this.route_x000D_
.queryParams_x000D_
.subscribe(params => {_x000D_
let code = params['code'];_x000D_
let userEmail = params['email'];_x000D_
});_x000D_
}
_x000D_
Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html
Try this command, it will purge all branches that have been merged to the develop
branch.
for i in `git branch -r --merged origin/develop| grep origin | grep -v '>' \
| grep -v master | grep -v develop | sed -E "s|^ *origin/||g"`; \
do \
git push origin $i --delete; \
done
You have an extra closing }
in your function.
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <== remove this brace
}, false);
};
You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.
If your Windows 7 machine is a member of an AD, or if you have UAC enabled, or if security policies are in effect, telnet more often than not must be run as an admin. The easiest way to do this is as follows
Create a shortcut that calls cmd.exe
Go to the shortcut's properties
Click on the Advanced button
Check the "Run as an administrator" checkbox
After these steps you're all set and telnet should work now.
Try this:
grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c
Sample:
grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
6 SMTP connect from unknown [188.190.118.90]
54 SMTP connect from unknown [62.193.131.114]
3 SMTP connect from unknown [91.222.51.253]
I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.
//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef CONDITION_01 //| |//
#define TEMP_MACRO //| |//
#endif //| |//
#ifdef CONDITION_02 //| |//
#define TEMP_MACRO //| |//
#endif //| |//
#ifdef CONDITION_03 //| |//
#define TEMP_MACRO //| |//
#endif //| |//
#ifdef TEMP_MACRO //| |//
//|- -- -- -- -- -- -- -- -- -- -|//
printf("[IF_CONDITION:(1|2|3)]\n");
//|- -- -- -- -- -- -- -- -- -- -|//
#endif //| |//
#undef TEMP_MACRO //| |//
//|________________________________________|//
Sed is a little ugly, you could do it elegantly like so:
hendry@i7 tmp$ cat foo
bar
candy
car
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done
barbar
candybar
carbar
Breakpoints and especially conditional breakpoints are your friends.
Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
if (isVisible) {
// element is visible
} else {
// element is not visible
}
}).catch(function(err){
console.log("Element is not found");
})
I ran into a similar issue. Sometimes, you wont find xdebug.so in php.ini. In which case, execute phpinfo()
in a php file and check for Additional .ini files parsed
. Here you'll see more ini files. One of these will be xdebug's ini file. Just remove (or rename) this file, restart apache, and this extension will be removed.
Let me assume that you have done the 'this' binding of 'sendThru' function.
The below functions clears the input fields when the method is triggered.
sendThru() {
this.inputTitle.value = "";
this.inputEntry.value = "";
}
Refs can be written as inline function expression:
ref={el => this.inputTitle = el}
where el
refers to the component.
When refs are written like above, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.
Read more about it here.
<script>
const geocodeArr = JSON.parse('{{ geocode | tojson }}');
console.log(geocodeArr);
</script>
This uses jinja2 to turn the geocode tuple into a json string, and then the javascript JSON.parse
turns that into a javascript array.
Simplest solution:
Convert array to list and you can get position of an element.
List<String> abcd = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");
Other solution, you can iterator array:
int position = 0;
for (String obj : yourArray) {
if (obj.equals("abcd") {
return position;
}
position += 1;
}
//OR
for (int i = 0; i < yourArray.length; i++) {
if (obj.equals("abcd") {
return i;
}
}
Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648
Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event()
and data pointers to a framework function watch_events()
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
I have Jquery and Angular from bower. Bower installed them in
/public_html/bower_components/jquery/dist/bunch-of-jquery-files
/public_html/bower_components/jquery/src/bunch-of-jquery-source-files
/public_html/bower_components/angular/angular-files
The minimized jquery is inside the dist
directory and angular is inside angular
directory. I only needed minimized files to be commited to github. Some tampering with .gitignore and this is what I managed to conjure...
/public_html/bower_components/jquery/*
!public_html/bower_components/jquery/dist
/public_html/bower_components/jquery/dist/*
!public_html/bower_components/jquery/dist/jquery.min.js
/public_html/bower_components/angular/*
!public_html/bower_components/angular/angular.min.js
Hope someone could find this useful.
public bool ValueExists(RegistryKey Key, string Value)
{
try
{
return Key.GetValue(Value) != null;
}
catch
{
return false;
}
}
This simple function will return true only if a value is found but it is not null, else will return false if the value exists but it is null or the value doesn't exists in the key.
USAGE for your question:
if (ValueExists(winLogonKey, "Start")
{
// The values exists
}
else
{
// The values does not exists
}
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
I had this problem on Ubuntu 18.04. I updated the gem
sudo gem install rails
sudo gem install jekyll
sudo gem install jekyll bundler
cd ~/desiredFolder
jekyll new <foldername>
cd <foldername> OR
bundle init
bundle install
bundle add jekyll
bundle exec jekyll serve
All worked and goto your browser just go to http://127.0.0.1:4000/ and it really should be running
Your friend's PC is missing the runtime support DLLs for your program:
You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:
moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want
Output: 28-Apr-1993
Hope it will help you :)
To make sure you get the right version with Environment.OSVersion
you should add an app.manifest
using Visual Studio and uncomment following supportedOS
tags:
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
Then in your code you can use Environment.OSVersion
like this:
var version = System.Environment.OSVersion;
Console.WriteLine(version);
Example
For instance in my machine (Windows 10.0 Build 18362.476
) result would be like this which is incorrect:
Microsoft Windows NT 6.2.9200.0
By adding app.manifest
and uncomment those tags I will get the right version number:
Microsoft Windows NT 10.0.18362.0
If you don't like adding app.manifest
to your project, you can use OSDescription
which is available since .NET Framework 4.7.1 and .NET Core 1.0.
string description = RuntimeInformation.OSDescription;
Note: Don't forget to add following using statement at top of your file.
using System.Runtime.InteropServices;
You can read more about it and supported platforms here.
Here is a cleaner way to do it if you are using Bootstrap 3.2.0.
Link HTML
<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>
Modal JavaScript
//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {
//get data-id attribute of the clicked element
var bookId = $(e.relatedTarget).data('book-id');
//populate the textbox
$(e.currentTarget).find('input[name="bookId"]').val(bookId);
});
You have explicitly set your stroke-linejoin
to round
but your stroke-width
to 0
, so of course you're not going to see rounded corners if you have no stroke to round.
Here's a modified example with rounded corners made through strokes:
http://jsfiddle.net/8uxqK/1/
<path d="M64.5 45.5 82.5 45.5 82.5 64.5 64.5 64.5 z"
stroke-width="5"
stroke-linejoin="round"
stroke="#808600"
fill="#a0a700" />
Otherwise—if you need an actual rounded shape fill and not just a rounded fatty stroke—you must do what @Jlange says and make an actual rounded shape.
While some of these answers are pretty good, I feel like none actually answered the OP's original constraint: selecting particular files from particular branches. This solution does that, but it may be tedious if there are many files.
Let’s say you have the master
, exp1
, and exp2
branches. You want to merge one file from each of the experimental branches into master. I would do something like this:
git checkout master
git checkout exp1 path/to/file_a
git checkout exp2 path/to/file_b
# Save these files as a stash
git stash
# Merge stash with master
git merge stash
This will give you in-file diffs for each of the files you want. Nothing more. Nothing less. It's useful you have radically different file changes between versions --in my case, changing an application from Ruby on Rails 2 to Ruby on Rails 3.
This will merge files, but it does a smart merge. I wasn't able to figure out how to use this method to get in-file diff information (maybe it still will for extreme differences. Annoying small things like whitespace get merged back in unless you use the -s recursive -X ignore-all-space
option)
Here is yet another, compact version, with the generics syntax:
public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null) {
if (obj is T)
yield return obj as T;
foreach (DependencyObject child in LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>())
foreach (T c in FindLogicalChildren<T>(child))
yield return c;
}
}
APScheduler might be what you are after.
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
https://apscheduler.readthedocs.io/en/latest/
You can just get it to schedule another run by building that into the function you are scheduling.
Both of the previous answers from Matt York and Cyberbolt are right.
Basic idea is here that you want to get some kind of File explorer in Sublime.
Approach:
1) With File -> New Folder -> Click on Desired folder and Hit Open
you will get new popup window in sublime which for me is very annoying
2) I use second option which is drag'n'drop from nautilus (a.k.a. Files) window. Simply drag'n'drop your file you want to explore from nautilus to sublime sidebar
. That way you stay in the same window and everything is cool.
Don't forget to enable View -> Sidebar -> Show Sidebar and drag'n'drop there from nautilus and of course run it with root privleges
. It works like charm
Theta is a shorthand way of referring to a special situtation where the big O and Omega are the same.
Thus, if one claims The Theta is expression q
, then they are also necessarily claiming that Big O is expression q
and Omega is expression q
.
Rough analogy:
If: Theta claims, "That animal has 5 legs." then it follows that: Big O is true ("That animal has less than or equal to 5 legs.") and Omega is true("That animal has more than or equal to 5 legs.")
It's only a rough analogy because the expressions aren't necessarily specific numbers, but instead functions of varying orders of magnitude such as log(n), n, n^2, (etc.).