HTML
<input type="button">
CSS
input[type=button]{
background:transparent;
border:0;
}
For Juno: (With Source in E:\workspace and destination in C:\workspace)
Copy project directory in its entirety to the workspace directory. (e.g. Copy E:\workspace\HelloWorld C:\workspace\helloWorld)
Start Eclipse.
Perform: File --> Import
Select: General -- > "Existing Project into Workspace"
"Next >"
Check "Select root Directory"
Select with "Browse Button"
Select "C:\workspace"
A list of existing projects will appear. Just check the ones that are in Bold (To Be Imported) then press the "Finish" button.
Review the Package Explorer and your copied projects should now be there.
I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
addNewStyle('td.EvenRow a {display:inline !important;}')
The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.
Use scrollTop() to get or set the scroll position.
Update for iOS9.2.1 and Xcode 7.2.1
If you get this error when building to a device in Xcode:
On your device, tap the app icon that would have just been added from your attempt at building the app and you should see this:
Next, on your device, go to Settings --> General --> Device Management, and you will see this page:
Select the profile you are using with Xcode, and you should see this page:
Click Trust "[email protected]" then click Trust on the next popup.
Go back to Xcode and re-run your project and it should build the app to your device.
Marek Sebera's is great most of the time, but if you're like me and find that you need to check the iOS version frequently, you don't want to constantly run a macro in memory because you'll experience a very slight slowdown, especially on older devices.
Instead, you want to compute the iOS version as a float once and store it somewhere. In my case, I have a GlobalVariables
singleton class that I use to check the iOS version in my code using code like this:
if ([GlobalVariables sharedVariables].iOSVersion >= 6.0f) {
// do something if iOS is 6.0 or greater
}
To enable this functionality in your app, use this code (for iOS 5+ using ARC):
GlobalVariables.h:
@interface GlobalVariables : NSObject
@property (nonatomic) CGFloat iOSVersion;
+ (GlobalVariables *)sharedVariables;
@end
GlobalVariables.m:
@implementation GlobalVariables
@synthesize iOSVersion;
+ (GlobalVariables *)sharedVariables {
// set up the global variables as a static object
static GlobalVariables *globalVariables = nil;
// check if global variables exist
if (globalVariables == nil) {
// if no, create the global variables class
globalVariables = [[GlobalVariables alloc] init];
// get system version
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
// separate system version by periods
NSArray *systemVersionComponents = [systemVersion componentsSeparatedByString:@"."];
// set ios version
globalVariables.iOSVersion = [[NSString stringWithFormat:@"%01d.%02d%02d", \
systemVersionComponents.count < 1 ? 0 : \
[[systemVersionComponents objectAtIndex:0] integerValue], \
systemVersionComponents.count < 2 ? 0 : \
[[systemVersionComponents objectAtIndex:1] integerValue], \
systemVersionComponents.count < 3 ? 0 : \
[[systemVersionComponents objectAtIndex:2] integerValue] \
] floatValue];
}
// return singleton instance
return globalVariables;
}
@end
Now you're able to easily check the iOS version without running macros constantly. Note in particular how I converted the [[UIDevice currentDevice] systemVersion]
NSString to a CGFloat that is constantly accessible without using any of the improper methods many have already pointed out on this page. My approach assumes the version string is in the format n.nn.nn (allowing for later bits to be missing) and works for iOS5+. In testing, this approach runs much faster than constantly running the macro.
Hope this helps anyone experiencing the issue I had!
The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.
I think there are two different things here. The first one is that normal SSH authentication requires the user to put the account's password (where the account password will be authenticated against different methods, depending on the sshd configuration).
You can avoid putting that password using certificates. With certificates you still have to put a password, but this time is the password of your private key (that's independent of the account's password).
To do this you can follow the instructions pointed out by steveth45:
If you want to avoid putting the certificate's password every time then you can use ssh-agent, as pointed out by DigitalRoss
The exact way you do this depends on Unix vs Windows, but essentially you need to run ssh-agent in the background when you log in, and then the first time you log in, run ssh-add to give the agent your passphrase. All ssh-family commands will then consult the agent and automatically pick up your passphrase.
Start here: man ssh-agent.
The only problem of ssh-agent is that, on *nix at least, you have to put the certificates password on every new shell. And then the certificate is "loaded" and you can use it to authenticate against an ssh server without putting any kind of password. But this is on that particular shell.
With keychain you can do the same thing as ssh-agent but "system-wide". Once you turn on your computer, you open a shell and put the password of the certificate. And then, every other shell will use that "loaded" certificate and your password will never be asked again until you restart your PC.
Gnome has a similar application, called Gnome Keyring that asks for your certificate's password the first time you use it and then it stores it securely so you won't be asked again.
Try this, this works for my code name is a String:
cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
ROLEID, NATIONALID, URL, IMAGEURL },
LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);
You can use ES6 backtick syntax too
<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>
For anyone meaning to do this more reliably for different Minecraft versions, I have a Python script (adapted from parts of minecraft-launcher-lib) that does the job very nicely
Besides setting some basic variables near the top after the functions, it calls a get_classpath
that goes through for example ~/.minecraft/versions/1.16.5/1.16.5.json
, and loops over the libraries
array, checking to see if each object (within the array), is supposed to be added to the classpath (cp
variable). whether this library is added to the java classpath is governed by the should_use_library
function, deterministic based on the computer's architecture and operating system. finally, some jarfiles that are platform specific have extra things prepended to them (ex. natives-linux
in org/lwjgl/lwjgl/3.2.1/lwjgl-3.2.1-natives-linux.jar
). this extra prepended string is handled by get_natives_string
and is empty if it doesn't apply to the current library
tested on Linux, distribution Arch Linux
#!/usr/bin/env python
import json
import os
import platform
from pathlib import Path
import subprocess
"""Debug output
"""
def debug(str):
if os.getenv('DEBUG') != None:
print(str)
"""
[Gets the natives_string toprepend to the jar if it exists. If there is nothing native specific, returns and empty string]
"""
def get_natives_string(lib):
arch = ""
if platform.architecture()[0] == "64bit":
arch = "64"
elif platform.architecture()[0] == "32bit":
arch = "32"
else:
raise Exception("Architecture not supported")
nativesFile=""
if not "natives" in lib:
return nativesFile
# i've never seen ${arch}, but leave it in just in case
if "windows" in lib["natives"] and platform.system() == 'Windows':
nativesFile = lib["natives"]["windows"].replace("${arch}", arch)
elif "osx" in lib["natives"] and platform.system() == 'Darwin':
nativesFile = lib["natives"]["osx"].replace("${arch}", arch)
elif "linux" in lib["natives"] and platform.system() == "Linux":
nativesFile = lib["natives"]["linux"].replace("${arch}", arch)
else:
raise Exception("Platform not supported")
return nativesFile
"""[Parses "rule" subpropery of library object, testing to see if should be included]
"""
def should_use_library(lib):
def rule_says_yes(rule):
useLib = None
if rule["action"] == "allow":
useLib = False
elif rule["action"] == "disallow":
useLib = True
if "os" in rule:
for key, value in rule["os"].items():
os = platform.system()
if key == "name":
if value == "windows" and os != 'Windows':
return useLib
elif value == "osx" and os != 'Darwin':
return useLib
elif value == "linux" and os != 'Linux':
return useLib
elif key == "arch":
if value == "x86" and platform.architecture()[0] != "32bit":
return useLib
return not useLib
if not "rules" in lib:
return True
shouldUseLibrary = False
for i in lib["rules"]:
if rule_says_yes(i):
return True
return shouldUseLibrary
"""
[Get string of all libraries to add to java classpath]
"""
def get_classpath(lib, mcDir):
cp = []
for i in lib["libraries"]:
if not should_use_library(i):
continue
libDomain, libName, libVersion = i["name"].split(":")
jarPath = os.path.join(mcDir, "libraries", *
libDomain.split('.'), libName, libVersion)
native = get_natives_string(i)
jarFile = libName + "-" + libVersion + ".jar"
if native != "":
jarFile = libName + "-" + libVersion + "-" + native + ".jar"
cp.append(os.path.join(jarPath, jarFile))
cp.append(os.path.join(mcDir, "versions", lib["id"], f'{lib["id"]}.jar'))
return os.pathsep.join(cp)
version = '1.16.5'
username = '{username}'
uuid = '{uuid}'
accessToken = '{token}'
mcDir = os.path.join(os.getenv('HOME'), '.minecraft')
nativesDir = os.path.join(os.getenv('HOME'), 'versions', version, 'natives')
clientJson = json.loads(
Path(os.path.join(mcDir, 'versions', version, f'{version}.json')).read_text())
classPath = get_classpath(clientJson, mcDir)
mainClass = clientJson['mainClass']
versionType = clientJson['type']
assetIndex = clientJson['assetIndex']['id']
debug(classPath)
debug(mainClass)
debug(versionType)
debug(assetIndex)
subprocess.call([
'/usr/bin/java',
f'-Djava.library.path={nativesDir}',
'-Dminecraft.launcher.brand=custom-launcher',
'-Dminecraft.launcher.version=2.1',
'-cp',
classPath,
'net.minecraft.client.main.Main',
'--username',
username,
'--version',
version,
'--gameDir',
mcDir,
'--assetsDir',
os.path.join(mcDir, 'assets'),
'--assetIndex',
assetIndex,
'--uuid',
uuid,
'--accessToken',
accessToken,
'--userType',
'mojang',
'--versionType',
'release'
])
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
Using static
will not help your case.
Using synchronize
locks a variable when it is in use by another thread.
You should use volatile
keyword to keep the variable updated among all threads.
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.
If you're happy to ignore the time portion in the columns, DATEDIFF() will give you the difference you're looking for in days.
SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
| 17 |
+------+
As Pax rightly said, measure, don't guess. That what I did for DNSwitness and the results were suprising: the ideal number of threads was much higher than I thought, something like 15,000 threads to get the fastest results.
Of course, it depends on many things, that's why you must measure yourself.
Complete measures (in French only) in Combien de fils d'exécution ?.
Just remove the comma like this:
<article class="column wrapper">
Quick solution:
add code to main function:
String log4jConfPath = "/path/to/log4j.properties";
PropertyConfigurator.configure(log4jConfPath);
create a file named log4j.properties at /path/to
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
As to "how do you calculate" Big O, this is part of Computational complexity theory. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.
If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic "worst case" analysis I have found Amortized analysis very useful in practice.
This code is actually used to add values to the dictionary
and through
the data to an Array
According to the Key
.
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSDictionary *dicto = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Hello",@"StackOverFlow",@"Key1",@"StackExchange",@"Key2", nil];
NSLog(@"The dictonary is = %@", dicto);
arr = [dicto valueForKey:@"Key1"];
NSLog(@"The array is = %@", arr);
I found a better solution on the Chrome product forums by a user called Gary. The original thread is here.
Navigate to C:\Windows\System32\GroupPolicy
Open each subdirectory there and change the *.pol
files to *.sav
, E.g. registry.pol
becomes registry.sav
.
Hit Windows-Key + R, type the following in the box and hit enter
reg delete HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome
In the command promt window that opens type: Yes and press Enter.
Restart Google Chrome and check whether you can change the search engine.
I just had this on OSX running brew and [email protected]
.
My fix was this:
CONFIGURE_ARGS="with-pg-include=/usr/local/opt/[email protected]/include/" bundle install
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
<a href="javascript:alert('Please be sure to set your printer to Landscape.');window.print();">Print Me...</a>
or
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>
Download the server response as an array buffer. Store it as a Blob using the content type from the server (which should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
):
var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
{ type: response.headers('Content-Type') }), fileName));
Save the blob to the user's device:
save(blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) { // For IE:
navigator.msSaveBlob(blob, fileName);
} else { // For other browsers:
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
This command disables only first console warning info
Result: console result
You can do like this:
INSERT INTO DENI/FRIEN01P
SELECT
RCRDID+112,
PROFESION,
NAME,
SURNAME,
AGE,
RCRDTYP,
RCRDLCU,
RCRDLCT,
RCRDLCD
FROM
FRIEN01P
There instead of 112 you should put a number of the maximum id in table DENI/FRIEN01P.
I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:
from itertools import chain
def involved(courses, person):
courses_info = chain.from_iterable(x.values() for x in courses.values())
return filter(lambda x: x['teacher'] == person, courses_info)
print involved(courses, 'Dave')
The first thing I do is getting the list of the courses and then filter by teacher's name.
There are two cases in which this error is raised.
As others have said, it is valid.
There are some downsides to each approach though:
href="#"
adds an extra entry to the browser history (which is annoying when e.g. back-buttoning).
href=""
reloads the page
href="javascript:;"
does not seem to have any problems (other than looking messy and meaningless) - anyone know of any?
If pip doesn't come with your installation of python 3.6, this may work:
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
then you can python -m install
As a workaround to force the evaluation of the SELECT clause before the WHERE clause, you could put the former in a sub-query while the latter remains in the main query:
SELECT * FROM (
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices) AS temp
WHERE BalanceDue > 0
You can create spinner by these simple steps
first create spinner in xml
<Spinner
android:id="@+id/select"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#070707"></Spinner>
now create string arary in values
<string-array name="itemselect">
<item>Repurchase</item>
<item>Coupons</item>
</string-array>
now initialized in java file
public class MemberCart_Activity extends AppCompatActivity {
Spinner select;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_cart);
select=findViewById(R.id.select);
ArrayAdapter<String> myadapter=new ArrayAdapter<String>(Main_Activity.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.itemselect));
myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
select.setAdapter(myadapter);
In Pass By Reference You only add "ref" in the function parameters and one
more thing you should be declaring function "static" because of main is static(#public void main(String[] args)
)!
namespace preparation
{
public class Program
{
public static void swap(ref int lhs,ref int rhs)
{
int temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a = 10;
int b = 80;
Console.WriteLine("a is before sort " + a);
Console.WriteLine("b is before sort " + b);
swap(ref a, ref b);
Console.WriteLine("");
Console.WriteLine("a is after sort " + a);
Console.WriteLine("b is after sort " + b);
}
}
}
The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.
To use the yaml module is extremely simple:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
Use the .Replace() method
Line.Replace("\n", "whatever you want to replace with");
In IPython (jupyter
) 7.3 and later, there is a magic %pip
and %conda
command that will install into the current kernel (rather than into the instance of Python that launched the notebook).
%pip install geocoder
In earlier versions, you need to use sys to fix the problem like in the answer by FlyingZebra1
import sys
!{sys.executable} -m pip install geocoder
This does work for a specific delimiter for a specific amount of characters between the delimiter. I had many issues attempting to use this in a for each loop where the position changed but the delimiter was the same. For example I was using the backslash as the delimiter and wanted to only use everything to the right of the backslash. The issue was that once the position was defined (71 characters from the beginning) it would use $pos as 71 every time regardless of where the delimiter actually was in the script. I found another method of using a delimiter and .split to break things up then used the split variable to call the sections For instance the first section was $variable[0] and the second section was $variable[1].
To make sure a click only actions once use this:
$(".bet").unbind().click(function() {
//Stuff
});
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
Here's a Kotlin extension function:
fun EditText.transformIntoDatePicker(context: Context, format: String, maxDate: Date? = null) {
isFocusableInTouchMode = false
isClickable = true
isFocusable = false
val myCalendar = Calendar.getInstance()
val datePickerOnDataSetListener =
DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, monthOfYear)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val sdf = SimpleDateFormat(format, Locale.UK)
setText(sdf.format(myCalendar.time))
}
setOnClickListener {
DatePickerDialog(
context, datePickerOnDataSetListener, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)
).run {
maxDate?.time?.also { datePicker.maxDate = it }
show()
}
}
}
Usage:
In Activity:
editText.transformIntoDatePicker(this, "MM/dd/yyyy")
editText.transformIntoDatePicker(this, "MM/dd/yyyy", Date())
In Fragments:
editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy")
editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy", Date())
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
VBA subs are no macros. A VBA sub can be a macro, but it is not a must.
The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.
The more elegant way is, to design and write your own VBA code without using the macro features!
VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.
If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".
In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.
It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.
In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.
The Easiest way example to show you how to do that is :
Code :
>>> points = 19.5
>>> total = 22
>>>'Correct answers: {:.2%}'.format(points/total)
`
Output : Correct answers: 88.64%
I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)
Now, you can use standard string function find
to check the output string output
.
As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):
var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);
Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):
var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);
In version 4 of lodash this method has been renamed orderBy:
var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);
Just adding another idea you could use a child selector to get immediate children
document.querySelectorAll(".parent > .child1");
should return all the immediate children with class .child1
I had this error and all the configurations mentioned above were correct however I was still getting "The client and service bindings may be mismatched" error.
What resolved my error, was matching the messageEncoding attribute values in the following node of service and client config files. They were different in mine, service was Text and client Mtom. Changing service to Mtom to match client's, resolved the issue.
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMySevice" ... messageEncoding="Mtom">
...
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above
You can send it as raw xml
<test>or like this</test>
If you declare the paramater2 as XElement data type
boost::is_any_of
Strip for all characters from one string that appear in another given string:
#include <cassert>
#include <boost/range/algorithm/remove_if.hpp>
#include <boost/algorithm/string/classification.hpp>
int main() {
std::string str = "a_bc0_d";
str.erase(boost::remove_if(str, boost::is_any_of("_0")), str.end());
assert((str == "abcd"));
}
Tested in Ubuntu 16.04, Boost 1.58.
I find the answers not satisfactory so I'll add my two cents.
Let's analyze the following cases:
int& getInt()
{
int x = 4;
return x;
}
This is obviously error
int& x = getInt(); // will refer to garbage
int& getInt()
{
static int x = 4;
return x;
}
This is right, because static variables are existant throughout lifetime of a program.
int& x = getInt(); // valid reference, x = 4
This is also quite common when implementing Singleton pattern
Class Singleton
{
public:
static Singleton& instance()
{
static Singleton instance;
return instance;
};
void printHello()
{
printf("Hello");
};
}
Usage:
Singleton& my_sing = Singleton::instance(); // Valid Singleton instance
my_sing.printHello(); // "Hello"
Standard library containers depend heavily upon usage of operators which return reference, for example
T & operator*();
may be used in the following
std::vector<int> x = {1, 2, 3}; // create vector with 3 elements
std::vector<int>::iterator iter = x.begin(); // iterator points to first element (1)
*iter = 2; // modify first element, x = {2, 2, 3} now
There are times when & may be used for quick access to internal data
Class Container
{
private:
std::vector<int> m_data;
public:
std::vector<int>& data()
{
return m_data;
}
}
with usage:
Container cont;
cont.data().push_back(1); // appends element to std::vector<int>
cont.data()[0] // 1
HOWEVER, this may lead to pitfall such as this:
Container* cont = new Container;
std::vector<int>& cont_data = cont->data();
cont_data.push_back(1);
delete cont; // This is bad, because we still have a dangling reference to its internal data!
cont_data[0]; // dangling reference!
I had an issue with the downscaleImage()
function posted above by @daniel-allen-langdon in that the image.width
and image.height
properties are not available immediately because the image load is asynchronous.
Please see updated TypeScript example below that takes this into account, uses async
functions, and resizes the image based on the longest dimension rather than just the width
function getImage(dataUrl: string): Promise<HTMLImageElement>
{
return new Promise((resolve, reject) => {
const image = new Image();
image.src = dataUrl;
image.onload = () => {
resolve(image);
};
image.onerror = (el: any, err: ErrorEvent) => {
reject(err.error);
};
});
}
export async function downscaleImage(
dataUrl: string,
imageType: string, // e.g. 'image/jpeg'
resolution: number, // max width/height in pixels
quality: number // e.g. 0.9 = 90% quality
): Promise<string> {
// Create a temporary image so that we can compute the height of the image.
const image = await getImage(dataUrl);
const oldWidth = image.naturalWidth;
const oldHeight = image.naturalHeight;
console.log('dims', oldWidth, oldHeight);
const longestDimension = oldWidth > oldHeight ? 'width' : 'height';
const currentRes = longestDimension == 'width' ? oldWidth : oldHeight;
console.log('longest dim', longestDimension, currentRes);
if (currentRes > resolution) {
console.log('need to resize...');
// Calculate new dimensions
const newSize = longestDimension == 'width'
? Math.floor(oldHeight / oldWidth * resolution)
: Math.floor(oldWidth / oldHeight * resolution);
const newWidth = longestDimension == 'width' ? resolution : newSize;
const newHeight = longestDimension == 'height' ? resolution : newSize;
console.log('new width / height', newWidth, newHeight);
// Create a temporary canvas to draw the downscaled image on.
const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
// Draw the downscaled image on the canvas and return the new data URL.
const ctx = canvas.getContext('2d')!;
ctx.drawImage(image, 0, 0, newWidth, newHeight);
const newDataUrl = canvas.toDataURL(imageType, quality);
return newDataUrl;
}
else {
return dataUrl;
}
}
JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.
The example he gives declares and initializes the variable i
in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i
would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:
switch(choice) {
case 1:
int i = 10; // i is never used outside of this case
printf("i = %d\n", i);
break;
case 2:
int j = 20; // j is never used outside of this case
printf("j = %d\n", j);
break;
}
One could expect this program to compile, since both i
and j
are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:
, because this would skip the declaration with initialization of i
, and even though case 2
doesn't use i
at all, this is still forbidden in C++.
Interestingly, with some adjustments (an #ifdef
to #include
the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:
// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif
int main() {
int choice;
printf("Please enter 1 or 2: ");
scanf("%d", &choice);
switch(choice) {
case 1:
;
int i = 10; // i is never used outside of this case
printf("i = %d\n", i);
break;
case 2:
;
int j = 20; // j is never used outside of this case
printf("j = %d\n", j);
break;
}
}
Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.
According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.
However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.
Very simple, you close it :)
var myWebSocket = new WebSocket("ws://example.org");
myWebSocket.send("Hello Web Sockets!");
myWebSocket.close();
Did you check also the following site And check the introduction article of Opera
I was looking for the same thing for a quick operation and found this question. I needed both 32-bit and 64-bit versions.
This is an older version but the links are from the Microsoft servers, it should be safe. The link for 32-bit version is also in a previous answer but the version number i get on the install is different, maybe the same link is updated with a newer version since 2013.
Cheksums are generated both locally and on VirusTotal, they match.
Debugging Tools for Windows (x64) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_amd64/dbg_amd64.msi (SHA-256:2e491bb98850abf9b9d2627185b57e048ba9b2410d68303698ac68c2daad9e5d)
Debugging Tools for Windows (x86) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools/dbg_x86.msi (SHA-256:5a0f43281e51405408a043e2f94dd51782ef29671307d3538cfdff5b0e69d115)
I tested the 64 bit debugger with a 64 bit program that was compiled some years ago (~2012) and it works. Test is done on Windows 10 Pro 64 bit (v2004 Build 19041.207).
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
To have the exact same output as you need, you need to format the file like that :
a very long string..........\t 112232432\t anotherfield\n
a smaller string\t 123124343\t anotherfield\n
And then using :
$ column -t -s $'\t' FILE
a very long string.......... 112232432 anotherfield
a smaller string 123124343 anotherfield
Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it
CASE
WHEN [condition.1] THEN [expression.1]
WHEN [condition.2] THEN [expression.2]
...
WHEN [condition.n] THEN [expression.n]
ELSE [expression]
END
It sounds like the best way is for you to iterate over entries using map.entrySet()
since map.containsValue()
probably does this anyway.
So ... more digging, with the result. It seems that although I ran one process normal and one "As Administrator", I had UAC off. Turning UAC to medium allowed me to see different results. Basically, it all boils down to integrity levels, which are 5.
Browsers, for example, run at Low Level (1), while services (System user) run at System Level (4). Everything is very well explained in Windows Integrity Mechanism Design . When UAC is enabled, processes are created with Medium level (SID S-1-16-8192 AKA 0x2000 is added) while when "Run as Administrator", the process is created with High Level (SID S-1-16-12288 aka 0x3000).
So the correct ACCESS_TOKEN for a normal user (Medium Integrity level) is:
0:000:x86> !token
Thread is not impersonating. Using process token...
TS Session ID: 0x1
User: S-1-5-21-1542574918-171588570-488469355-1000
Groups:
00 S-1-5-21-1542574918-171588570-488469355-513
Attributes - Mandatory Default Enabled
01 S-1-1-0
Attributes - Mandatory Default Enabled
02 S-1-5-32-544
Attributes - DenyOnly
03 S-1-5-32-545
Attributes - Mandatory Default Enabled
04 S-1-5-4
Attributes - Mandatory Default Enabled
05 S-1-2-1
Attributes - Mandatory Default Enabled
06 S-1-5-11
Attributes - Mandatory Default Enabled
07 S-1-5-15
Attributes - Mandatory Default Enabled
08 S-1-5-5-0-1908477
Attributes - Mandatory Default Enabled LogonId
09 S-1-2-0
Attributes - Mandatory Default Enabled
10 S-1-5-64-10
Attributes - Mandatory Default Enabled
11 S-1-16-8192
Attributes - GroupIntegrity GroupIntegrityEnabled
Primary Group: LocadDumpSid failed to dump Sid at addr 000000000266b458, 0xC0000078; try own SID dump.
s-1-0x515000000
Privs:
00 0x000000013 SeShutdownPrivilege Attributes -
01 0x000000017 SeChangeNotifyPrivilege Attributes - Enabled Default
02 0x000000019 SeUndockPrivilege Attributes -
03 0x000000021 SeIncreaseWorkingSetPrivilege Attributes -
04 0x000000022 SeTimeZonePrivilege Attributes -
Auth ID: 0:1d1f65
Impersonation Level: Anonymous
TokenType: Primary
Is restricted token: no.
Now, the differences are as follows:
S-1-5-32-544
Attributes - Mandatory Default Enabled Owner
for "As Admin", while
S-1-5-32-544
Attributes - DenyOnly
for non-admin.
Note that S-1-5-32-544 is BUILTIN\Administrators. Also, there are fewer privileges, and the most important thing to notice:
admin:
S-1-16-12288
Attributes - GroupIntegrity GroupIntegrityEnabled
while for non-admin:
S-1-16-8192
Attributes - GroupIntegrity GroupIntegrityEnabled
I hope this helps.
Further reading: http://www.blackfishsoftware.com/blog/don/creating_processes_sessions_integrity_levels
From the Official documentation,
For example, to set the background color to orange:
<meta name="theme-color" content="#db5945">
In addition, Chrome will show beautiful high-res favicons when they’re provided. Chrome for Android picks the highest res icon that you provide, and we recommend providing a 192×192px PNG file. For example:
<link rel="icon" sizes="192x192" href="nice-highres.png">
Previous answers point out correctly that you can only do this with the standard JDK tools by converting the JKS file into PKCS #12 format first. If you're interested, I put together a compact utility to import OpenSSL-derived keys into a JKS-formatted keystore without having to convert the keystore to PKCS #12 first: http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art049
You would use the linked utility like this:
$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"
(sign the CSR, get back localhost.cer)
$ openssl rsa -in localhost.key -out localhost.rsa
Enter pass phrase for localhost.key:
writing RSA key
$ java -classpath . KeyImport -keyFile localhost.rsa -alias localhost -certificateFile localhost.cer -keystore localhost.jks -keystorePassword changeit -keystoreType JKS -keyPassword changeit
I would use it at every opportunity. See When do you use Java's @Override annotation and why?
Personally, I would shorten it a touch too if all you need is the columns:
For i = LBound(arr1) To UBound(arr1)
Sheets("SheetA").Columns(arr1(i)).Copy
Sheets("SheetB").Columns(arr2(i)).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Next
as from this code snippet, there isnt much point in lastrow
or firstrowDB
You may use the following extension method:
public static class CharExtensions
{
public static int CharToInt(this char c)
{
if (c < '0' || c > '9')
throw new ArgumentException("The character should be a number", "c");
return c - '0';
}
}
might be surprised to know.. its PHP. read all about it here
If message.value[] is string:
if message.value[0] in ('/', '\'):
do_stuff()
If it not str
http://docs.notepad-plus-plus.org/index.php/Inserting_Variable_Text
Notepad++ comes equipped with a Edit -> Column "Alt+C" Editor which can work on a rectangular selection in two different ways: Coledit.png inserting some fixed text on every line including and following the current line, at the column of the insertion point (aka caret). Initially selected text is left untouched. As the picture illustrates, a linear series of numbers can be inserted in the same manner. The starting value and increment are to be provided. Left padding with zeroes is an option, and the number may be entered in base 2, 8, 10 or 16 - this is how the computed values will be displayed too, padding being based on the largest.
Just change +
to -
:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
[^ ]
: match NOT from the set[^a-z0-9-]
: match if not a-z
, 0-9
or -
/ /g
: do global matchMore information:
I have found that you have to comment out the namespace wrapping the the class at time when moving between version of Visual Studio:
'Namespace FormsAuth
'End Namespace
and at other times, I have to uncomment the namespace.
This happened to me several times when other developers edited the same solution using a different version of VS and/or I moved (copied) the solution to another location
In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:
make sure your API is sending the Content-Type
header to tell the client to expect a JSON response:
header('Content-Type: application/json');
echo json_encode($response);
Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.
If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController
with an add()
action/method.
There are a few starting point projects for RESTful APIs on GitHub that are worth a look.
Just to addon if someone is dealing with
, this would work if dealing with
.
Replace it with str_replace()
first and check it with empty()
empty(str_replace(" " ,"" , $YOUR_DATA)) ? $YOUR_DATA = '--' : $YOUR_DATA;
It will redirects to index.html on localhost:8080 call.
app.get('/',function(req,res){
res.sendFile('index.html', { root: __dirname });
});
I describe here a problem that I faced when run npm install
- the package does not appear in node_modules
.
The issue was that the name
value in package.json
of installed package was different than the name of imported package (key in package.json
of my project).
So if your installed project name is some-package
(name value in its package.json
) then
in package.json
of your project write: "some-package": "owner/some-repo#tag"
.
${word:$(expr index "$word" "="):1}
that gets the 7
. Assuming you mean the entire rest of the string, just leave off the :1
.
In the project level build.gradle file, I have replaced this line
classpath 'com.android.tools.build:gradle:3.6.3'
with this one
classpath 'com.google.gms:google-services:4.3.3'
After adding both of those lines, and syncing, everything became fine. Hope this will help someone.
function getMethods(obj)
{
var res = [];
for(var m in obj) {
if(typeof obj[m] == "function") {
res.push(m)
}
}
return res;
}
This is an excellent example for understanding event bubbling concept. Based on the above answers, the final code will look like as mentioned below. Where the user Clicks on checkbox the event propagation to its parent element 'header' will be stopped using event.stopPropagation();
.
$(document).ready(function() {
$('#container').addClass('hidden');
$('#header').click(function() {
if($('#container').hasClass('hidden')) {
$('#container').removeClass('hidden');
} else {
$('#container').addClass('hidden');
}
});
$('#header input[type=checkbox]').click(function(event) {
if (event.stopPropagation) { // standard
event.stopPropagation();
} else { // IE6-8
event.cancelBubble = true;
}
});
});
My Bots are running well against ReCaptcha.
Here my Solution.
Let your Bot do this Steps:
First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.
Also use for better results a VPN like https://www.purevpn.com
For every Recpatcha do these Steps:
If you use VPN switch IP first
Clear all Browser Cookies
Clear all Browser Cache
Set one of these Useragents by Random:
a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0
5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange
Then Click ever with random delay between
WM_LBUTTONDOWN
and
WM_LBUTTONUP
Take Screenshot from Image Captcha
Send Screenshot to
or
and let they solve.
After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images
Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button
In 75% all trys Recaptcha will solved
Chears Google
Tom
I dislike "Don't" answers, but... don't.
make
's variables are global and are supposed to be evaluated during makefile's "parsing" stage, not during execution stage.
In this case, as long as the variable local to a single target, follow @nobar's answer and make it a shell variable.
Target-specific variables, too, are considered harmful by other make implementations: kati, Mozilla pymake. Because of them, a target can be built differently depending on if it's built standalone, or as a dependency of a parent target with a target-specific variable. And you won't know which way it was, because you don't know what is already built.
If you need to search for all element's positions between certain indices, you can state them:
[i for i,x in enumerate([1,2,3,2]) if x==2 & 2<= i <=3] # -> [3]
There are many answers here but no answer helps to manipulate the css of :before
or :after
, not even the accepted one.
Here is how I propose to do it. Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content
attribute in element itself so that you can take it out easily later.
Now there is a button
clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS
:
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before
, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
Ultimately if you want to dynamically change :before
content by jQuery, You can achieve that as follows:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>#something:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
Clicking on above "changeBefore" button will change :before
content of #something
into '22' which is a dynamic value.
I hope it helps
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
To use Enum with any type of value, try this:
Updated with some improvements... Thanks @Jeff, by your tip!
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 'GREEN'
BLUE = ('blue', '#0000ff')
@staticmethod
def list():
return list(map(lambda c: c.value, Color))
print(Color.list())
As result:
[1, 'GREEN', ('blue', '#0000ff')]
So based on what you said, these files are libraries/documentation you don't want to delete but also don't want to push to github
. Let say you have your project in folder your_project
and a doc directory: your_project/doc
.
git rm --cached doc/*
.gitignore
, you can make one right inside of your project folder: project/.gitignore
. doc/*
in the .gitignore git add project/.gitignore
git commit -m "message"
. github
.you need to put font-awesome file in css folder and change
href="../css/font-awesome.css" to href="css/font-awesome.css"
One more thing You can Replace this Font-awesome css File And and try this one
.social-media{
list-style-type: none;
padding: 0px;
margin: 0px;
}
.social-media li .fa{
background: #fff;
color: #262626;
width: 50px;
height: 50px;
border-radius: 50%;
text-align:center;
line-height:50px;
}
.social-media .fa:hover {
box-shadow: 5px 5px 5px #000;
}
.social-media .fa.fa-twitter:hover{
background:#55acee;
color:#fff;
}
.social-media .fa.fa-facebook:hover{
background:#3b5998;
color:#fff;
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<ul class="social-media">
<li><i class="fa fa-twitter fa-2x"></i></li>
<li><i class="fa fa-facebook fa-2x"></i></li>
</ul>
_x000D_
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
The condition below:
//Element[@attribute1="abc" and @attribute2="xyz" and Data]
checks for the existence of the element Data within Element and not for element value Data.
Instead you can use
//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
$destroy
can refer to 2 things: method and event
.directive("colorTag", function(){
return {
restrict: "A",
scope: {
value: "=colorTag"
},
link: function (scope, element, attrs) {
var colors = new App.Colors();
element.css("background-color", stringToColor(scope.value));
element.css("color", contrastColor(scope.value));
// Destroy scope, because it's no longer needed.
scope.$destroy();
}
};
})
See @SunnyShah's answer.
Also for anyone using properties such as Props or Refs without your "DocgetId's" then you can:
("" as HTMLInputElement).value;
Where the inverted quotes is your props value so an example would be like so:
var val = (this.refs.newText as HTMLInputElement).value;
alert("Saving this:" + val);
to make UITableView sections header not sticky or sticky:
change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)
if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
following Anton's solution, come up with this ViewHolder
which holds/handles/delegates different type of layouts.
But not sure if the replacing new layout would work when the recycling view's ViewHolder
is not type of the data roll in.
So basically,
onCreateViewHolder(ViewGroup parent, int viewType)
is only called when new view layout is needed;
getItemViewType(int position)
will be called for the viewType
;
onBindViewHolder(ViewHolder holder, int position)
is always called when recycling the view (new data is brought in and try to display with that ViewHolder
).
So when onBindViewHolder
is called it needs to put in the right view layout and update the ViewHolder
.
Is the way correct to replacing the view layout for that ViewHolder
to be brought in, or any problem?
Appreciate any comment!
public int getItemViewType(int position) {
TypedData data = mDataSource.get(position);
return data.type;
}
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
return ViewHolder.makeViewHolder(parent, viewType);
}
public void onBindViewHolder(ViewHolder holder,
int position) {
TypedData data = mDataSource.get(position);
holder.updateData(data);
}
///
public static class ViewHolder extends
RecyclerView.ViewHolder {
ViewGroup mParentViewGroup;
View mCurrentViewThisViewHolderIsFor;
int mDataType;
public TypeOneViewHolder mTypeOneViewHolder;
public TypeTwoViewHolder mTypeTwoViewHolder;
static ViewHolder makeViewHolder(ViewGroup vwGrp,
int dataType) {
View v = getLayoutView(vwGrp, dataType);
return new ViewHolder(vwGrp, v, viewType);
}
static View getLayoutView(ViewGroup vwGrp,
int dataType) {
int layoutId = getLayoutId(dataType);
return LayoutInflater.from(vwGrp.getContext())
.inflate(layoutId, null);
}
static int getLayoutId(int dataType) {
if (dataType == TYPE_ONE) {
return R.layout.type_one_layout;
} else if (dataType == TYPE_TWO) {
return R.layout.type_two_layout;
}
}
public ViewHolder(ViewGroup vwGrp, View v,
int dataType) {
super(v);
mDataType = dataType;
mParentViewGroup = vwGrp;
mCurrentViewThisViewHolderIsFor = v;
if (data.type == TYPE_ONE) {
mTypeOneViewHolder = new TypeOneViewHolder(v);
} else if (data.type == TYPE_TWO) {
mTypeTwoViewHolder = new TypeTwoViewHolder(v);
}
}
public void updateData(TypeData data) {
mDataType = data.type;
if (data.type == TYPE_ONE) {
mTypeTwoViewHolder = null;
if (mTypeOneViewHolder == null) {
View newView = getLayoutView(mParentViewGroup,
data.type);
/**
* how to replace new view with
the view in the parent
view container ???
*/
replaceView(mCurrentViewThisViewHolderIsFor,
newView);
mCurrentViewThisViewHolderIsFor = newView;
mTypeOneViewHolder =
new TypeOneViewHolder(newView);
}
mTypeOneViewHolder.updateDataTypeOne(data);
} else if (data.type == TYPE_TWO){
mTypeOneViewHolder = null;
if (mTypeTwoViewHolder == null) {
View newView = getLayoutView(mParentViewGroup,
data.type);
/**
* how to replace new view with
the view in the parent view
container ???
*/
replaceView(mCurrentViewThisViewHolderIsFor,
newView);
mCurrentViewThisViewHolderIsFor = newView;
mTypeTwoViewHolder =
new TypeTwoViewHolder(newView);
}
mTypeTwoViewHolder.updateDataTypeOne(data);
}
}
}
public static void replaceView(View currentView,
View newView) {
ViewGroup parent = (ViewGroup)currentView.getParent();
if(parent == null) {
return;
}
final int index = parent.indexOfChild(currentView);
parent.removeView(currentView);
parent.addView(newView, index);
}
Edit: ViewHolder has member mItemViewType to hold the view
Edit: looks like in onBindViewHolder(ViewHolder holder, int position) the ViewHolder passed in has been picked up (or created) by looked at getItemViewType(int position) to make sure it is a match, so may not need to worry there that ViewHolder's type does not match the data[position]'s type. Does anyone knows more how the ViewHolder in the onBindViewHolder() is picked up?
Edit: Looks like The recycle ViewHolder
is picked by type, so no warrior there.
Edit: http://wiresareobsolete.com/2014/09/building-a-recyclerview-layoutmanager-part-1/ answers this question.
It gets the recycle ViewHolder
like:
holder = getRecycledViewPool().getRecycledView(mAdapter.getItemViewType(offsetPosition));
or create new one if not find recycle ViewHolder
of right type.
public ViewHolder getRecycledView(int viewType) {
final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
if (scrapHeap != null && !scrapHeap.isEmpty()) {
final int index = scrapHeap.size() - 1;
final ViewHolder scrap = scrapHeap.get(index);
scrapHeap.remove(index);
return scrap;
}
return null;
}
View getViewForPosition(int position, boolean dryRun) {
......
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
}
final int type = mAdapter.getItemViewType(offsetPosition);
// 2) Find from scrap via stable ids, if exists
if (mAdapter.hasStableIds()) {
holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun);
if (holder != null) {
// update position
holder.mPosition = offsetPosition;
fromScrap = true;
}
}
if (holder == null && mViewCacheExtension != null) {
// We are NOT sending the offsetPosition because LayoutManager does not
// know it.
final View view = mViewCacheExtension
.getViewForPositionAndType(this, position, type);
if (view != null) {
holder = getChildViewHolder(view);
if (holder == null) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view which does not have a ViewHolder");
} else if (holder.shouldIgnore()) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view that is ignored. You must call stopIgnoring before"
+ " returning this view.");
}
}
}
if (holder == null) { // fallback to recycler
// try recycler.
// Head to the shared pool.
if (DEBUG) {
Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared "
+ "pool");
}
holder = getRecycledViewPool()
.getRecycledView(mAdapter.getItemViewType(offsetPosition));
if (holder != null) {
holder.resetInternal();
if (FORCE_INVALIDATE_DISPLAY_LIST) {
invalidateDisplayListInt(holder);
}
}
}
if (holder == null) {
holder = mAdapter.createViewHolder(RecyclerView.this,
mAdapter.getItemViewType(offsetPosition));
if (DEBUG) {
Log.d(TAG, "getViewForPosition created new ViewHolder");
}
}
}
boolean bound = false;
if (mState.isPreLayout() && holder.isBound()) {
// do not update unless we absolutely have to.
holder.mPreLayoutPosition = position;
} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
if (DEBUG && holder.isRemoved()) {
throw new IllegalStateException("Removed holder should be bound and it should"
+ " come here only in pre-layout. Holder: " + holder);
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
mAdapter.bindViewHolder(holder, offsetPosition);
attachAccessibilityDelegate(holder.itemView);
bound = true;
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = fromScrap && bound;
return holder.itemView;
}
In case if you are using node js, then this could be the possible solution
const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;
I had a similar problem where CREATE FULLTEXT
timed out after 30 seconds:
Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:
Also, I did not have to restart mysql workbench for this to work.
try like below it will work...
<html>
<head>
<script>
function displayResult(element)
{
document.getElementById(element).value = 'hi';
}
</script>
</head>
<body>
<textarea id="myTextarea" cols="20">
BYE
</textarea>
<br>
<button type="button" onclick="displayResult('myTextarea')">Change</button>
</body>
</html>
Your formula is wrong. You probably meant something like:
=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Another equivalent:
=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Or even shorter:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))
OR EVEN SHORTER:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))
One way
SELECT t1.*
FROM db.table t1
WHERE exists
(SELECT *
FROM db.table t2
where t1.pk != t2.pk
and t1.someField = t2.someField)
Install pip
Download get-pip. Remember to save it as "get-pip.py"
Now go to the download folder. Right click on get-pip.py then open with python.exe.
You can add system variable by
(by doing this you can use pip and easy_install without specifying path)
1 Clicking on Properties of My Computer
2 Then chose Advanced System Settings
3 Click on Advanced Tab
4 Click on Environment Variables
5 From System Variables >>> select variable path.
6 Click edit then add the following lines at the end of it
;c:\Python27;c:\Python27\Scripts
(please dont copy this, just go to your python directory and copy the paths similar to this)
NB:- you have to do this once only.
Install beautifulsoup4
Open cmd and type
pip install beautifulsoup4
I only needed to add the feature in windows features as Charlie mentioned.For people who cannot find it on window 10 or server 2012+ find it as below. I struggled a bit
You could call an mWebView.reload();
That's what it does
You can either:
pre { white-space: normal; }
to maintain the monospace font but add word-wrap, or:
pre { overflow: auto; }
which will allow a fixed size with horizontal scrolling for long lines.
Use DefinePlugin.
The DefinePlugin allows you to create global constants which can be configured at compile time.
new webpack.DefinePlugin(definitions)
plugins: [
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true)
})
//...
]
console.log(`Environment is in production: ${PRODUCTION}`);
You can send any signal to any process using the kill(2)
interface:
kill -SIGABRT 30823
30823 was a dash
process I started, so I could easily find the process I wanted to kill.
$ /bin/dash
$ Aborted
The Aborted
output is apparently how dash
reports a SIGABRT.
It can be sent directly to any process using kill(2)
, or a process can send the signal to itself via assert(3)
, abort(3)
, or raise(3)
.
The ZingChart library has an AngularJS directive that was built in-house. Features include:
Support from the development team
...
$scope.myJson = {
type : 'line',
series : [
{ values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
]
};
...
<zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
There is a full demo with code examples available.
As a Javascript beginner, I found Rapahel samples not so easy, I recommend http://cancerbero.mbarreneche.com/raphaeltut, which is a real Step by step tutorial.
Try this. It will work. jquery unload method is depreceted.
window.onbeforeunload = function(event) {
event.returnValue = "Write something clever here..";
};
Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
Embed code example:
<object type="application/pdf" data="example.pdf" width="100%" height="100%" id="examplePDF" name="examplePDF"><param name='src' value='example.pdf'/></object>
<script>
examplePDF.printWithDialog();
</script>
May have to fool around with the ids/names. Using adobe reader...
Instead of dropping the backup table, just rename it...
BEGIN TRANSACTION;
CREATE TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;
COMMIT;
To get a new line inside text-area, put an actual line-break there:
<textarea cols='60' rows='8'>This is my statement one._x000D_
This is my statement2</textarea>
_x000D_
ul {
margin:0;
list-style-type: none;
}
li:before { content: "- ";}
Sometimes the file is kept in tracking history, try the following steps:
git commit
, If you are seeing create mode with the big file listed, then do:git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch filename' HEAD
.
You should see a bunch of Rewrites shown in your console which ends with:
rm 'filename' and
the last line Ref was rewritten.
It's done.
You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as https://xxx.xxx.xx.xx/~mohidul
Try this.
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var json = config.Formatters.JsonFormatter;
json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }
);
}
}
Please refer to the following link which explains why lock (this) is not a good idea.
https://docs.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices
So the solution is to add a private object, for example, lockObject to the class and place the code region inside the lock statement as shown below:
lock (lockObject)
{
...
}
The below code works perfectly in my case - my page contains complex java scripts
public void checkPageIsReady() {
JavascriptExecutor js = (JavascriptExecutor)driver;
//Initially bellow given if condition will check ready state of page.
if (js.executeScript("return document.readyState").toString().equals("complete")){
System.out.println("Page Is loaded.");
return;
}
//This loop will rotate for 25 times to check If page Is ready after every 1 second.
//You can replace your value with 25 If you wants to Increase or decrease wait time.
for (int i=0; i<25; i++){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {}
//To check page ready state.
if (js.executeScript("return document.readyState").toString().equals("complete")){
break;
}
}
}
Source - How To Wait For Page To Load/Ready In Selenium WebDriver
We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.
// const objectScan = require('object-scan');
const tool = (() => {
const scanner = objectScan(['[*]'], {
abort: true,
rtn: 'bool',
filterFn: ({
value, parent, property, context
}) => {
if (value.id === context.id) {
context.fn({ value, parent, property });
return true;
}
return false;
}
});
return {
add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
mod: (data, id, prop, v = undefined) => scanner(data, {
id,
fn: ({ value }) => {
if (value !== undefined) {
value[prop] = v;
} else {
delete value[prop];
}
}
})
};
})();
// -------------------------------
const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };
const exec = (fn) => {
console.log('---------------');
console.log(fn.toString());
console.log(fn());
console.log(data);
};
exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));
// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
To String
import strings
stringFiles := strings.Join(fileSlice[:], ",")
Back to Slice again
import strings
fileSlice := strings.Split(stringFiles, ",")
The easiest and the correct way to do it - use Spacer()
Example:
Column(
children: [
SomeWidgetOnTheTop(),
Spacer(),
SomeCenterredBottomWidget(),
],
);
if self.automaticallyAdjustsScrollViewInsets = NO;
doesn't work for you, make sure the height of either tableview header or section header is CGFLOAT_MIN
not 0
.
For example if you want to make tableview header 0 high, you can do:
CGRect frame = self.tableViewHeader.frame;
frame.size.height = CGFLOAT_MIN; //not 0
self.tableView.tableHeaderView.frame = frame;
self.tableView.tableHeaderView = self.tableViewHeader;
Hope it helps.
I found this an easy way of cleaning in a shape between the desired row and column. I am not sure if this is what you are looking for. Hope it helps.
Sub sbClearCellsOnlyData()
Range("A1:C10").ClearContents
End Sub
I use the following method in my project
-(NSArray*)networkErrorCodes
{
static NSArray *codesArray;
if (![codesArray count]){
@synchronized(self){
const int codes[] = {
//kCFURLErrorUnknown, //-998
//kCFURLErrorCancelled, //-999
//kCFURLErrorBadURL, //-1000
//kCFURLErrorTimedOut, //-1001
//kCFURLErrorUnsupportedURL, //-1002
//kCFURLErrorCannotFindHost, //-1003
kCFURLErrorCannotConnectToHost, //-1004
kCFURLErrorNetworkConnectionLost, //-1005
kCFURLErrorDNSLookupFailed, //-1006
//kCFURLErrorHTTPTooManyRedirects, //-1007
kCFURLErrorResourceUnavailable, //-1008
kCFURLErrorNotConnectedToInternet, //-1009
//kCFURLErrorRedirectToNonExistentLocation, //-1010
kCFURLErrorBadServerResponse, //-1011
//kCFURLErrorUserCancelledAuthentication, //-1012
//kCFURLErrorUserAuthenticationRequired, //-1013
//kCFURLErrorZeroByteResource, //-1014
//kCFURLErrorCannotDecodeRawData, //-1015
//kCFURLErrorCannotDecodeContentData, //-1016
//kCFURLErrorCannotParseResponse, //-1017
kCFURLErrorInternationalRoamingOff, //-1018
kCFURLErrorCallIsActive, //-1019
//kCFURLErrorDataNotAllowed, //-1020
//kCFURLErrorRequestBodyStreamExhausted, //-1021
kCFURLErrorFileDoesNotExist, //-1100
//kCFURLErrorFileIsDirectory, //-1101
kCFURLErrorNoPermissionsToReadFile, //-1102
//kCFURLErrorDataLengthExceedsMaximum, //-1103
};
int size = sizeof(codes)/sizeof(int);
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i=0;i<size;++i){
[array addObject:[NSNumber numberWithInt:codes[i]]];
}
codesArray = [array copy];
}
}
return codesArray;
}
Then I just check the error code and show alert if it is in the list
if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){
// Fire Alert View Here
}
But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.
In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.
Regards to martinezdelariva for a link to documentation.
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
One could achieve something similar in react native with position: absolute
let footerStyle = {
position: 'absolute',
bottom: 0,
}
There are a few things to keep in mind though.
absolute
positions the element relative to its parent.A practical style definition would look something like this:
import { Dimensions } from 'react-native';
var screenWidth = Dimensions.get('window').width; //full screen width
let footerStyle = {
position: 'absolute',
bottom: 0,
width: screenWidth,
height: 60
}
For a Windows machine start the mongod
process by specifying the dbpath:
mongod --dbpath \mongodb\data
Reference: Manage mongod
Processes
It's something you can put "(args)" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated.
Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt
) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:
critical.t <- function(){
cat("\n","\bEnter Alpha Level","\n")
alpha<-scan(n=1,what = double(0),quiet=T)
cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
tt <- scan(n=1,what = double(0),quiet=T)
cat("\n","\bEnter Number of Observations","\n")
n <- scan(n=1,what = double(0),quiet=T)
cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}
critical.t()
I have been implementing installation without user consent recently - it was a kiosk application for API level 21+ where I had full control over environment.
The basic requirements are
The following method reads and installs APK from InputStream:
public static boolean installPackage(Context context, InputStream in, String packageName)
throws IOException {
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setAppPackageName(packageName);
// set params
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
OutputStream out = session.openWrite("COSU", 0, -1);
byte[] buffer = new byte[65536];
int c;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
session.fsync(out);
in.close();
out.close();
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("info", "somedata"); // for extra data if needed..
Random generator = new Random();
PendingIntent i = PendingIntent.getActivity(context, generator.nextInt(), intent,PendingIntent.FLAG_UPDATE_CURRENT);
session.commit(i.getIntentSender());
return true;
}
The following code calls the installation
try {
InputStream is = getResources().openRawResource(R.raw.someapk_source);
installPackage(MainActivity.this, is, "com.example.apk");
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
for the whole thing to work you desperately need INSTALL_PACKAGES
permission, or the code above will fail silently
<uses-permission
android:name="android.permission.INSTALL_PACKAGES" />
to get this permission you must install your APK as System application which REQUIRES root (however AFTER you have installed your updater application it seem to work WITHOUT root)
To install as system application I created a signed APK and pushed it with
adb push updater.apk /sdcard/updater.apk
and then moved it to system/priv-app
- which requires remounting FS (this is why the root is required)
adb shell
su
mount -o rw,remount /system
mv /sdcard/updater.apk /system/priv-app
chmod 644 /system/priv-app/updater.apk
for some reason it didn't work with simple debug version, but logcat shows useful info if your application in priv-app
is not picked up for some reason.
Take a look at the fields's proprieties (type, length, default value, etc.), they should be the same.
I had this problem with SQL Server 2008 R2 because the fields's length are not equal.
A very common usecase of calc is take 100% width and adding some margin around the element.
One can do so with:
@someMarginVariable = 15px;
margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);
The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:
http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/
Go to PHPMyAdmin in your browser
Settings > Features > Change the value of Login cookie validity > Save
NOTE: You will have to do this per session.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
With the introduction of lambda expression in Java 8 you can now have anonymous methods.
Say I have a class Alpha
and I want to filter Alpha
s on a specific condition. To do this you can use a Predicate<Alpha>
. This is a functional interface which has a method test
that accepts an Alpha
and returns a boolean
.
Assuming that the filter method has this signature:
List<Alpha> filter(Predicate<Alpha> filterPredicate)
With the old anonymous class solution you would need to something like:
filter(new Predicate<Alpha>() {
boolean test(Alpha alpha) {
return alpha.centauri > 1;
}
});
With the Java 8 lambdas you can do:
filter(alpha -> alpha.centauri > 1);
For more detailed information see the Lambda Expressions tutorial
As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread
, as now the sleep functions are public:
Static Public Members
QThread * currentThread()
Qt::HANDLE currentThreadId()
int idealThreadCount()
void msleep(unsigned long msecs)
void sleep(unsigned long secs)
void usleep(unsigned long usecs)
void yieldCurrentThread()
cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members
Do this:
>>> d = [ [ None for y in range( 2 ) ] for x in range( 2 ) ]
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [None, None]]
The other solutions will lead to this kind of problem:
>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [1, None]]
I had the same issue and I resolved by changing the following in web.config.
It happened to me because I am running the application using Newtonsoft.Json 4.0
From:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
To:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="4.5.0.0" />
</dependentAssembly>
With Firefox and Chrome you can use :
<a href="whatever" target="_parent" onclick="myfunction()">
If myfunction is present both in iframe and in parent, the parent one will be called.
Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.
Array can be initialized as :
let emptyArray = [String]()
It shows that its an array of type string
The type of the emptyArray variable is inferred to be [String] from the type of the initializer.
For Creating the array of type string with elements
var groceryList: [String] = ["Eggs", "Milk"]
groceryList has been initialized with two items
The groceryList variable is declared as “an array of string values”, written as [String]. This particular array has specified a value type of String, it is allowed to store String values only.
There are various properities of array like :
- To check if array has elements (If array is empty or not)
isEmpty property( Boolean ) for checking whether the count property is equal to 0:
if groceryList.isEmpty {
print("The groceryList list is empty.")
} else {
print("The groceryList is not empty.")
}
- Appending(adding) elements in array
You can add a new item to the end of an array by calling the array’s append(_:) method:
groceryList.append("Flour")
groceryList now contains 3 items.
Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):
groceryList += ["Baking Powder"]
groceryList now contains 4 items
groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
groceryList now contains 7 items
There is a free python tool called YouTube transcript API
You can use it in scripts or as a command line tool:
pip install youtube_transcript_api
Word Break will mimic some of the intent
input[type=text] {
word-wrap: break-word;
word-break: break-all;
height: 80px;
}
_x000D_
<input type="text" value="The quick brown fox jumped over the lazy dog" />
_x000D_
As a workaround, this solution lost its effectiveness on some browsers. Please check the demo: http://cssdesk.com/dbCSQ
I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.
*Answering your question, system variable has higher priority *
@Component
@Profile("dev")
public class DatasourceConfigForDev
Now, the profile is dev
Note : if the Profile is given as
@Profile("!dev")
then the profile will exclude dev and be for all others.
<beans profile="dev">
<bean id="DatasourceConfigForDev" class="org.skoolguy.profiles.DatasourceConfigForDev"/>
</beans>
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("spring.profiles.active", "dev");
}
}
@Autowired
private ConfigurableEnvironment env;
// ...
env.setActiveProfiles("dev");
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
The profile names passed as the parameter will be activated during application start-up:
-Dspring.profiles.active=dev
In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:
to set via command line : export spring_profiles_active=dev
Any bean that does not specify a profile belongs to “default” profile.
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
Watch this YouTube video:
How about creating a timer with the next date?
In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.
The difference between MyString[0]
and MyString.ToCharArray()[0]
is that the former treats the string as a read-only array, while ToCharArray()
creates a new array. The former will be quicker (along with easier) for almost anything where it will work, but ToCharArray
can be necessary if you have a method that needs to accept an array, or if you want to change the array.
If the string isn't known to be non-null and non-empty you could do:
string.IsNullOrEmpty(MyString) ? (char?)null : MyString[0]
which returns a char?
of either null or the first character in the string, as appropriate.
This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.
http://www.microsoft.com/en-ca/download/details.aspx?id=13255
QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler); // switch to popup window
// Now you are in the popup window, perform necessary actions here
driver.switchTo().window(parentWindowHandler); // switch back to parent window
There is a plugin for Jquery called "Hotkeys" which allows you to bind to key down combinations.
Does this do what you are after?
I am on an angular project that (unfortunately) uses source code inclusion via tsconfig.json
to connect different collections of code. I came across a similar StaticInjector
error for a service (e.g.RestService
in the top example) and I was able to fix it by listing the service dependencies in the deps
array when providing the affected service in the module, for example:
import { HttpClient } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RestService } from 'mylib/src/rest/rest.service';
...
@NgModule({
imports: [
...
HttpModule,
...
],
providers: [
{
provide: RestService,
useClass: RestService,
deps: [HttpClient] /* the injected services in the constructor for RestService */
},
]
...
The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify()
method to compare the passwords.
if(password_verify($upass, $userRow['user_pass'])){
//code for redirecting to login screen }
where, $upass
is password entered by user and $userRow['user_pass']
is user_pass field in database which is encrypted by password_hash()
function.
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
Most answers use some kind of duck typing, checking for example that the object has a nodeType
property. But that's not enough, because non-nodes can also have node-like properties.
The other common approach is instanceof
, which can produce false positives e.g. with Object.create(Node)
, which is not a node despite inheriting node properties.
Moreover, both approaches above call internal essential methods, which can be problematic e.g. if the tested value is a proxy.
Instead, what I recommend is borrowing a node method and calling it on our object. The browser will check that the value is a node probably by looking at internal slots not customizable in proxies, so even they won't be able to interfere with our check.
function isNode(value) {
try {
Node.prototype.cloneNode.call(value, false);
return true;
} catch(err) {
return false;
}
}
You can also use property getters, if you prefer.
function isNode(value) {_x000D_
try {_x000D_
Object.getOwnPropertyDescriptor(Node.prototype,'nodeType').get.call(value);_x000D_
return true;_x000D_
} catch(err) {_x000D_
return false;_x000D_
}_x000D_
}
_x000D_
Similarly, if you want to test if a value is an element, you can use
function isElement(value) {
try {
Element.prototype.getAttribute.call(value, '');
return true;
} catch(err) {
return false;
}
}
function isHTMLElement(value) {
try {
HTMLElement.prototype.click.call(value);
return true;
} catch(err) {
return false;
}
}
Try to add auth method explicitly as below, because sometimes it is required:
session.setConfig("PreferredAuthentications", "password");
This is done with
ANALYZE TABLE table_name;
Read more about it here.
ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB. This statement works with MyISAM, BDB, InnoDB, and NDB tables.
AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.
In a scoped service, with every HTTP request, we get a new instance. However, within the same HTTP request, if the service is required in multiple places, like in the view and in the controller, then the same instance is provided for the entire scope of that HTTP request. But every new HTTP request will get a new instance of the service.
With a transient service, a new instance is provided every time a service instance is requested whether it is in the scope of the same HTTP request or across different HTTP requests.
Caller-saved registers (AKA volatile registers, or call-clobbered) are used to hold temporary quantities that need not be preserved across calls.
For that reason, it is the caller's responsibility to push these registers onto the stack or copy them somewhere else if it wants to restore this value after a procedure call.
It's normal to let a call
destroy temporary values in these registers, though.
Callee-saved registers (AKA non-volatile registers, or call-preserved) are used to hold long-lived values that should be preserved across calls.
When the caller makes a procedure call, it can expect that those registers will hold the same value after the callee returns, making it the responsibility of the callee to save them and restore them before returning to the caller. Or to not touch them.
The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null
and IsLoaded
is true
.
Basically the answer from Jani Hartikainen is right! I upvoted his answer. What was missing on my system (based on Ubuntu 15.04) was to enable PDO Extension in my php.ini
extension=pdo.so
extension=pdo_mysql.so
restart the webserver (e.g. with "sudo service apache2 restart") -> every fine :-)
To find where your current active php.ini file is located you can use phpinfo() or some other hints from here: https://www.ostraining.com/blog/coding/phpini-file/
function foo() {_x000D_
function bar() {_x000D_
console.trace("Tracing is Done here");_x000D_
}_x000D_
bar();_x000D_
}_x000D_
_x000D_
foo();
_x000D_
console.log(console); //to print console object_x000D_
console.clear('console.clear'); //to clear console_x000D_
console.log('console.log'); //to print log message_x000D_
console.info('console.info'); //to print log message _x000D_
console.debug('console.debug'); //to debug message_x000D_
console.warn('console.warn'); //to print Warning_x000D_
console.error('console.error'); //to print Error_x000D_
console.table(["car", "fruits", "color"]);//to print data in table structure_x000D_
console.assert('console.assert'); //to print Error_x000D_
console.dir({"name":"test"});//to print object_x000D_
console.dirxml({"name":"test"});//to print object as xml formate
_x000D_
To Print Error:- console.error('x=%d', x);
console.log("This is the outer level");_x000D_
console.group();_x000D_
console.log("Level 2");_x000D_
console.group();_x000D_
console.log("Level 3");_x000D_
console.warn("More of level 3");_x000D_
console.groupEnd();_x000D_
console.log("Back to level 2");_x000D_
console.groupEnd();_x000D_
console.log("Back to the outer level");
_x000D_
in my case I was able to find a fix and by looking at the everyone else's code it may be the same issue.. I simply just had to add 'django.contrib.sites' to the list of installed apps in the settings.py file.
hope this helps someone. this is my first contribution to the coding community
This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180
and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.
the pom.xml for the project I have doesn't have this "http://repo1.maven.org/myurlhere" anywhere in it
All projects have http://repo1.maven.org/ declared as <repository>
(and <pluginRepository>
) by default. This repository, which is called the central repository, is inherited like others default settings from the "Super POM" (all projects inherit from the Super POM). So a POM is actually a combination of the Super POM, any parent POMs and the current POM. This combination is called the "effective POM" and can be printed using the effective-pom
goal of the Maven Help plugin (useful for debugging).
And indeed, if you run:
mvn help:effective-pom
You'll see at least the following:
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories>
it has the absolute url where the maven repo is for the project but maven is still trying to download from the general maven repo
Maven will try to find dependencies in all repositories declared, including in the central one which is there by default as we saw. But, according to the trace you are showing, you only have one repository defined (the central repository) or maven would print something like this:
Reason: Unable to download the artifact from any repository
url.project:project:pom:x.x
from the specified remote repositories:
central (http://repo1.maven.org/),
another-repository (http://another/repository)
So, basically, maven is unable to find the url.project:project:pom:x.x
because it is not available in central.
But without knowing which project you've checked out (it has maybe specific instructions) or which dependency is missing (it can maybe be found in another repository), it's impossible to help you further.
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
I searched for git PHP implementations too, but with no results. The only way to re-create a site similar to GitHub is to setup a "real" git server on your own server and then use a PHP git web client like http://www.xiphux.com/programming/gitphp/.
Unfortunatly, you can forget to do this with a hosting solution. You need a real virtual server where you can install everything you want.
However, if you need a place where store some personal, non-public, non-accessible-to-everyone code for a project, you can try BitBucket. It offers private and private-shared git repos for free.
Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.
Its party trick is a CSS selector syntax to find elements, e.g.:
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.select("a");
Element head = doc.select("head").first();
See the Selector javadoc for more info.
This is a new project, so any ideas for improvement are very welcome!
SELECT Id 'PatientId',
ISNULL(CONVERT(varchar(50),ParentId),'') 'ParentId'
FROM Patients
ISNULL
always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar
), you'd best make sure that's the type of the first argument.
COALESCE
is usually a better function to use than ISNULL
, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier
has higher precedence than varchar
, so that doesn't help.
(It's also generally preferred because it extends to more than two arguments)
Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.
If you use PM2 via node modules instead of globally, you'll need to set interpreter: 'none'
in order for the above solutions to work. Related docs here.
In ecosystem.config.js
:
apps: [
{
name: 'myApp',
script: 'yarn',
args: 'start',
interpreter: 'none',
},
],
First you have to check login existence using syslogins view:
IF NOT EXISTS
(SELECT name
FROM master.sys.server_principals
WHERE name = 'YourLoginName')
BEGIN
CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END
Then you have to check your database existence:
USE your_dbname
IF NOT EXISTS
(SELECT name
FROM sys.database_principals
WHERE name = 'your_dbname')
BEGIN
CREATE USER [your_dbname] FOR LOGIN [YourLoginName]
END
A question mark is a signifier for 'any type'. ?
alone means
Any type extending
Object
(includingObject
)
while your example above means
Any type extending or implementing
HasWord
(includingHasWord
ifHasWord
is a non-abstract class)
Your statement is calling SELECT and WHERE but does not specify which TABLE or record set you would like to SELECT FROM.
SELECT DISTINCT Description, Date as treatmentDate
FROM (TABLE_NAME or SUBQUERY)<br> --This is missing from your query.
WHERE doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I
AND P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
You can use urllib2 as well:
import urllib2
req = urllib2.Request('http://www.python.org/fish.html')
try:
resp = urllib2.urlopen(req)
except urllib2.HTTPError as e:
if e.code == 404:
# do something...
else:
# ...
except urllib2.URLError as e:
# Not an HTTP-specific error (e.g. connection refused)
# ...
else:
# 200
body = resp.read()
Note that HTTPError
is a subclass of URLError
which stores the HTTP status code.
The ggrepel
package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel()
(draws rectangles around the text) or geom_text_repel()
functions.
library(ggplot2)
library(ggrepel)
nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")
nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) +
geom_point(color = "blue", size = 3)
### geom_label_repel
nbaplot +
geom_label_repel(aes(label = Name),
box.padding = 0.35,
point.padding = 0.5,
segment.color = 'grey50') +
theme_classic()
### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) +
geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77",
nba$PTS < 18 ~ "#d95f02",
TRUE ~ "#7570b3"),
size = 3, alpha = 0.8) +
geom_text_repel(data = subset(nba, PTS > 25),
nudge_y = 32 - subset(nba, PTS > 25)$PTS,
size = 4,
box.padding = 1.5,
point.padding = 0.5,
force = 100,
segment.size = 0.2,
segment.color = "grey50",
direction = "x") +
geom_label_repel(data = subset(nba, PTS < 18),
nudge_y = 16 - subset(nba, PTS < 18)$PTS,
size = 4,
box.padding = 0.5,
point.padding = 0.5,
force = 100,
segment.size = 0.2,
segment.color = "grey50",
direction = "x") +
scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
theme_classic(base_size = 16)
Edit: To use ggrepel
with lines, see this and this.
Created on 2019-05-01 by the reprex package (v0.2.0).
In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @
:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})
For VB.NET this syntax would be accomplished using the dot, .
, which in that language is default syntax for all anonymous types:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
Free read-only viewers:
tail
." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.Free editors:
Builtin programs (no installation required):
MORE
, not the Unix more
. A console program that allows you to view a file, one screen at a time.Web viewers:
Paid editors:
As Sahil Chhabra suggested you can use @JsonFormat
with proper shape
on your variable.
In case you would like to apply it on every BigDecimal
field you have in your Dto's
you can override default format for given class.
@Configuration
public class JacksonObjectMapperConfiguration {
@Autowired
public void customize(ObjectMapper objectMapper) {
objectMapper
.configOverride(BigDecimal.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
}
}
The name of the spyder executable was changed to spyder3.exe in python version 3. I install pyqt5 and spyder via pip and was able to launch spyder3. I first tried without installing pyqt5 and nothing happened. Once I installed pyqt5, then spyder 3 opened.
Try the following from a windows cmd.exe prompt:
C:\Users\..>pip install pyqt5
C:\Users\..>pip install spyder
C:\Users\..>spyder3
This is the question I faced in my interview.
Why is main method in Java called as public static void main(String[] args) ?
Answer:
1.main() must be declared public because it is invoked by JVM whenever the program execution starts.JVM doesnot belong to our program package.
Inorder to access main outside the package we have to declare it as public.If we declare it as anything other than public it shows a Runtime Error but not Compilation time error
2.main() must be declared as static because if a method is declared as static then we can call that method outside the class using ClassName.methodName();
class Sample
{
static void fun()
{
System.out.println("Hello");
}
}
class Test
{
public static void main(String[] args)
{
Sample.fun();
}
}
The JVM will first Load the Test class,and will check for the Commandline arguments and calls the main method as Test.main();
3.main() must be declared as void main() because JVM is not expecting any value from main().So,it must be declared as void.
If other return type is provided,the it is a RunTimeError i.e;NoSuchMethodFoundError.
4.main() must have String arguements as arrays because JVM calls main method by passing command line arguement.As they are stored in string array object it is passed as an argument to main().
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Just to generate the java classes from wsdl to me the best tool is "cxf wsdl2java". Its pretty simple and easy to use. I have found some complexities with some data type in axis2. But unfortunately you can't use those client stub code in your android application because android environment doesn't allow the "java/javax" package name in compiling time unless you rename the package name.
And in the android.jar all the javax.* sources for web service consuming are not available. To resolve these I have developed this WS Client Generation Tool for android.
In background it uses "cxf wsdl2java" to generate the java client stub for android platform for you, And I have written some sources to consume the web service in a smarter way.
Just give the wsdl file location it will give you the sources and some library. you have to just put the sources and the libraries in your project. and you can just call it in some "method call fashion" just we do in our enterprise project, you don't need to know the namespace/soap action etc. For example, you have a service to login, what you need to do is :
LoginService service = new LoginService ( );
Login login = service.getLoginPort ( );
LoginServiceResponse resp = login.login ( "someUser", "somePass" );
And its fully open and free.
Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g
$getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");
foreach($getvidids->result() as $key=>$myids)
{
$vidid[$key] = $myids->videoid; // better methodology to retrieve and store multiple records in arrays in loop
}
<div class="row" data-toggle="popover" data-trigger="hover"
data-content="My popover content.My popover content.My popover content.My popover content.">
<div class="col-md-6">
<label for="name">Name:</label>
<input id="name" class="form-control" type="text" />
</div>
</div>
Basically i put the popover code in the row div, instead of the input div. Solved the problem.
You can use Eloquent in different queries and make things easier to understand and mantain:
$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
->select('product_id'); //don't need ->get() or ->first()
and then we put all together:
Products::whereIn('id', $productCategory)
->where('active', 1)
->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
->get();//runs all queries at once
This will generate the same query that you wrote in your question.
It happens to me only when modifying the XML files on the project. If you rebuild the entire project before running (Build > Rebuild Project) it doesn't show up anymore.
Old question but I came up with a definitive answer with an example. Can't hurt to keep questions fresh as I had this same problem and didn't find a clear answer. The key is to make sure you have numpy
imported, and then run the isinstance
bool. While this may seem simple, if you are doing some computations across different data types, this small check can serve as a quick test before your start some numpy vectorized operation.
##################
# important part!
##################
import numpy as np
####################
# toy array for demo
####################
arr = np.asarray(range(1,100,2))
########################
# The instance check
########################
isinstance(arr,np.ndarray)
So this is ancient, but there's a much better modern solution. Not sure what version of c#/.NET is required, but this is how I do it:
... Other method code not relevant to the question.
// a token source that will timeout at the specified interval, or if cancelled outside of this scope
using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutTokenSource.Token);
async Task<MessageResource> FetchAsync()
{
try
{
return await MessageResource.FetchAsync(m.Sid);
} catch (TaskCanceledException e)
{
if (timeoutTokenSource.IsCancellationRequested)
throw new TimeoutException("Timeout", e);
throw;
}
}
return await Task.Run(FetchAsync, linkedTokenSource.Token);
the CancellationTokenSource
constructor takes a TimeSpan
parameter which will cause that token to cancel after that interval has elapsed. You can then wrap your async (or syncronous, for that matter) code in another call to Task.Run
, passing the timeout token.
This assumes you're passing in a cancellation token (the token
variable). If you don't have a need to cancel the task separately from the timeout, you can just use timeoutTokenSource
directly. Otherwise, you create linkedTokenSource
, which will cancel if the timeout ocurrs, or if it's otherwise cancelled.
We then just catch OperationCancelledException
and check which token threw the exception, and throw a TimeoutException
if a timeout caused this to raise. Otherwise, we rethrow.
Also, I'm using local functions here, which were introduced in C# 7, but you could easily use lambda or actual functions to the same affect. Similarly, c# 8 introduced a simpler syntax for using statements, but those are easy enough to rewrite.
Most browsers don't fully support the numerical values for font-weight
. Here's a good article about the problem, and even tough it's a little old, it does seem to be correct.
If you need something bolder then you might want to try using a different font that's bolder than your existing one. Naturally, you could probably adjust the font size for a similar effect.
It is possible to use patterns in a .gitignore
file. See the gitignore man page. The pattern */target/*
should ignore any directory named target and anything under it. Or you may try */target/**
to ignore everything under target.
Just change
var div = '<div>top div</div>'; // you just created a text string
to
var div = document.createElement("div"); // we want a DIV element instead
div.innerHTML = "top div";
Ansible command-line help, such as ansible-playbook --help
shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.
There is the command line parameter --spider
exactly for this. In this mode, wget does not download the files and its return value is zero if the resource was found and non-zero if it was not found. Try this (in your favorite shell):
wget -q --spider address
echo $?
Or if you want full output, leave the -q
off, so just wget --spider address
. -nv
shows some output, but not as much as the default.