If you have Google analytics or Facebook api in you app, you need to check all of them to make sure it works!
Edit: This is an old answer - see comments or other answers for an exact answer.
Something similar to Google Ads, from the documentation:
public AdRequest.Builder addTestDevice (String deviceId)
Causes a device to receive test ads. The deviceId can be obtained by viewing the logcat output after creating a new ad. For emulators, use DEVICE_ID_EMULATOR.
for example my Test Device id displayed in LogCat is "B86BC9402A69B031A516BC57F7D3063F"
:
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("B86BC9402A69B031A516BC57F7D3063F")
.build();
I'm not sure about you, but I spent about 30 minutes troubleshooting the same issue here, until I realized that the line for app/build.gradle is:
apply plugin: 'com.google.gms.google-services'
and not:
apply plugin: 'com.google.gms:google-services'
Eg: I had copied that line from a tutorial, but when specifying the apply plugin namespace, no colon (:
) is required. It's, in fact, a dot. (.
).
Hey... it's easy to miss.
I was getting similar bugs on library not found. Ultimately this is how I was able to resolve it
If yours is a gradle project replace:
xmlns:android="http://schemas.android.com/apk/res/android"
with:
xmlns:app="http://schemas.android.com/apk/res-auto"
you don't need to declare Map groovy internally recognizes it
def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']
// print the values..
println "First Name: ${personDetails.firstName}"
println "Last Name: ${personDetails.lastName}"
Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.
var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"
Here's a DEMO on how this regex works with test() and match().
You can take a snapshot of the complete status of your cluster (including all data indices) and restore them (using the restore API) in the new cluster or server.
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
Python3:
exec(open('helloworld.py').read())
If your file not in the same dir:
exec(open('./app/filename.py').read())
See https://stackoverflow.com/a/437857/739577 for passing global/local variables.
In deprecated Python versions
Python2 Built-in function: execfile
execfile('helloworld.py')
It normally cannot be called with arguments. But here's a workaround:
import sys
sys.argv = ['helloworld.py', 'arg'] # argv[0] should still be the script name
execfile('helloworld.py')
Deprecated since 2.6: popen
import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout
With arguments:
os.popen('python helloworld.py arg').read()
Advance usage: subprocess
import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout
With arguments:
subprocess.call(['python', 'helloworld.py', 'arg'])
Read the docs for details :-)
Tested with this basic helloworld.py
:
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
function myResizeFunction() {
...
}
$(function() {
$(window).resize(myResizeFunction).trigger('resize');
});
This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize')
to run on page load instead.
UPDATE: Here's another option if you don't want to make use of any other third-party libraries.
This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).
It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.
function myResizeFunction() {
var $window = $(this),
height = Math.ceil($window.height()),
previousHeight = $window.data('previousHeight');
if (height !== previousHeight) {
if (height < 819)
previousHeight >= 819 && $('.footer').removeClass('hgte819');
else if (!previousHeight || previousHeight < 819)
$('.footer').addClass('hgte819');
$window.data('previousHeight', height);
}
}
$(function() {
$(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});
As an example, you might have the following as some of your CSS rules:
.footer {
bottom: auto;
left: auto;
position: static;
}
.footer.hgte819 {
bottom: 3px;
left: 0;
position: absolute;
}
Easy way:
#include <time.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
time_t mytime = time(NULL);
char * time_str = ctime(&mytime);
time_str[strlen(time_str)-1] = '\0';
printf("Current Time : %s\n", time_str);
return 0;
}
You can use this text-underline-position: under
See here for more detail: https://css-tricks.com/almanac/properties/t/text-underline-position/
See also browser compatibility.
Use LINQ - The beauty of C#
DataTable newDataTable = baseTable.AsEnumerable()
.OrderBy(r=> r.Field<int>("ColumnName"))
.CopyToDataTable();
In a nutshell, this is the code which works for me :)
WebDriver driver;
WebElement element;
String value;
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);
I tried all of the above said solutions but did not worked out for me, Here is what i did to get it done project-> config build path-> order and export-> move dependent project on top
I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.
Maybe you could look into full text search.
As last resorts you'd be looking at caching or precomputed columns/an indexed view.
SQLDeveloper can do this.
In kotlin you can add boolean variable in companion object and check its value from any class you want:
companion object{
var isRuning = false
}
Change it value when service is created and destroyed
override fun onCreate() {
super.onCreate()
isRuning = true
}
override fun onDestroy() {
super.onDestroy()
isRuning = false
}
kleolb02's answer looks pretty good. another way would be a combination of the sticky footer and the min-height hack
SQL Server uses the TCP port 1433. This is probably blocked either by the VPN tunnel or by a firewall on the server.
you can check that by either isset()
or empty()
(its check explicit isset) weather check box is checked or not
for example
<input type='checkbox' name='Mary' value='2' id='checkbox' />
here you can check by
if (isset($_POST['Mary'])) {
echo "checked!";
}
or
if (!empty($_POST['Mary'])) {
echo "checked!";
}
the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo htmlspecialchars($aDoor[$i] ). " ";
}
}
You can use TypeScript's native string interpolation in case if your only goal to eliminate ugly string concatenations and boring string conversions:
var yourMessage = `Your text ${yourVariable} your text continued ${yourExpression} and so on.`
NOTE:
At the right side of the assignment statement the delimiters are neither single or double quotes, instead a special char called backtick or grave accent.
The TypeScript compiler will translate your right side special literal to a string concatenation expression. With other words this syntax is not relies the ECMAScript 6 feature instead a native TypeScript feature. Your generated javascript code remains compatible.
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
when I load in a json object I usually setup the relationships by iterating through the object arrays like this:
for (var i = 0; i < some.json.objectarray.length; i++) {
var p = some.json.objectarray[i];
for (var j = 0; j < p.somechildarray.length; j++) {
p.somechildarray[j].parent = p;
}
}
then you can access the parent object of some object in the somechildarray by using .parent
This did the trick for me:
echo trim($entry->title);
On Arch Linux run the following:
sudo pacman -S base-devel
Try this:
String str = "5 * x^3 - 6 * x^1 + 1";
String replacedStr = str.replaceAll("\\^(\\d+)", "<sup>\$1</sup>");
Be sure to import java.util.regex.
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
$(document).ready(function() {
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
});
<form id="form1" name="form1">
Field 1: <input id="field1" type="text" class="required">
<input id="btn" type="submit" value="Validate">
</form>
You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.
sed '$d' ~/path/to/your/file/name
sed -i '' -e '$ d' ~/path/to/your/file/name
It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.
The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.
The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).
I wrote a blog describing the pros/cons of DinD vs DooD here.
Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.
If all image’s heights are same,
imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
np.concatenate(
[np.array(Image.open(x)) for x in imgs],
axis=1
)
)
maybe you can resize images before the concatenation like this,
imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
np.concatenate(
[np.array(Image.open(x).resize((640,480)) for x in imgs],
axis=1
)
)
In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.
select standard_hash('foo', 'MD5') from dual;
The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:
select rawtohex(
DBMS_CRYPTO.Hash (
UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
2)
) from dual;
Output:
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
Add a lower function call if needed. More on DBMS_CRYPTO.
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}
Set colspan to your number of columns, and background color as you wish
<tr style="background: #aaa;">
<td colspan="2"></td>
</tr>
std::list
doesn't provide any function to get element given an index. You may try to get it by writing some code, which I wouldn't recommend, because that would be inefficient if you frequently need to do so.
What you need is : std::vector
. Use it as:
std::vector<Object> objects;
objects.push_back(myObject);
Object const & x = objects[0]; //index isn't checked
Object const & y = objects.at(0); //index is checked
As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem
(or sessionStorage.setItem
) is called.
One solution is to do a try/catch or Modernizr check in each instance of using setItem
.
However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:
https://gist.github.com/philfreo/68ea3cd980d72383c951
// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
try {
localStorage.setItem('localStorage', 1);
localStorage.removeItem('localStorage');
} catch (e) {
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function() {};
alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
}
}
My solution is:
events: {
'apply.daterangepicker #selector': 'function'
}
All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):
function isFunction(possibleFunction) {
return typeof(possibleFunction) === typeof(Function);
}
Personally, I try to reduce the number of strings hanging around in my code...
Also, while I am aware that typeof
is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.
Find the text nodes (nodeType==3
) and replace the textContent
:
$('#one').contents().filter(function() {
return this.nodeType == 3
}).each(function(){
this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
Note that as per the docs you can replace the hard-coded 3
in the above with Node.TEXT_NODE
which is much clearer what you're doing.
$('#one').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).each(function(){
this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
<div class="first"></div>
"Hi I am text"
<div class="second"></div>
<div class="third"></div>
</div>
_x000D_
I made this for when doing aggregate functions and similar
per.fun <- function(x) {
if(length(x)>1){
denom <- length(x);
num <- sum(x);
percentage <- num/denom;
percentage*100
}
else NA
}
Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.
I found the problem. Instead of adding a class (.cs)
file by mistake I had added a Web API Controller
class which added a configuration file in my solution. And that configuration file was looking for the mentioned DLL (Microsoft.Web.Infrastructure 1.0.0.0).
It worked when I removed that file, cleaned the application and then published.
td[rowspan] {
vertical-align: top;
text-align: left;
}
See: CSS attribute selectors.
I set the following beforeShow event handler (in the options parameter) to achieve this functionality.
beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }
A simplified version of Daniel's answer above. This function gets a yes or no from user in an alert dialog but could easily be modified to get other input.
private boolean mResult;
public boolean getYesNoWithExecutionStop(String title, String message, Context context) {
// make a handler that throws a runtime exception when a message is received
final Handler handler = new Handler() {
@Override
public void handleMessage(Message mesg) {
throw new RuntimeException();
}
};
// make a text input dialog and show it
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
alert.setMessage(message);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mResult = true;
handler.sendMessage(handler.obtainMessage());
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mResult = false;
handler.sendMessage(handler.obtainMessage());
}
});
alert.show();
// loop till a runtime exception is triggered.
try { Looper.loop(); }
catch(RuntimeException e2) {}
return mResult;
}
I'm using GIMP 2.8.1. I hope this will work for you:
Open the "Windows" menu and select "Single-Window Mode".
Simple ;)
Here is the answer.
System.exit(0);// normal termination - Successful - zero
System.exit(-1);//Exit with some Error
System.exit(1);//one or any positive integer // exit with some Information message
Seems reflection only help here.. I've done small example of converting object to dictionary and vise versa:
[TestMethod]
public void DictionaryTest()
{
var item = new SomeCLass { Id = "1", Name = "name1" };
IDictionary<string, object> dict = ObjectToDictionary<SomeCLass>(item);
var obj = ObjectFromDictionary<SomeCLass>(dict);
}
private T ObjectFromDictionary<T>(IDictionary<string, object> dict)
where T : class
{
Type type = typeof(T);
T result = (T)Activator.CreateInstance(type);
foreach (var item in dict)
{
type.GetProperty(item.Key).SetValue(result, item.Value, null);
}
return result;
}
private IDictionary<string, object> ObjectToDictionary<T>(T item)
where T: class
{
Type myObjectType = item.GetType();
IDictionary<string, object> dict = new Dictionary<string, object>();
var indexer = new object[0];
PropertyInfo[] properties = myObjectType.GetProperties();
foreach (var info in properties)
{
var value = info.GetValue(item, indexer);
dict.Add(info.Name, value);
}
return dict;
}
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
Based on the documentation the origin
parameter is optional and it defaults to the user's location.
... Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin....
ex: https://www.google.com/maps/dir/?api=1&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling
For me this works on Desktop, IOS and Android.
It's called String#start_with?
, not String#startswith
: In Ruby, the names of boolean-ish methods end with ?
and the words in method names are separated with an _
. Not sure where the s
went, personally, I'd prefer String#starts_with?
over the actual String#start_with?
Funny, I was just researching this yesterday!
I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download
You might be able to make use of sql.js.
sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. no C bindings or node-gyp compilation here.
<script src='js/sql.js'></script>
<script>
//Create the database
var db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);
// Prepare a statement
var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}
// Bind new values
stmt.bind({$start:1, $end:2});
while(stmt.step()) { //
var row = stmt.getAsObject();
// [...] do something with the row of result
}
</script>
sql.js
is a single JavaScript file and is about 1.5MiB in size currently. While this could be a problem in a web-page, the size is probably acceptable for an extension.
Only justification for moving your application to 64 bit is need for more memory in applications like large databases or ERP applications with at least 100s of concurrent users where 2 GB limit will be exceeded fairly quickly when applications cache for better performance. This is case specially on Windows OS where integer and long is still 32 bit (they have new variable _int64. Only pointers are 64 bit. In fact WOW64 is highly optimised on Windows x64 so that 32 bit applications run with low penalty on 64 bit Windows OS. My experience on Windows x64 is 32 bit application version run 10-15% faster than 64 bit since in former case at least for proprietary memory databases you can use pointer arithmatic for maintaining b-tree (most processor intensive part of database systems). Compuatation intensive applications which require large decimals for highest accuracy not afforded by double on 32-64 bit operating system. These applications can use _int64 in natively instead of software emulation. Of course large disk based databases will also show improvement over 32 bit simply due to ability to use large memory for caching query plans and so on.
You can use the WindowsIdentity class (with a logon token) to impersonate while reading and writing files.
var windowsIdentity = new WindowsIdentity(logonToken);
using (var impersonationContext = windowsIdentity.Impersonate()) {
// Connect, read, write
}
function greet(name, greeting) {_x000D_
name = (typeof name !== 'undefined') ? name : 'Student';_x000D_
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';_x000D_
_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet(); // Welcome Student!_x000D_
greet('James'); // Welcome James!_x000D_
greet('Richard', 'Howdy'); // Howdy Richard!_x000D_
_x000D_
//ES6 provides new ways of introducing default function parameters this way:_x000D_
_x000D_
function greet2(name = 'Student', greeting = 'Welcome') {_x000D_
// return '${greeting} ${name}!';_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet2(); // Welcome Student!_x000D_
greet2('James'); // Welcome James!_x000D_
greet2('Richard', 'Howdy'); // Howdy Richard!
_x000D_
Use this bitmap.recycle();
This helps without any image quality issue.
I had the same problem. Turns out the project I was referencing did not get build. When I went to the build configuration manager in visual studio and enabled the reference project , the issue got resolved.
The most correct answer I can think of is Int32.MaxValue
.
For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .
you can define it like this:
new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };
and here is a more realistic example:
new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}
and finally in:
MVC 1
<%= Html.TextBox("test", new { style="width:50px" }) %>
MVC 2
<%= Html.TextBox("test", null, new { style="width:50px" }) %>
MVC 3
@Html.TextBox("test", null, new { style="width:50px" })
You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.
File.Open("filename", FileMode.Create).Close();
You can simply call it:
SubGraphButton_Click(sender, args);
Now, if your SubGraphButton_Click
does something with the args, you might be in trouble, but usually you don't do anything with them.
You must set minLength
to zero in order to make this work! Here is the working example.
$( "#dropdownlist" ).autocomplete({
source: availableTags,
minLength: 0
}).focus(function() {
$(this).autocomplete('search', $(this).val())
});
});
Here is a QuickSort that I wrote for the arrays returned from the GetRows method of ADODB.Recordset.
'Author: Eric Weilnau
'Date Written: 7/16/2003
'Description: QuickSortDataArray sorts a data array using the QuickSort algorithm.
' Its arguments are the data array to be sorted, the low and high
' bound of the data array, the integer index of the column by which the
' data array should be sorted, and the string "asc" or "desc" for the
' sort order.
'
Sub QuickSortDataArray(dataArray, loBound, hiBound, sortField, sortOrder)
Dim pivot(), loSwap, hiSwap, count
ReDim pivot(UBound(dataArray))
If hiBound - loBound = 1 Then
If (sortOrder = "asc" and dataArray(sortField,loBound) > dataArray(sortField,hiBound)) or (sortOrder = "desc" and dataArray(sortField,loBound) < dataArray(sortField,hiBound)) Then
Call SwapDataRows(dataArray, hiBound, loBound)
End If
End If
For count = 0 to UBound(dataArray)
pivot(count) = dataArray(count,int((loBound + hiBound) / 2))
dataArray(count,int((loBound + hiBound) / 2)) = dataArray(count,loBound)
dataArray(count,loBound) = pivot(count)
Next
loSwap = loBound + 1
hiSwap = hiBound
Do
Do While (sortOrder = "asc" and dataArray(sortField,loSwap) <= pivot(sortField)) or sortOrder = "desc" and (dataArray(sortField,loSwap) >= pivot(sortField))
loSwap = loSwap + 1
If loSwap > hiSwap Then
Exit Do
End If
Loop
Do While (sortOrder = "asc" and dataArray(sortField,hiSwap) > pivot(sortField)) or (sortOrder = "desc" and dataArray(sortField,hiSwap) < pivot(sortField))
hiSwap = hiSwap - 1
Loop
If loSwap < hiSwap Then
Call SwapDataRows(dataArray,loSwap,hiSwap)
End If
Loop While loSwap < hiSwap
For count = 0 to Ubound(dataArray)
dataArray(count,loBound) = dataArray(count,hiSwap)
dataArray(count,hiSwap) = pivot(count)
Next
If loBound < (hiSwap - 1) Then
Call QuickSortDataArray(dataArray, loBound, hiSwap-1, sortField, sortOrder)
End If
If (hiSwap + 1) < hiBound Then
Call QuickSortDataArray(dataArray, hiSwap+1, hiBound, sortField, sortOrder)
End If
End Sub
Use the function String.Contains();
an example call,
abs.Contains("s"); // to look for lower case s
here is more from MSDN.
Fetch the KeyListener value of EditText
by editText.getKeyListener()
and store in the KeyListener type variable, which will contain
the Editable property value:
KeyListener variable;
variable = editText.getKeyListener();
Set the Editable property of EditText
to false as:
edittext.setKeyListener(null);
Now set Editable property of EditText
to true as:
editText.setKeyListener(variable);
Note: In XML the default Editable property of EditText
should be true.
{
isloading? progressIos:Container()
progressIos(int i) {
return Container(
color: i == 1
? AppColors.liteBlack
: i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
child: Center(child: CupertinoActivityIndicator()));
}
}
A couple of code examples in C# using SelectNextControl.
The first moves to the next control when ENTER is pressed.
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( (e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return) )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
The second uses the UP and DOWN arrows to move through the controls.
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( e.KeyCode == Keys.Up )
{
this.SelectNextControl( (Control)sender, false, true, true, true );
}
else if( e.KeyCode == Keys.Down )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
See MSDN SelectNextControl Method
You will need to use ArrayList<String>
or such.
List<String>
is an interface.
Use this:
import java.util.ArrayList;
...
List<String> supplierNames = new ArrayList<String>();
What I am thinking is having webpack would be easy when production release.
If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:
type User = {
Username?: string;
Email?: string;
}
This CSS3 will make you line through property more easier, and working fine.
span{
text-decoration: line-through;
text-decoration-color: red;
}
I found "Choose a Collection" section of Microsoft Docs on Collection and Data Structure page really useful
C# Collections and Data Structures : Choose a collection
And also the following matrix to compare some other features
For JAVA 7 the download link is jce-7-download
Copy the two downloaded jars in Java\jdk1.7.0_10\jre\lib\security
Take a backup of older jars to be on safer side.
For JAVA 8 the download link is jce-8-download
Copy the downloaded jars in Java\jdk1.8.0_45\jre\lib\security
Take a backup of older jars to be on safer side.
<style name="captionOnly">
<item name="android:background">@null</item>
<item name="android:clickable">false</item>
<item name="android:focusable">false</item>
<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>
</style>
<FrameLayout
style="?android:attr/buttonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
style="@style/captionOnly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@android:drawable/ic_delete"
android:gravity="center"
android:text="Button Challenge" />
</FrameLayout>
Put the FrameLayout in LinearLayout and set orientation to Horizontal.
Sometimes I'm asked to use some pretty odd grid layouts in existing bootstrap websites (without messing up the current code). What I have done is create a separate CSS file which i can just drop into current bootstrap projects and use the grid layout styles in there. Here is what the bootstrap-5ths.css file contains along with an example of how it looks for bootstrap version 4.
If you want to use this with bootstrap version 3, just remove the col-xl-* styles and change the min-widths from 576px to 768px, 768px to 992px and 992px to 1200px.
.col-xs-5ths, .col-sm-5ths, .col-md-5ths, .col-lg-5ths, .col-xl-5ths, _x000D_
.col-xs-two5ths, .col-sm-two5ths, .col-md-two5ths, .col-lg-two5ths, .col-xl-two5ths, _x000D_
.col-xs-three5ths, .col-sm-three5ths, .col-md-three5ths, .col-lg-three5ths, .col-xl-three5ths, _x000D_
.col-xs-four5ths, .col-sm-four5ths, .col-md-four5ths, .col-lg-four5ths, .col-xl-four5ths, _x000D_
.col-xs-five5ths, .col-sm-five5ths, .col-md-five5ths, .col-lg-five5ths, .col-xl-five5ths, _x000D_
{_x000D_
position: relative;_x000D_
min-height: 1px;_x000D_
padding-right: 15px;_x000D_
padding-left: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 576px) {_x000D_
.col-sm-5ths {width: 20%;float: left;}_x000D_
.col-sm-two5ths {width: 40%;float: left;}_x000D_
.col-sm-three5ths {width: 60%;float: left;}_x000D_
.col-sm-four5ths {width: 80%;float: left;}_x000D_
}_x000D_
_x000D_
@media (min-width: 768px) {_x000D_
.col-md-5ths {width: 20%;float: left;}_x000D_
.col-md-two5ths {width: 40%;float: left;}_x000D_
.col-md-three5ths {width: 60%;float: left;}_x000D_
.col-md-four5ths {width: 80%;float: left;}_x000D_
}_x000D_
_x000D_
@media (min-width: 992px) {_x000D_
.col-lg-5ths {width: 20%;float: left;}_x000D_
.col-lg-two5ths {width: 40%;float: left;}_x000D_
.col-lg-three5ths {width: 60%;float: left;}_x000D_
.col-lg-four5ths {width: 80%;float: left;}_x000D_
}_x000D_
_x000D_
@media (min-width: 1200px) {_x000D_
.col-xl-5ths {width: 20%;float: left;}_x000D_
.col-xl-two5ths {width: 40%;float: left;}_x000D_
.col-xl-three5ths {width: 60%;float: left;}_x000D_
.col-xl-four5ths {width: 80%;float: left;}_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-5ths">1</div>_x000D_
<div class="col-md-5ths">1</div>_x000D_
<div class="col-md-5ths">1</div>_x000D_
<div class="col-md-5ths">1</div>_x000D_
<div class="col-md-5ths">1</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-5ths">1</div>_x000D_
<div class="col-md-two5ths">2</div>_x000D_
<div class="col-md-two5ths">2</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-three5ths">3</div>_x000D_
<div class="col-md-two5ths">2</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-four5ths">4</div>_x000D_
<div class="col-md-5ths">1</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-five5ths">5</div>_x000D_
</div>_x000D_
</div>
_x000D_
To set JDK you can watch this video : how to set JDK . Then when you'll have JDK:
Solve that by using std::basic_string<TCHAR>
instead of std::string
and it should work fine regardless of your character setting.
One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.
For instance :
$arr = array(
'a' => 123,
'b' => 456,
'c' => 789,
);
foreach ($arr as $key => $item) {
if ($item == 456) {
unset($arr[$key]);
}
}
var_dump($arr);
Will give you this array, in the end :
array
'a' => int 123
'c' => int 789
Which means that, in your case, something like this should do the trick :
foreach($images as $key => $image)
{
if($image == 'http://i27.tinypic.com/29yk345.gif' ||
$image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
$image == 'http://i42.tinypic.com/9pp2456x.gif')
{
unset($images[$key]);
}
}
I had the same issue on Linux with Jupyter.
To solve it I've added the dot library to python sys.path
First: check if dot
is installed,
Then:
find his path whereis dot
-> /local/notebook/miniconda2/envs/ik2/bin/dot
Finally in python script : sys.path.append("/local/notebook/miniconda2/envs/ik2/bin/dot")
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
In my case just changing the permissions of anaconda folder worked:
sudo chmod -R u=rwx,g=rx,o=rx /path/to/anaconda
mysql> GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';
The wildcard character is a "%" instead of an "*"
I ran into the same problem with audio fading and HTML5 player. It got stuck when tab became inactive. So I found out a WebWorker is allowed to use intervals/timeouts without limitation. I use it to post "ticks" to the main javascript.
WebWorkers Code:
var fading = false;
var interval;
self.addEventListener('message', function(e){
switch (e.data) {
case 'start':
if (!fading){
fading = true;
interval = setInterval(function(){
self.postMessage('tick');
}, 50);
}
break;
case 'stop':
clearInterval(interval);
fading = false;
break;
};
}, false);
Main Javascript:
var player = new Audio();
player.fader = new Worker('js/fader.js');
player.faderPosition = 0.0;
player.faderTargetVolume = 1.0;
player.faderCallback = function(){};
player.fadeTo = function(volume, func){
console.log('fadeTo called');
if (func) this.faderCallback = func;
this.faderTargetVolume = volume;
this.fader.postMessage('start');
}
player.fader.addEventListener('message', function(e){
console.log('fader tick');
if (player.faderTargetVolume > player.volume){
player.faderPosition -= 0.02;
} else {
player.faderPosition += 0.02;
}
var newVolume = Math.pow(player.faderPosition - 1, 2);
if (newVolume > 0.999){
player.volume = newVolume = 1.0;
player.fader.postMessage('stop');
player.faderCallback();
} else if (newVolume < 0.001) {
player.volume = newVolume = 0.0;
player.fader.postMessage('stop');
player.faderCallback();
} else {
player.volume = newVolume;
}
});
int min and max values
Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807
i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64
if you always want a to be grater that b why do you need to check it? just set it to be true always
I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
One more way assume branch1 - is branch with committed changes branch2 - is desirable branch
git fetch && git checkout branch1
git log
select commit ids that you need to move
git fetch && git checkout branch2
git cherry-pick commit_id_first..commit_id_last
git push
Now revert unpushed commits from initial branch
git fetch && git checkout branch1
git reset --soft HEAD~1
You can't "execute" a DLL. You can execute functions within the DLL, as explained in the other answers. Although .EXE files and .DLL files are essentially identical in terms of format, the distinguishing feature of an .EXE is that it contains a designated "entry point" to go and do the thing the EXE was created to do. DLLs actually have something similar, but the purpose of the "dll main" is just to perform initialization and not fulfill the primary purpose of the DLL; that is for the (presumably) various other functions it contains.
You can execute any of the functions exported by a DLL, assuming you know which one you want to execute; an EXE may contain a whole lot of functions, but one and only one is specially designated to be executed simply by "running" it.
Try this way.
Date.prototype.addSeconds = function(seconds) {
var copiedDate = new Date(this.getTime());
return new Date(copiedDate.getTime() + seconds * 1000);
}
Just call and assign new Date().addSeconds(10)
This is a clever little trick (that I think I've seen on SO before):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
That is, with the above:
Supporting negative numbers is left as an exercise ;-)
Happy coding.
You should use BFG Repo-Cleaner.
According to the website:
The BFG is a simpler, faster alternative to git-filter-branch for cleansing bad data out of your Git repository history:
- Removing Crazy Big Files
- Removing Passwords, Credentials & other Private data
The classic procedure for reducing the size of a repository would be:
git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --strip-biggest-blobs 500 some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push
Use the getResourceAsStream()
method on the ServletContext object, e.g.
servletContext.getResourceAsStream("/WEB-INF/myfile");
How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?
EDITED: If you're inside a Servlet object, then call getServletContext()
. If you're in JSP, use the predefined variable application
.
Same thing just happened to me on Google Chrome v22.0.1221.1 (Nvidia GPU).
The workaround was to disable GPU compositing on all pages (setting available on chrome://flags/
)
If it happens in Chrome version > 45.x, See answer https://stackoverflow.com/a/32955808/293023 by @detale.
Use google-chrome -disable-gpu
from the command line to temporary disable gpu.
Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.
// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size = filesize($file);
header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );
From http://yassershaikh.com/what-is-the-difference-between-strings-and-stringbuilder-in-c-net/
Short Answer : String is immutable – whereas StringBuilder is mutable.
What does that mean ? Wiki says : In object-oriented, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.
From the StringBuilder Class documentation:
The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object.
In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
You can use the Java enum TimeUnit
to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...)
and a pair of StringBuilder
(s) as well as a DecimalFormat
to build the requested output. Something like,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
: "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
: "hours"));
sb.append(String.format("%d %s and ", minutesCount,
(minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
(secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
new DecimalFormat("#,###").format(secondsIn), sb, sb2);
Which, when I enter 500000
outputs the requested (manual line break added for post) -
You entered 500,000 seconds, which is 5 days, 18 hours,
53 minutes and 20 seconds. (5 days, 18:53:20 hours)
In my opinion you have two options:
Just try to convert it to an int
, but catch the exception:
try:
value = int(value)
except ValueError:
pass # it was a string, not an int.
This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit()
returns True
only if all characters in the string are digits (0
-9
).
The unicode
/ Python 3 str
type equivalent is unicode.isdecimal()
/ str.isdecimal()
; only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).
This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int()
values, as whitespace and +
and -
are also allowed in int()
values. The first form will happily accept ' +10 '
as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.
This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
SELECT * FROM NOTES ORDER BY UPPER(title)
document.getElementById('tries').scrollIntoView()
works. This works better than window.location.hash
when you have fixed positioning.
Key differences:
C++ is a general-purpose programming language, but is developed from the originally C programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ was originally named C with Classes. It was renamed C++ in 1983.
Visual C++, on the other hand, is not a programming language at all. It is in fact a development environment. It is an “integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages.” Microsoft Visual C++, also known as MSVC or VC++, is sold as part of the Microsoft Visual Studio app.
You can maintain your html as it is but use this php code
<?php
$name = $_POST['name'];
$purchase1 = $_POST['Tea'];
$purchase2 =$_POST['Coffee'];
?>
If you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Otherwise,
var scrollTop = function() {
window.scrollTo(0, 0);
};
should do the trick.
If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.
public static Stream ToStream(this bytes[] bytes)
{
return new MemoryStream(bytes)
{
Position = 0
};
}
first, you need to load URL helper like this type or you can upload within autoload.php file:
$this->load->helper('url');
if (!$user_logged_in)
{
redirect('/account/login', 'refresh');
}
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
Shouldn't you have:
DELETE FROM tableA WHERE entitynum IN (...your select...)
Now you just have a WHERE with no comparison:
DELETE FROM tableA WHERE (...your select...)
So your final query would look like this;
DELETE FROM tableA WHERE entitynum IN (
SELECT tableA.entitynum FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
)
The best way to you fix this problem.
http://www.youtube.com/watch?v=i4WcMIyc8OQ
Good Luck =D
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
You can call listIterator
method again to get an instance of iterator pointing at beginning of list:
iter = list.listIterator();
The asterisk (*) means "zero or more of the previous item".
If you want to match any single character use
sed -i 's/string-./string-0/g' file.txt
If you want to match any string (i.e. any single character zero or more times) use
sed -i 's/string-.*/string-0/g' file.txt
If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/
For architectures (i386 ... i686) use /usr/lib/
I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.
__stdcall
is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.
There are a number of other calling conventions, __cdecl
, __thiscall
, __fastcall
and the wonderfully named __declspec(naked)
. __stdcall
is the standard calling convention for Win32 system calls.
Wikipedia covers the details.
It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.
If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:
//code to refresh the page
var page_y = $( document ).scrollTop();
window.location.href = window.location.href + '?page_y=' + page_y;
//code to handle setting page offset on load
$(function() {
if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
//gets the number from end of url
var match = window.location.href.split('?')[1].match( /\d+$/ );
var page_y = match[0];
//sets the page offset
$( 'html, body' ).scrollTop( page_y );
}
});
I use Eclipse (without Maven) so I place the .properties
file in src
folder that also contains the java source code, in order to have the .properties
file in the classes
folder after building the project. It works fine.
Take a look at this post: https://www.mkyong.com/jsf2/cant-find-bundle-for-base-name-xxx-locale-en_us/
Hope this help you.
Since JVM arguments are eventually passed to your java program as system variables, you can use this code at the beginning of your execution point to edit the property and have log4j read the property you just set in system properties
try {
System.setProperty("log4j.configuration", new File(System.getProperty("user.dir")+File.separator+"conf"+File.separator+"log4j.properties").toURI().toURL().toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
To add an Activity
using Android Studio.
This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.
[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.
To add a Service
, or a BroadcastReceiver
, just do the same step.
Assume your code is looking for the file say app.properties. Copy this file to any dir and add this dir to classpath, by creating a setenv.sh in the bin dir of tomcat.
In your setenv.sh of tomcat( if this file is not existing, create one , tomcat will load this setenv.sh file.
#!/bin/sh
CLASSPATH="$CLASSPATH:/home/user/config_my_prod/"
You should not have your properties files in ./webapps//WEB-INF/classes/app.properties
Tomcat class loader will override the with the one from WEB-INF/classes/
A good read: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
No, LabelEncoder
does not do this. It takes 1-d arrays of class labels and produces 1-d arrays. It's designed to handle class labels in classification problems, not arbitrary data, and any attempt to force it into other uses will require code to transform the actual problem to the problem it solves (and the solution back to the original space).
I think is a little late but
sudo yum install -y gcc ruby-devel libxml2 libxml2-devel libxslt libxslt-devel
worked for me on fedora.
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
If you're using GitHub and haven't yet pushed the commit, GitHub Desktop solves this problem easily:
Another truncate with no rounding solution and example.
Convert 71.950005666 to a single decimal place number (71.9)
1) 71.950005666 * 10.0 = 719.50005666
2) Floor(719.50005666) = 719.0
3) 719.0 / 10.0 = 71.9
select Floor(71.950005666 * 10.0) / 10.0
yarn policies set-version
Use the above command in powershell to upgrade your current yarn version to Latest.It will download the latest yarn release
If you do not have float exceptions enabled (which you shouldn't imho), you can simply say:
double neg_inf = -1/0.0;
This yields negative infinity. If you need a float, you can either cast the result
float neg_inf = (float)-1/0.0;
or use single precision arithmetic
float neg_inf = -1.0f/0.0f;
The result is always the same, there is exactly one representation of negative infinity in both single and double precision, and they convert to each other as you would expect.
Primary key fields should be declared as not null (this is non standard as the definition of a primary key is that it must be unique and not null). But below is a good practice for all multi-column primary keys in any DBMS.
create table foo
(
fooint integer not null
,foobar string not null
,fooval real
,primary key (fooint, foobar)
)
;
You should be able to use non-greedy quantifiers, specifically *?. You're going to probably want the following:
Pattern MY_PATTERN = Pattern.compile("\\[(.*?)\\]");
This will give you a pattern that will match your string and put the text within the square brackets in the first group. Have a look at the Pattern API Documentation for more information.
To extract the string, you could use something like the following:
Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
String s = m.group(1);
// s now contains "BAR"
}
I wrote a simple wrapper called KRNSendEmail that simplify sending email to one method call.
The KRNSendEmail is well documented and added to CocoaPods.
https://github.com/ulian-onua/KRNSendEmail
function isDecimal(num) {
return (num !== parseInt(num, 10));
}
In Card Range Recognition (CRR), a drawback with algorithms that use a series of regex or other hard-coded ranges, is that the BINs/IINs do change over time in my experience. The co-branding of cards is an ongoing complication. Different Card Acquirers / merchants may need you treat the same card differently, depending on e.g. geolocation.
Additionally, in the last few years with e.g. UnionPay cards in wider circulation, existing models do not cope with new ranges that sometimes interleave with broader ranges that they supersede.
Knowing the geography your system needs to cover may help, as some ranges are restricted to use in particular countries. For example, ranges 62 include some AAA sub-ranges in the US, but if your merchant base is outside the US, you may be able to treat all 62 as UnionPay.
You may be also asked to treat a card differently based on merchant location. E.g. to treat certain UK cards as debit domestically, but as credit internationally.
There are very useful set of rules maintained by one major Acquiring Bank. E.g. https://www.barclaycard.co.uk/business/files/BIN-Rules-EIRE.pdf and https://www.barclaycard.co.uk/business/files/BIN-Rules-UK.pdf. (Valid links as of June 2017, thanks to the user who provided a link to updated reference.) But be aware of the caveat that, while these CRR rules may represent the Card Issuing universe as it applies to the merchants acquired by that entity, it does not include e.g. ranges identified as CUP/UPI.
These comments apply to magnetic stripe (MagStripe) or PKE (Pan Key Entry) scenarios. The situation is different again in the ICC/EMV world.
Update: Other answers on this page (and also the linked WikiPedia page) have JCB as always 16 long. However, in my company we have a dedicated team of engineers who certify our POS devices and software across multiple acquiring banks and geographies. The most recent Certification Pack of cards this team have from JCB, had a pass case for a 19 long PAN.
You can do it through storyboard, just disable "Scrolling Enabled":)
Adding below lines in build.gradle solved my issue .
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
I needeed to solve very similar problem, which is configuring Jackson Mapper to "Do not serialize null values for Christ's sake!!!".
I didn't want to leave fancy mvc:annotation-driven tag, so I found, how to configure Jackson's ObjectMapper without removing mvc:annotation-driven and adding not really fancy ContentNegotiatingViewResolver.
The beautiful thing is that you don't have to write any Java code yourself!
And here is the XML configuration (don't be confused with different namespaces of Jackson classes, I simply used new Jakson 2.x library ... the same should also work with Jackson 1.x libraries):
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.
Right Click on your project: Run (As) -> Maven clean Right Click on your project: Run (As) -> Maven install
If you wish to lowercase all values in an nested array, use the following code:
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
So:
[ 'A', 'B', ['C-1', 'C-2'], 'D']
would return:
[ 'a', 'b', ['c-1', 'c-2'], 'd']
Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.
grunt-contrib-uglify
gulp-uglify
--create_source_map
If think this will work:
if(sizeof($response->records)>0)
$role_arr = getRole($response->records);
newly defined proprties included too.
For what it's worth, here's the previously provided code encapsulated within a function.
openWindowWithPost("http://www.example.com/index.php", {
p: "view.map",
coords: encodeURIComponent(coords)
});
Function definition:
function openWindowWithPost(url, data) {
var form = document.createElement("form");
form.target = "_blank";
form.method = "POST";
form.action = url;
form.style.display = "none";
for (var key in data) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = data[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
I presume SELECT user FROM dual;
should give you the current user
and SELECT sys_context('userenv','instance_name') FROM dual;
the name of the instance
I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;
Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. WTF?
Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker:
Bryce Nesbitt on April 4 2008 4:36pm:
On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warning. While not a bug, it's possible to get trapped by this if you write code on a lenient platform, and later run it on a strict platform:
Personally, I do view this as a bug. Searching for "BLOB/TEXT column can't have a default value" returns about 2,940 results on Google. Most of them are reports of incompatibilities when trying to install DB scripts that worked on one system but not others.
I am running into the same problem now on a webapp I'm modifying for one of my clients, originally deployed on Linux MySQL v5.0.83-log. I'm running Windows MySQL v5.1.41. Even trying to use the latest version of phpMyAdmin to extract the database, it doesn't report a default for the text column in question. Yet, when I try running an insert on Windows (that works fine on the Linux deployment) I receive an error of no default on ABC column. I try to recreate the table locally with the obvious default (based on a select of unique values for that column) and end up receiving the oh-so-useful BLOB/TEXT column can't have a default value.
Again, not maintaining basic compatability across platforms is unacceptable and is a bug.
How to disable strict mode in MySQL 5 (Windows):
Edit /my.ini and look for line
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Replace it with
sql_mode='MYSQL40'
Restart the MySQL service (assuming that it is mysql5)
net stop mysql5
net start mysql5
If you have root/admin access you might be able to execute
mysql_query("SET @@global.sql_mode='MYSQL40'");
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
// use `new DepartmentFactory` as given below. `new` is imporatant
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
function sortOn(property){
return function(a, b){
if(a[property] < b[property]){
return -1;
}else if(a[property] > b[property]){
return 1;
}else{
return 0;
}
}
}
//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);
You can also use ls -w1
This allows to set number of columns. From manpage of ls:
-w, --width=COLS
set output width to COLS. 0 means no limit
I was using nano, and it took me a long time to figure out this error. My problem was I was using the wrong port. I had port 5948 instead of 5984.
var nano = require('nano')('http://localhost:5984');
var db = nano.use('address');
var app = express();
android:background="@drawable/eye"
works automatically.
android:src="@drawable/eye"
was what I used with all the problems of resizing the image the the width and height of the button...
STATIC_DEPS=true easy_install lxml
I have an alternative solution for you. You could create a hidden worksheet to maintain the old values for your range of interest.
Private Sub Workbook_Open()
Dim hiddenSheet As Worksheet
Set hiddenSheet = Me.Worksheets.Add
hiddenSheet.Visible = xlSheetVeryHidden
hiddenSheet.Name = "HiddenSheet"
'Change Sheet1 to whatever sheet you're working with
Sheet1.UsedRange.Copy ThisWorkbook.Worksheets("HiddenSheet").Range(Sheet1.UsedRange.Address)
End Sub
Delete it when the workbook is closed...
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
Me.Worksheets("HiddenSheet").Delete
Application.DisplayAlerts = True
End Sub
And modify your Worksheet_Change event like so...
For Each cell In Target
If Not (Intersect(cell, Range("cell_of_interest")) Is Nothing) Then
new_value = cell.Value
' here's your "old" value...
old_value = ThisWorkbook.Worksheets("HiddenSheet").Range(cell.Address).Value
Call DoFoo(old_value, new_value)
End If
Next cell
' Update your "old" values...
ThisWorkbook.Worksheets("HiddenSheet").UsedRange.Clear
Me.UsedRange.Copy ThisWorkbook.Worksheets("HiddenSheet").Range(Me.UsedRange.Address)
In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto)
to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto)
and its working.
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
You will be much happier using a dictionary instead:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
There is a tool for static code analysis called PHP Analyzer. PHP Analyzer is now a deprecated project, but you still can access it on the legacy branch.
Among many types of static analysis it also provides basic auto-fixing functionality, see the documentation.
one line solution: basic idea:
$('sth').click(function () {
let COND = $(this).propery == 'cond1' ? 'cond2' : 'cond1';
doSomeThing(COND);
})
example 1, changing innerHTML of an element in a toggle-mode:
$('#clickTest1').click(function () {
$(this).html($(this).html() == 'click Me' ? 'clicked' : 'click Me');
});
example 2, toggling displays between "none" and "inline-block":
$('#clickTest2, #clickTest2 > span').click(function () {
$(this).children().css('display', $(this).children().css('display') == 'inline-block' ? 'none' : 'inline-block');
});
An alternative solution:
div[class|='tocolor']
will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.
Beware that this won't match
<div class="foo tocolor-">
Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)
You could use QuartzCore and do something this --
self.circleView = [[UIView alloc] initWithFrame:CGRectMake(10,20,100,100)];
self.circleView.alpha = 0.5;
self.circleView.layer.cornerRadius = 50; // half the width/height
self.circleView.backgroundColor = [UIColor blueColor];
Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser). Then just add the needed number of milliseconds to it.
var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );_x000D_
_date.setUTCMilliseconds(1270544790922);_x000D_
_x000D_
alert(_date); //date shown shifted corresponding to local time settings_x000D_
alert(_date.getUTCFullYear()); //the UTC year value_x000D_
alert(_date.getUTCMonth()); //the UTC month value_x000D_
alert(_date.getUTCDate()); //the UTC day of month value_x000D_
alert(_date.getUTCHours()); //the UTC hour value_x000D_
alert(_date.getUTCMinutes()); //the UTC minutes value
_x000D_
Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings. Otherwise date values will be shifted corresponding to local time settings.
int range = max - min + 1;
int num = rand() % range + min;
=============UPDATE=============
Since Android Studio introduce a new build system: Gradle. Android developers can now use a simple, declarative DSL to have access to a single, authoritative build that powers both the Android Studio IDE and builds from the command-line.
Edit your build.gradle
like this:
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
defaultConfig {
minSdkVersion 18
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:21.+'
}
NOTES: Use + in compile 'com.android.support:support-v4:21.+'
so that gradle can always use the newest version.
==========DEPRECATED==========
Because Android Studio is based on IntelliJ IDEA, so the procedure is just same like on IntelliJ IDEA 12 CE
1.Open Project Structure (Press F4 on PC and Command+; on MAC) on your project).
2.Select Modules on the left pane.
3.Choose your project and you will see Dependencies TAB above the third Column.
4.Click on the plus sign in the bottom. Then a tree-based directory chooser dialog will pop up, navigate to your folder containing android-support-v4.jar, press OK.
5.Press OK.
May be this will be usefull for u: ReGExp on-line editor
Pod `Alamofire` has `NetworkReachabilityManager`, you just have to create one function
func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
To check whether the frame have been loaded, use onload function. Or put your main function in load: I recommend to use load when creating the iframe by js
$('<iframe />', {
src: url,
id: 'receiver',
frameborder: 1,
load:function(){
//put your code here, so that those code can be make sure to be run after the frame loaded
}
}).appendTo('body');
You can use the provided system views to do this:
eg
select * from INFORMATION_SCHEMA.COLUMNS
where table_name = '[table name]'
alternatively, you can use the system proc sp_help
eg
sp_help '[table name]'
Add an :order parameter to the query
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
DataTable dt = new DataTable();
dt.Load(reader);
int numRows= dt.Rows.Count;
If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:
public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T), true);
return atts.Length > 0;
}
which you can use like typeof(Foo).HasAttribute<BarAttribute>();
Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:
ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
Since GDB 7.5 you can use these native Convenience Functions:
$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)
Seems quite less problematic than having to execute a "foreign" strcmp()
on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.
Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running
show configuration
inside GDB and searching for--with-python
. This little oneliner does the trick, too:$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python' --with-python=/usr (relocatable)
For your demo case, the usage would be
break <where> if $_streq(x, "hello")
or, if your breakpoint already exists and you just want to add the condition to it
condition <breakpoint number> $_streq(x, "hello")
$_streq
only matches the whole string, so if you want something more cunning you should use $_regex
, which supports the Python regular expression syntax.
Right_click on the drawable and create new layout xml file in the name of for example button_background.xml. then copy and paste the following code. You can change it according your need.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="14dp" />
<solid android:color="@color/colorButton" />
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<size
android:width="120dp"
android:height="40dp" />
</shape>
Now you can use it.
<Button
android:background="@drawable/button_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
if you are facing this error in windows with android
open your root directory app folder and move into android folder .
cd android
gradlew clean
start your app again react-native run-android
bhooom it works
Usually I go about parsing instead of sourcing, to avoid complexities of certain artifacts in my file. It also offers me ways to specially handle quotes and other things. My main aim is to keep whatever comes after the '=' as a literal, even the double quotes and spaces.
#!/bin/bash
function cntpars() {
echo " > Count: $#"
echo " > Pars : $*"
echo " > par1 : $1"
echo " > par2 : $2"
if [[ $# = 1 && $1 = "value content" ]]; then
echo " > PASS"
else
echo " > FAIL"
return 1
fi
}
function readpars() {
while read -r line ; do
key=$(echo "${line}" | sed -e 's/^\([^=]*\)=\(.*\)$/\1/')
val=$(echo "${line}" | sed -e 's/^\([^=]*\)=\(.*\)$/\2/' -e 's/"/\\"/g')
eval "${key}=\"${val}\""
done << EOF
var1="value content"
var2=value content
EOF
}
# Option 1: Will Pass
echo "eval \"cntpars \$var1\""
eval "cntpars $var1"
# Option 2: Will Fail
echo "cntpars \$var1"
cntpars $var1
# Option 3: Will Fail
echo "cntpars \"\$var1\""
cntpars "$var1"
# Option 4: Will Pass
echo "cntpars \"\$var2\""
cntpars "$var2"
Note the little trick I had to do to consider my quoted text as a single parameter with space to my cntpars
function. There was one extra level of evaluation required. If I wouldn't do this, as in Option 2, I would have passed 2 parameters as follows:
"value
content"
Double quoting during command execution causes the double quotes from the parameter file to be kept. Hence the 3rd Option also fails.
The other option would be of course to just simply not provide variables in double quotes, as in Option 4, and then just to make sure that you quote them when needed.
Just something to keep in mind.
Another thing I like to do is to do a real-time lookup, avoiding the use of environment variables:
lookup() {
if [[ -z "$1" ]] ; then
echo ""
else
${AWK} -v "id=$1" 'BEGIN { FS = "=" } $1 == id { print $2 ; exit }' $2
fi
}
MY_LOCAL_VAR=$(lookup CONFIG_VAR filename.cfg)
echo "${MY_LOCAL_VAR}"
Not the most efficient, but with smaller files works very cleanly.
Things have changed quite a bit since 2010 when this was posted and I haven't tried all the other answers but I have tried a few, and I found this to work the best for me using python3.6.
I was able to fetch about ~150 unique domains per second running on AWS.
import pandas as pd
import concurrent.futures
import requests
import time
out = []
CONNECTIONS = 100
TIMEOUT = 5
tlds = open('../data/sample_1k.txt').read().splitlines()
urls = ['http://{}'.format(x) for x in tlds[1:]]
def load_url(url, timeout):
ans = requests.head(url, timeout=timeout)
return ans.status_code
with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
future_to_url = (executor.submit(load_url, url, TIMEOUT) for url in urls)
time1 = time.time()
for future in concurrent.futures.as_completed(future_to_url):
try:
data = future.result()
except Exception as exc:
data = str(type(exc))
finally:
out.append(data)
print(str(len(out)),end="\r")
time2 = time.time()
print(f'Took {time2-time1:.2f} s')
print(pd.Series(out).value_counts())
Follow this steps to overcome the issue.
NOTE:-
1) You should not have different instances of Android Debug Bridge(adb) running on system.
2) If using Genymotion then make sure that you use the custom sdk path mentioned in the Genymotion settings the which you mentioned in the settings of Android Studio.
Follow all the steps and I am sure you will get the issue fix.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
alert("Hello!");
}
</script>
</body>
</html>
Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.
$ sudo killall -u username && sudo deluser --remove-home -f username
The killall
command is used if multiple processes are used by the user you want to delete.
The -f
option forces the removal of the user account, even if the user is still logged in. It also forces deluser
to remove the user's home directory and mail spool, even if another user uses the same home directory.
Please confirm that it works in the comments.
NPX:
Web developers can have dozens of projects on their development machines, and each project has its own particular set of npm-installed dependencies. A few years back, the usual advice for dealing with CLI applications like Grunt or Gulp was to install them locally in each project and also globally so they could easily be run from the command line.
But installing globally caused as many problems as it solved. Projects may depend on different versions of command line tools, and polluting the operating system with lots of development-specific CLI tools isn’t great either. Today, most developers prefer to install tools locally and leave it at that.
Local versions of tools allow developers to pull projects from GitHub without worrying about incompatibilities with globally installed versions of tools. NPM can just install local versions and you’re good to go. But project specific installations aren’t without their problems: how do you run the right version of the tool without specifying its exact location in the project or playing around with aliases?
That’s the problem npx solves. A new tool included in NPM 5.2, npx is a small utility that’s smart enough to run the right application when it’s called from within a project.
If you wanted to run the project-local version of mocha, for example, you can run npx mocha inside the project and it will do what you expect.
A useful side benefit of npx is that it will automatically install npm packages that aren’t already installed. So, as the tool’s creator Kat Marchán points out, you can run npx benny-hill without having to deal with Benny Hill polluting the global environment.
If you want to take npx for a spin, update to the most recent version of npm.
They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.
Something like this:
typedef struct vec
{
unsigned char* _mem;
unsigned long _elems;
unsigned long _elemsize;
unsigned long _capelems;
unsigned long _reserve;
};
vec* vec_new(unsigned long elemsize)
{
vec* pvec = (vec*)malloc(sizeof(vec));
pvec->_reserve = 10;
pvec->_capelems = pvec->_reserve;
pvec->_elemsize = elemsize;
pvec->_elems = 0;
pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
return pvec;
}
void vec_delete(vec* pvec)
{
free(pvec->_mem);
free(pvec);
}
void vec_grow(vec* pvec)
{
unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
free(pvec->_mem);
pvec->_mem = mem;
pvec->_capelems += pvec->_reserve;
}
void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
assert(elemsize == pvec->_elemsize);
if (pvec->_elems == pvec->_capelems) {
vec_grow(pvec);
}
memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
pvec->_elems++;
}
unsigned long vec_length(vec* pvec)
{
return pvec->_elems;
}
void* vec_get(vec* pvec, unsigned long index)
{
assert(index < pvec->_elems);
return (void*)(pvec->_mem + (index * pvec->_elemsize));
}
void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}
void playwithvec()
{
vec* pvec = vec_new(sizeof(int));
for (int val = 0; val < 1000; val += 10) {
vec_push_back(pvec, &val, sizeof(val));
}
for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
int val;
vec_copy_item(pvec, &val, index);
printf("vec(%d) = %d\n", index, val);
}
vec_delete(pvec);
}
Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.
The coalesce() is the best solution when there are multiple columns [and]/[or] values and you want the first one. However, looking at books on-line, the query optimize converts it to a case statement.
MSDN excerpt
The COALESCE expression is a syntactic shortcut for the CASE expression.
That is, the code COALESCE(expression1,...n) is rewritten by the query optimizer as the following CASE expression:
CASE
WHEN (expression1 IS NOT NULL) THEN expression1
WHEN (expression2 IS NOT NULL) THEN expression2
...
ELSE expressionN
END
With that said, why not a simple ISNULL()? Less code = better solution?
Here is a complete code snippet.
-- drop the test table
drop table #temp1
go
-- create test table
create table #temp1
(
issue varchar(100) NOT NULL,
total_amount int NULL
);
go
-- create test data
insert into #temp1 values
('No nulls here', 12),
('I am a null', NULL);
go
-- isnull works fine
select
isnull(total_amount, 0) as total_amount
from #temp1
Last but not least, how are you getting null values into a NOT NULL column?
I had to change the table definition so that I could setup the test case. When I try to alter the table to NOT NULL, it fails since it does a nullability check.
-- this alter fails
alter table #temp1 alter column total_amount int NOT NULL
If one of you guys are using virtual terminal in proteus and want to clear it just add Serial.write(0x0C); and it gonna work fine
json loads -> returns an object from a string representing a json object.
json dumps -> returns a string representing a json object from an object.
load and dump -> read/write from/to file instead of string
put your session() auth in all server side pages accepting an ajax request:
if(require_once("auth.php")) {
//run json code
}
// do nothing otherwise
that's about the only way I've ever done it.
A back link is a link that moves the browser backwards one page, as if the user had clicked the Back button available in most browsers. Back links use JavaScript. It moves the browser back one page if your browser supports JavaScript (which it does) and if it supports the window.history
object, which is necessary for back links.
Simple ways are
<a href="#" onClick="history.go(-1)">Go Back</a>
OR:
function goBack() {_x000D_
window.history.back()_x000D_
}
_x000D_
<a href="#" onclick="goBack()" />Go Back</a>
_x000D_
Generally speaking a back link isn't necessary… the Back button usually suffices quite nicely, and usually you can also simply link to the previous page in your site. However, sometimes you might want to provide a link back to one of several "previous" pages, and that's where a back link comes in handy. So I refer you below tutorial if you want to do in more advanced way:
http://www.htmlcodetutorial.com/linking/linking_famsupp_108.html
According to Java Persistence with Hibernate
mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard
If you were using Hibernate, you could do something like:
@org.hibernate.annotations.CollectionOfElements(
targetElement = java.lang.String.class
)
@JoinTable(
name = "foo",
joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();
Update: Note, this is now available in JPA2.
Let's take a look at the start
command.
Open Windows command prompt
To open a new Chrome window (blank), type the following:
start chrome --new-window
or
start chrome
To open a URL in Chrome, type the following:
start chrome --new-window "http://www.iot.qa/2018/02/narrowband-iot.html"
To open a URL in Chrome in incognito mode, type the following:
start chrome --new-window --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"
or
start chrome --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"
This will make extend your properties create a new Object with the object parameter prototypes without altering the passed object.
function extend(object) {
if (object === null)
throw TypeError;
if (typeof object !== "object" && typeof object !== "function")
throw TypeError;
if (Object.create)
return Object.create(object);
function f() {}
;
f.prototype = p;
return new f();
}
But if you want to extend your Object without modifying it parameters, you can add extendProperty to your object.
var Person{
//some code
extend: extendProperty
}
//Enforce type checking an Error report as you wish
function extendProperty(object) {
if ((object !== null && (typeof object === "object" || typeof object === "function"))){
for (var prop in object) {
if (object.hasOwnProperty(prop))
this[prop] = object[prop];
}
}else{
throw TypeError; //Not an object
}
}
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
That would be:
b.rstrip('\n')
If you want to strip space from each and every line, you might consider instead:
a.read().splitlines()
This will give you a list of lines, without the line end characters.
<iframe title='YouTube video player' class='youtube-player' type='text/html'
width='030' height='030'
src='http://www.youtube.com/embed/ZFo8b9DbcMM?rel=0&border=&autoplay=1'
type='application/x-shockwave-flash'
allowscriptaccess='always' allowfullscreen='true'
frameborder='0'></iframe>
just insert your code after embed/
There is Mozilla official solution: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
(function() {
/**Array*/
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (null === this || undefined === this) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
})();
Christoph's answer is perfect. Sometimes however you may want to go more classes up than one. In this case you could try the @at-root
and #{}
css features which would enable two root classes to sit next to each other using &
.
This wouldn't work (due to the nothing before &
rule):
container {_x000D_
background:red;_x000D_
color:white;_x000D_
_x000D_
.desc& {_x000D_
background: blue;_x000D_
}_x000D_
_x000D_
.hello {_x000D_
padding-left:50px;_x000D_
}_x000D_
}
_x000D_
But this would (using @at-root plus #{&}
):
container {_x000D_
background:red;_x000D_
color:white;_x000D_
_x000D_
@at-root .desc#{&} {_x000D_
background: blue;_x000D_
}_x000D_
_x000D_
.hello {_x000D_
padding-left:50px;_x000D_
}_x000D_
}
_x000D_
I hope this little function converts invalid JSON string to valid one.
function JSONize(str) {
return str
// wrap keys without quote with valid double quote
.replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":'})
// replacing single quote wrapped ones to double quote
.replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"'})
}
Result
let invalidJSON = "{ hello: 'world',foo:1, bar : '2', foo1: 1, _bar : 2, $2: 3, 'xxx': 5, \"fuz\": 4, places: ['Africa', 'America', 'Asia', 'Australia'] }"
JSON.parse(invalidJSON)
//Result: Uncaught SyntaxError: Unexpected token h VM1058:2
JSON.parse(JSONize(invalidJSON))
//Result: Object {hello: "world", foo: 1, bar: "2", foo1: 1, _bar: 2…}
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
bin
folder to your PATH environment variablecd
to the place where you want to download (i.e checkout) the projects' code.I had the same task recently and I used the following for sql server 2012 db. Use management studio and connect to the database you want to search. Then execute the following script.
Select
[tgr].[name] as [trigger name],
[tbl].[name] as [table name]
from sysobjects tgr
join sysobjects tbl
on tgr.parent_obj = tbl.id
WHERE tgr.xtype = 'TR'
This seems to be an efficient way to list vars with column number:
cbind(names(df))
Output:
[,1]
[1,] "A"
[2,] "B"
[3,] "C"
Sometimes I like to copy variables with position into my code so I use this function:
varnums<- function(x) {w=as.data.frame(c(1:length(colnames(x))),
paste0('# ',colnames(x)))
names(w)= c("# Var/Pos")
w}
varnums(df)
Output:
# Var/Pos
# A 1
# B 2
# C 3
I am a bit late to answer this but none of the above worked for me.
This is what worked for me
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
//your styles here
}
if your port is 3307 (based on your port)
Add this line in xampp\phpMyAdmin\config.inc: after i++
$cfg['Servers'][$i]['port'] = '3307';