A simple method: enable logging in recent versions of Requests (1.x and higher.)
Requests uses the http.client
and logging
module configuration to control logging verbosity, as described here.
Code excerpted from the linked documentation:
import requests
import logging
# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
requests.get('https://httpbin.org/headers')
$ python requests-logging.py
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226
I'm also struck with this same problem, finally i got simple solution. just added one line to action bar style.
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@color/colorAccent</item>
<item name="android:colorBackground">@color/colorAppWhite</item>
</style>
"android:colorBackground" is enough to change option menu background
I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.
To get the current path from within the JSP file you can simply do one of the following:
<%= request.getContextPath() %>
<%= request.getRequestURI() %>
<%= request.getRequestURL() %>
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
use google guava !
Iterable<String> fieldsIterable = ...
List<String> fields = Lists.newArrayList(fieldsIterable);
++
As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.
Go to Product > Clean Build Folder
This behavior is easy explained by:
So:
def x(a=0, b=[], c=[], d=0):
a = a + 1
b = b + [1]
c.append(1)
print a, b, c
a
doesn't change - every assignment call creates new int object - new object is printedb
doesn't change - new array is build from default value and printedc
changes - operation is performed on same object - and it is printedWhile the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per PEP8. You should also avoid mixing tabs and spaces.
I also recommend that you try to run your script using the '-tt
' command-line option to determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list'
option).
There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.
I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use element.get_attribute('value')
for input elements and element.text
to return the text node of an element.
You could check the WebElement object with element.tag_name
to find out what kind of element it is and return the appropriate value.
This should help you figure out:
driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')
element_text = element.text
element_attribute_value = element.get_attribute('value')
print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
Codified version of all other answers (at the time of writing):
import java.io.*;
/**
* This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
* <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
* of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
* Also includes comments and observations from others on the same question, and my own experience.
* <p>
* <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
* <p>
* <b>JVM memory management crash course</b>:
* Java virtual machine process' heap size is bounded by the maximum memory allowed.
* The startup and maximum size can be configured by JVM arguments.
* JVMs don't allocate the maximum memory on startup as the program running may never require that.
* This is to be a good player and not waste system resources unnecessarily.
* Instead they allocate some memory and then grow when new allocations require it.
* The garbage collector will be run at times to clean up unused objects to prevent this growing.
* Many parameters of this management such as when to grow/shrink or which GC to use
* can be tuned via advanced configuration parameters on JVM startup.
*
* @see <a href="http://stackoverflow.com/a/42567450/253468">
* What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
* @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
* Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
* Full VM options reference for Windows</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
* Full VM options reference for Linux, Mac OS X and Solaris</a>
* @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
* Java HotSpot VM Options quick reference</a>
*/
public class SystemMemory {
// can be white-box mocked for testing
private final Runtime runtime = Runtime.getRuntime();
/**
* <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
* <p>
* <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
*/
public long getAllocatedTotal() {
return runtime.totalMemory();
}
/**
* <b>Current allocated free memory</b>: space immediately ready for new objects.
* <p>
* <i>Caution</i>: this is not the total free available memory,
* the JVM may grow the heap for new allocations.
*/
public long getAllocatedFree() {
return runtime.freeMemory();
}
/**
* <b>Used memory</b>:
* Java heap currently used by instantiated objects.
* <p>
* <i>Caution</i>: May include no longer referenced objects, soft references, etc.
* that will be swept away by the next garbage collection.
*/
public long getUsed() {
return getAllocatedTotal() - getAllocatedFree();
}
/**
* <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
* <p>
* <i>Caution</i>: This may change over time, do not cache it!
* There are some JVMs / garbage collectors that can shrink the allocated process memory.
* <p>
* <i>Caution</i>: If this is true, the JVM will likely run GC more often.
*/
public boolean isAtMaximumAllocation() {
return getAllocatedTotal() == getTotal();
// = return getUnallocated() == 0;
}
/**
* <b>Unallocated memory</b>: amount of space the process' heap can grow.
*/
public long getUnallocated() {
return getTotal() - getAllocatedTotal();
}
/**
* <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
* <p>
* <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
*/
public long getTotal() {
return runtime.maxMemory();
}
/**
* <b>Total free memory</b>: memory available for new Objects,
* even at the cost of growing the allocated memory of the process.
*/
public long getFree() {
return getTotal() - getUsed();
// = return getAllocatedFree() + getUnallocated();
}
/**
* <b>Unbounded memory</b>: there is no inherent limit on free memory.
*/
public boolean isBounded() {
return getTotal() != Long.MAX_VALUE;
}
/**
* Dump of the current state for debugging or understanding the memory divisions.
* <p>
* <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
*/
public String getCurrentStats() {
StringWriter backing = new StringWriter();
PrintWriter out = new PrintWriter(backing, false);
out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
getAllocatedTotal(),
(float)getAllocatedTotal() / (float)getTotal() * 100,
getTotal(),
isBounded()? "bounded" : "unbounded",
isAtMaximumAllocation()? "maxed out" : "can grow",
getUnallocated()
);
out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
getUsed(),
(float)getUsed() / (float)getTotal() * 100,
getTotal(),
(float)getUsed() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
getFree(),
(float)getFree() / (float)getTotal() * 100,
getTotal(),
getAllocatedFree(),
(float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.flush();
return backing.toString();
}
public static void main(String... args) {
SystemMemory memory = new SystemMemory();
System.out.println(memory.getCurrentStats());
}
}
I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:
jQuery('.bookmarkMeLink').click(function() {
if (window.sidebar && window.sidebar.addPanel) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(document.title,window.location.href,'');
}
else if(window.sidebar && jQuery.browser.mozilla){
//for other version of FF add rel="sidebar" to link like this:
//<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
jQuery(this).attr('rel', 'sidebar');
}
else if(window.external && ('AddFavorite' in window.external)) {
// IE Favorite
window.external.AddFavorite(location.href,document.title);
} else if(window.opera && window.print) {
// Opera Hotlist
this.title=document.title;
return true;
} else {
// webkit - safari/chrome
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
}
});
You can use us jquery function getJson :
$(function(){
$.getJSON('/api/rest/abc', function(data) {
console.log(data);
});
});
To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>IPA</string>
<key>LSItemContentTypes</key>
<array>
<string>public.item</string>
<string>public.content</string>
<string>public.data</string>
<string>public.database</string>
<string>public.composite-content</string>
<string>public.contact</string>
<string>public.archive</string>
<string>public.url-name</string>
<string>public.text</string>
<string>public.plain-text</string>
<string>public.source-code</string>
<string>public.executable</string>
<string>public.script</string>
<string>public.shell-script</string>
<string>public.xml</string>
<string>public.symlink</string>
<string>org.gnu.gnu-zip-archve</string>
<string>org.gnu.gnu-tar-archive</string>
<string>public.image</string>
<string>public.movie</string>
<string>public.audiovisual-?content</string>
<string>public.audio</string>
<string>public.directory</string>
<string>public.folder</string>
<string>com.apple.bundle</string>
<string>com.apple.package</string>
<string>com.apple.plugin</string>
<string>com.apple.application-?bundle</string>
<string>com.pkware.zip-archive</string>
<string>public.filename-extension</string>
<string>public.mime-type</string>
<string>com.apple.ostype</string>
<string>com.apple.nspboard-typ</string>
<string>com.adobe.pdf</string>
<string>com.adobe.postscript</string>
<string>com.adobe.encapsulated-?postscript</string>
<string>com.adobe.photoshop-?image</string>
<string>com.adobe.illustrator.ai-?image</string>
<string>com.compuserve.gif</string>
<string>com.microsoft.word.doc</string>
<string>com.microsoft.excel.xls</string>
<string>com.microsoft.powerpoint.?ppt</string>
<string>com.microsoft.waveform-?audio</string>
<string>com.microsoft.advanced-?systems-format</string>
<string>com.microsoft.advanced-?stream-redirector</string>
<string>com.microsoft.windows-?media-wmv</string>
<string>com.microsoft.windows-?media-wmp</string>
<string>com.microsoft.windows-?media-wma</string>
<string>com.apple.keynote.key</string>
<string>com.apple.keynote.kth</string>
<string>com.truevision.tga-image</string>
</array>
<key>CFBundleTypeIconFiles</key>
<array>
<string>Icon-76@2x</string>
</array>
</dict>
</array>
"an object" of what type?
You can certainly assign NULL
(and nullptr
) to objects of pointer types, and it is implementation defined if you can assign NULL
to objects of arithmetic types.
If you mean objects of some class type, the answer is NO (excepting classes that have operator=
accepting pointer or arithmetic types)
"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==
Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding
As the other posters say, pull merges changes from upstream into your repository. If you want to replace what is in your repository with what is in upstream, you have several options. Off the cuff, I'd go with
git checkout HEAD^1 # Get off your repo's master.. doesn't matter where you go, so just go back one commit
git branch -d master # Delete your repo's master branch
git checkout -t upstream/master # Check out upstream's master into a local tracking branch of the same name
This gives a pretty good overview over the current options. Some of which are named in other answers. Jython is not usable until they decide to implement Python 3.x and many of the other projects are coming form the python side and want to access java. But there are a few options still, to name something which has not been named yet: gRPC
You can probably use:
os.environ.get('USERNAME')
or
os.environ.get('USER')
But it's not going to be safe because environment variables can be changed.
Additional information to abouve answers for those still having problems.
FindBoost.cmake
may not content last
version fo Boost. Add it if needed.Boost_COMPILER
and Boost_ARCHITECTURE
suffix vars if needed.Sometimes you need to apply a function to the members of a list in place. The following code worked for me:
>>> def func(a, i):
... a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']
Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place
You should use return as in:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (exit) {
return;
}
I have been doing PHP for my project, and I can say that the following code works for me. You should try it.
echo '<input type = "text" value = '.$idtest.'>';
You can create regular expressions in JS in one of two ways:
/ab{2}/g
new RegExp("ab{2}", "g")
. Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is
new RegExp(regularExpressionString, modifiersString)
You can embed variables as part of the regularExpressionString. For example,
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")
This will match any appearance of the pattern cdcdcd
.
You can do it using this class I just made. With this class you can use the Map
object like another dictionary(including json serialization) or with the dot notation. I hope help you:
class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v
if kwargs:
for k, v in kwargs.iteritems():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
Usage examples:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']
Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION_SCHEMA views:
select COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
Use rgba as most of the commonly used browsers supports it..
.social img:hover {
background-color: rgba(0, 0, 0, .5)
}
This one worked for me:
df=df.sort_values(by=[2])
Whereas:
df=df.sort_values(by=['2'])
is not working.
df.reset_index(drop=True, inplace=True)
The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
I faced the same issue, I was trying to import translate from google.cloud but kept getting same error.
This is what I did
pip install protobuf
pip install google-cloud-translate
and to install storage service from google google-cloud-storage
should be installed separately
Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
And yes static methods can be overloaded just like any other method.
as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.
I experienced this crash even though I had the RecyclerView.LayoutManager
properly set. I had to move the RecyclerView
initialization code into the onViewCreated(...)
callback to fix this issue.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_listing, container, false);
rootView.setTag(TAG);
return inflater.inflate(R.layout.fragment_listing, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ListingAdapter(mListing);
mRecyclerView.setAdapter(mAdapter);
}
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
You can access them directly, by assigning the special variable @ARGV
to a list of variables.
So, for example:
( $st, $prod, $ar, $file, $chart, $e, $max, $flag ,$id) = @ARGV;
perl tmp.pl 1 2 3 4 5
\b is used as word boundary
word = "categorical cat"
Find all "cat" in the above word
without \b
re.findall(r'cat',word)
['cat', 'cat']
with \b
re.findall(r'\bcat\b',word)
['cat']
It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.
Entity::upsert([
['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);
You need to add gravity to the layout not the Button, gravity in button settings is for Text inside the button
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_gravity="right"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
echo "<a href='index.php'>Index Page</a>";
if you wanna use html tag like anchor tag you have to put in echo
Not a lot of "slick" going on so far:
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
When you initialize an array with a number, it creates an array with the length
set to that value so that the array appears to contain that many undefined
elements. Though some Array instance methods skip array elements without values, .join()
doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1
in there.
Example usage:
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
pad(10, 4, '-'); // --10
You can't ref
a property, but if your functions need both get
and set
access you can pass around an instance of a class with a property defined:
public class Property<T>
{
public delegate T Get();
public delegate void Set(T value);
private Get get;
private Set set;
public T Value {
get {
return get();
}
set {
set(value);
}
}
public Property(Get get, Set set) {
this.get = get;
this.set = set;
}
}
Example:
class Client
{
private string workPhone; // this could still be a public property if desired
public readonly Property<string> WorkPhone; // this could be created outside Client if using a regular public property
public int AreaCode { get; set; }
public Client() {
WorkPhone = new Property<string>(
delegate () { return workPhone; },
delegate (string value) { workPhone = value; });
}
}
class Usage
{
public void PrependAreaCode(Property<string> phone, int areaCode) {
phone.Value = areaCode.ToString() + "-" + phone.Value;
}
public void PrepareClientInfo(Client client) {
PrependAreaCode(client.WorkPhone, client.AreaCode);
}
}
It is going to write the value of your property model.Destination
This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.
Just delete your .metadata folder in your workspace and start eclipse....:)
(StartA <= EndB) and (EndA >= StartB)
Proof:
Let ConditionA Mean that DateRange A Completely After DateRange B
_ |---- DateRange A ------|
|---Date Range B -----| _
(True if StartA > EndB
)
Let ConditionB Mean that DateRange A is Completely Before DateRange B
|---- DateRange A -----| _
_ |---Date Range B ----|
(True if EndA < StartB
)
Then Overlap exists if Neither A Nor B is true -
(If one range is neither completely after the other,
nor completely before the other,
then they must overlap.)
Now one of De Morgan's laws says that:
Not (A Or B)
<=> Not A And Not B
Which translates to: (StartA <= EndB) and (EndA >= StartB)
NOTE: This includes conditions where the edges overlap exactly. If you wish to exclude that,
change the >=
operators to >
, and <=
to <
NOTE2. Thanks to @Baodad, see this blog, the actual overlap is least of:
{ endA-startA
, endA - startB
, endB-startA
, endB - startB
}
(StartA <= EndB) and (EndA >= StartB)
(StartA <= EndB) and (StartB <= EndA)
NOTE3. Thanks to @tomosius, a shorter version reads:
DateRangesOverlap = max(start1, start2) < min(end1, end2)
This is actually a syntactical shortcut for what is a longer implementation, which includes extra checks to verify that the start dates are on or before the endDates. Deriving this from above:
If start and end dates can be out of order, i.e., if it is possible that startA > endA
or startB > endB
, then you also have to check that they are in order, so that means you have to add two additional validity rules:
(StartA <= EndB) and (StartB <= EndA) and (StartA <= EndA) and (StartB <= EndB)
or:
(StartA <= EndB) and (StartA <= EndA) and (StartB <= EndA) and (StartB <= EndB)
or,
(StartA <= Min(EndA, EndB) and (StartB <= Min(EndA, EndB))
or:
(Max(StartA, StartB) <= Min(EndA, EndB)
But to implement Min()
and Max()
, you have to code, (using C ternary for terseness),:
(StartA > StartB? Start A: StartB) <= (EndA < EndB? EndA: EndB)
Windows 10 includes tar.exe
:
# example 1
tar.exe -a -c -f out.zip in.txt
# example 2
tar.exe -x -f out.zip
https://techcommunity.microsoft.com/t5/containers/-/ba-p/382409
If you have older Windows, you can still download it:
https://github.com/libarchive/libarchive/releases
# example 1
Compress-Archive in.txt out.zip
# example 2
Expand-Archive out.zip
https://docs.microsoft.com/powershell/module/microsoft.powershell.archive
For both tools, you can use a file or directory for the input.
I got the same error in this code:
var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
this was the exactly error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'
I solved this way:
var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated
NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory
BasicResponseHandler throws if the status is not 2xx. See its javadoc.
Here is how I would do it:
HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream
Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.
If you came here looking for an answer to this question but not exactly the way the OP meant, ie how do you get multi-line CMD to work in a single line, I have a sort of dangerous answer for you.
Trying to use this with things that actually use piping, like say findstr
is quite problematic. The same goes for dealing with else
s. But if you just want a multi-line conditional command to execute directly from CMD and not via a batch file, this should do work well.
Let's say you have something like this in a batch that you want to run directly in command prompt:
@echo off
for /r %%T IN (*.*) DO (
if /i "%%~xT"==".sln" (
echo "%%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file
echo Dumping SLN file contents
type "%%~T"
)
)
Now, you could use the line-continuation carat (^
) and manually type it out like this, but warning, it's tedious and if you mess up you can learn the joy of typing it all out again.
Well, it won't work with just ^
thanks to escaping mechanisms inside of parentheses shrug At least not as-written. You actually would need to double up the carats like so:
@echo off ^
More? for /r %T IN (*.sln) DO (^^
More? if /i "%~xT"==".sln" (^^
More? echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file^^
More? echo Dumping SLN file contents^^
More? type "%~T"))
Instead, you can be a dirty sneaky scripter from the wrong side of the tracks that don't need no carats by swapping them out for a single pipe (|
) per continuation of a loop/expression:
@echo off
for /r %T IN (*.sln) DO if /i "%~xT"==".sln" echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file | echo Dumping SLN file contents | type "%~T"
In my case, when I switch keyboard language to English, the auto complete works again.
Just need config file under ~/.ssh directory
ref : https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html
add bellow configuration in config file
Host bitbucket.org
IdentityFile ~/.ssh/<privatekeyfile>
isEmptyOrSpaces(str){
return !str || str.trim() === '';
}
Some old gradle tools cannot copy .so files into build folder by somehow, manually copying these files into build folder as below can solve the problem:
build/intermediates/rs/{build config}/{support architecture}/
build config: beta/production/sit/uat
support architecture: armeabi/armeabi-v7a/mips/x86
You can't use an initialization-list for a struct
after it's been initialized. You've already default-initialized the two Customer
structs when you declared the array customerRecords
. Therefore you're going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator=
member function to initialize the array members.
So either of the following could work:
Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = "Bob Jones";
customerRecords[1].uid = 25;
customerRecords[1].namem = "Jim Smith";
Or if you defined a constructor for your struct like:
Customer::Customer(int id, string input_name): uid(id), name(input_name) {}
You could then do:
Customer customerRecords[2];
customerRecords[0] = Customer(25, "Bob Jones");
customerRecords[1] = Customer(26, "Jim Smith");
Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because you're actually initializing the Customer
structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.
let now = new Date();
let timestamp = now.getFullYear().toString();
let month = now.getMonth() + 1;
timestamp += (month < 10 ? '0' : '') + month.toString();
timestamp += (now.getDate() < 10 ? '0' : '') + now.getDate().toString();
timestamp += (now.getHours() < 10 ? '0' : '') + now.getHours().toString();
timestamp += (now.getMinutes() < 10 ? '0' : '') + now.getMinutes().toString();
timestamp += (now.getSeconds() < 10 ? '0' : '') + now.getSeconds().toString();
timestamp += (now.getMilliseconds() < 100 ? '0' : '') + now.getMilliseconds().toString();
$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags_to_remove = array('script','style','iframe','link');
foreach($tags_to_remove as $tag){
$element = $dom->getElementsByTagName($tag);
foreach($element as $item){
$item->parentNode->removeChild($item);
}
}
$html = $dom->saveHTML();
What worked for me:
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
<script src="foo.js?<?php echo date('YmdHis',filemtime('foo.js'));?>"></script>
It will refresh if modify.
The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.
Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793
There are a few ways to reach this goal. Basically you need an object which is extendable.
obj.a = type('Test', (object,), {})
obj.a.b = 'fun'
obj.b = lambda:None
class Test:
pass
obj.c = Test()
A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.
In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.
In jQuery this should do the trick:
$.ajax({
url: 'http://yourserver/',
data: 'your image',
success: function(){window.open(someUrl);},
async: false
});
Here is your answer: Open new tab without popup blocker after ajax call on user click
For me the easiest solution was to put my modal in a wrapper with absolute position and z-index higher than .modal-backdrop. Since modal-backdrop (at least in my case) has z-index 1050:
.my-modal-wrapper {_x000D_
position: absolute;_x000D_
z-index: 1060;_x000D_
}
_x000D_
<div class="my-modal-wrapper"></div>
_x000D_
Here is a rough description of HashMap
's mechanism, for Java 8
version, (it might be slightly different from Java 6).
hash()
on key, and it decide which bucket of the hashtable to use for a given key.Map.Entry
HashMap.Node
Linked list version of node.
It could represent:
HashMap.TreeNode
Node[] table
Set<Map.Entry> entrySet
Set of entities.int size
float loadFactor
int threshold
threshold = capacity * loadFactor
int hash(key)
How to map hash to bucket?
Use following logic:
static int hashToBucket(int tableSize, int hash) { return (tableSize - 1) & hash; }
In hash table, capacity means the bucket count, it could be get from table.length
.
Also could be calculated via threshold
and loadFactor
, thus no need to be defined as a class field.
Could get the effective capacity via: capacity()
threshold
reached, will double hashtable's capacity(table.length
), then perform a re-hash on all elements to rebuild the table.O(1)
, because:
O(1)
.O(1)
.O(1)
, not O(log N)
.A section is basically a wrapper for h1
(or other h
tags) and the content that corresponds to this. An article
is essentially a document within your document that is repeated or paginated...like each blog post on your document can be an article, or each comment on your document can be an article.
If you specify API >= 16, Activity#finishAffinity() meets your needs.
git gc --aggressive
is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now
). You have other commands to clean the repo too. Don't forget though, sometimes git gc
alone can increase the size of the repo!
It can be also used after a filter-branch
, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch
can keep backup refs in .git/refs/original
, so that directory can be cleaned too.
Finally, as mentioned in this comment and this question; cleaning the reflog can help:
git reflog expire --all --expire=now
git gc --prune=now --aggressive
An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository
Update Feb. 2021, eleven years later: the new git maintenance
command (man page) should supersede git gc
, and can be scheduled.
Simplest code is DataGridView1.SelectedCells(column_index).Value
As an example, for the first selected cell:
DataGridView1.SelectedCells(0).Value
An intuitive explanation to this is by simply analysing a single loop:
So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives
For every V
=>
O(1)
+
O(e)
=> O(V) + O(E)
In the version of .NET I am using you also have to do this:
System.Net.ServicePointManager.Expect100Continue = false;
If you don't, the HttpWebRequest
class will automatically add the Expect:100-continue
request header which fouls everything up.
Also I learned the hard way that you have to have the right number of dashes. whatever you say is the "boundary" in the Content-Type
header has to be preceded by two dashes
--THEBOUNDARY
and at the end
--THEBOUNDARY--
exactly as it does in the example code. If your boundary is a lot of dashes followed by a number then this mistake won't be obvious by looking at the http request in a proxy server
From javadocs
next() Returns the next token if it matches the pattern constructed from the specified string. nextLine() Advances this scanner past the current line and returns the input that was skipped.
Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.
As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.
From Here
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
$("#img_id").error(function(){
//$(this).hide();
//alert("img not loaded");
//some action you whant here
});
careful - .error() event will not trigger when the src attribute is empty for an image.
This is the most efficient way to get just the callers class. Other approaches take an entire stack dump and only give you the class name.
However, this class in under sun.*
which is really for internal use. This means that it may not work on other Java platforms or even other Java versions. You have to decide whether this is a problem or not.
In Linker, general, additional library directories, add the directory to the .dll or .libs you have included in Linker, Input. It does not work if you put this in VC++ Directories, Library Directories.
This bug still exists in 0.8+/1.10
With Jackson
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.2.2'
I had to include as well as the above suggestion before it would compile
exclude 'META-INF/services/com.fasterxml.jackson.core.JsonFactory'
AFAIK, there is nothing built in for searching all columns. You can use Find
only against the primary key. Select
needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.
Here's another idea. You have to remember, that it's .NET underneath:
$arr = [System.Array]::CreateInstance([System.Object], 5)
$arr.GetType()
$arr.Length
$arr = [Object[]]::new(5)
$arr.GetType()
$arr.Length
Result:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
5
True True Object[] System.Array
5
Using new()
has one distinct advantage: when you're programming in ISE and want to create an object, ISE will give you hint with all paramer combinations and their types. You don't have that with New-Object
, where you have to remember the types and order of arguments.
See response on this thread that has worked for me:
https://stackoverflow.com/a/62275293/11141700
NOTE - Additional STEP 3 that has made the difference for me compared to similar approaches suggested here
In short:
Step 1 - Generate config for Jupyter Notebook:
jupyter notebook --generate-config
Step 2 - Edit the config file using "nano" or other editor
The config fileshould be under your home directory under ".jupyter" folder:
~/.jupyter/jupyter_notebook_config.py
Step 3 - Disable launching browser by redirecting file
First comment out the line, then change True to False:
c.NotebookApp.use_redirect_file = False
Step 4 - add a line to your .bashrc file to set the BROWSER path
export BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'
For me it was Chrome under my Windows Program File. Otherwise any linux installation under WSL doesn't have a native browser to launch, so need to set it to the Windows executable.
Step 5 - restart .bashrc
source .bashrc
Simply use min()
SELECT company, workflow, MIN(date)
FROM workflowTable
GROUP BY company, workflow
I used slice, split and join You can just write one line of code
let arrys = (str.split(":").slice(1)).join(":");
Just to add a different approach - you can simply cast your ref, something like:
let myInputElement: Element = this.refs["myInput"] as Element
PHP side code Name of file class.sendCode.php
<?php
class sendCode{
function __construct($dateini,$datefin) {
echo $this->printCode($dateini,$datefin);
}
function printCode($dateini,$datefin){
$code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute,
//only javascript or Jquery code , dont incluce <script> tags
return $code ;
}
}
new sendCode($_POST['dateini'],$_POST['datefin']);
Now from your Html page you must trigger the ajax function to send the data.
.... <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>
Now at our local script.js we will define the ajax
function triggerAjax() {
$.ajax({
type: "POST",
url: 'class.sendCode.php',
dataType: "HTML",
data : {
dateini : $('#startdate').val(),
datefin : $('#enddate').val()},
success: function(data){
$.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class. That is our javascript code to be executed
}
});
}
Now we can use:
sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)
You could search all the option values until it finds the correct one.
var defaultVal = "Country";
$("#select").find("option").each(function () {
if ($(this).val() == defaultVal) {
$(this).prop("selected", "selected");
}
});
This is pretty simple with numpy
, just subtract the arrays:
diffs = array1 - array2
I get:
diffs == array([ 0.1, 0.2, 0.3])
Perhaps you want to do
soup.find("li", { "class" : "test" }).find('a')
Also you can use JavaScript to solve your problem
iterate(item, index) {
console.log(`${item} has index ${index}`);
//Do what you want...
}
readJsonList() {
jsonList.forEach(this.iterate);
//it could be any array list.
}
_x000D_
just set the width of the td/column you want to be fixed and the rest will expand.
<td width="200"></td>
There are a number of ways to get information on the attributes of your DataFrame or Series.
Create Sample DataFrame and Series
df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df
a b
0 5.0 9
1 2.0 2
2 NaN 4
s = df['a']
s
0 5.0
1 2.0
2 NaN
Name: a, dtype: float64
shape
AttributeThe shape
attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.
df.shape
(3, 2)
s.shape
(3,)
len
functionTo get the number of rows of a DataFrame or get the length of a Series, use the len
function. An integer will be returned.
len(df)
3
len(s)
3
size
attributeTo get the total number of elements in the DataFrame or Series, use the size
attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len
function:
df.size
6
s.size
3
ndim
attributeThe ndim
attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:
df.ndim
2
s.ndim
1
count
methodThe count
method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.
df.count() # by default, get the count of each column
a 2
b 3
dtype: int64
df.count(axis='columns') # change direction to get count of each row
0 2
1 2
2 1
dtype: int64
For a Series, there is only one axis for computation and so it just returns a scalar:
s.count()
2
info
method for retrieving metadataThe info
method returns the number of non-missing values and data types of each column
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a 2 non-null float64
b 3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
gem uninstall -aIx
and
bundle install
worked for me.
There seems to be no proper solution. max-height
approach is quite good but doesn't work well for the hide phase - there will be a noticeable delay unless you know the height of the content.
I think the best way is to use max-height
but only for the show phase. And not to use any animation on hiding. For most cases it shouldn't be crucial.
max-height
should be set to a quite huge value to ensure any content fits. Animation speed can be controlled using transition
duration (speed = max-height / duration
). Speed does not depend on the size of the content. The time it takes to show the whole content will depend on its size.
document.querySelector("button").addEventListener(_x000D_
"click", _x000D_
function(){_x000D_
document.querySelector("div").classList.toggle("hide");_x000D_
}_x000D_
)
_x000D_
div { _x000D_
max-height: 20000px;_x000D_
transition: max-height 3000ms;_x000D_
overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.hide {_x000D_
max-height: 0;_x000D_
transition: none;_x000D_
}
_x000D_
<button>Toggle</button>_x000D_
<div class="hide">Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. _x000D_
</div>
_x000D_
If Android Studio shows you the path /Users/<name>/Library/Android/sdk
but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.
Just add e.preventDefault();
in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user agent that if the event is not explicitly processed, its default action should not be taken into account as it would normally be. The event continues to propagate as usual, unless one of its listeners calls
stopPropagation ()
orstopImmediatePropagation ()
, either of which terminates the propagation.
In SQL server 2005 new datatypes were introduced: varchar(max)
and nvarchar(max)
They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar
and nvarchar
. Among these advantages are the ability to use string manipulation functions such as substring().
Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.
In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.
As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.
FWIW, here is a sort method for showing which processes are using the most virt memory.
memstat | sort -k 1 -t':' -g -r | less
Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
Assuming your data frame is named d
,
d[order(as.Date(d$V3, format="%d/%m/%Y")),]
Read my blog post, Sorting a data frame by the contents of a column, if that doesn't make sense.
In 0.18.1 groupby
together with count
does not give the frequency of unique values:
>>> df
a
0 a
1 b
2 s
3 s
4 b
5 a
6 b
>>> df.groupby('a').count()
Empty DataFrame
Columns: []
Index: [a, b, s]
However, the unique values and their frequencies are easily determined using size
:
>>> df.groupby('a').size()
a
a 2
b 3
s 2
With df.a.value_counts()
sorted values (in descending order, i.e. largest value first) are returned by default.
You will need to assign an ID to the checkbox:
<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">
and then in JavaScript:
document.getElementById("checkboxId").checked = false;
Here are some other solutions. No need to use additional plugins.
Snippets down below uses .subtract
API and requires moment 2.1.0+
Snippets are also available in here https://jsfiddle.net/traBolic/ku5cyrev/
Formatting with the .format
API:
const duration = moment.duration(9, 's');
const intervalId = setInterval(() => {
duration.subtract(1, "s");
const inMilliseconds = duration.asMilliseconds();
// "mm:ss:SS" will include milliseconds
console.log(moment.utc(inMilliseconds).format("HH[h]:mm[m]:ss[s]"));
if (inMilliseconds !== 0) return;
clearInterval(intervalId);
console.warn("Times up!");
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
_x000D_
Manuel formatting by .hours
, .minutes
and .seconds
API in a template string
const duration = moment.duration(9, 's');
const intervalId = setInterval(() => {
duration.subtract(1, "s");
console.log(`${duration.hours()}h:${duration.minutes()}m:${duration.seconds()}s`);
// `:${duration.milliseconds()}` to add milliseconds
if (duration.asMilliseconds() !== 0) return;
clearInterval(intervalId);
console.warn("Times up!");
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
_x000D_
Insert some vertical space
blah blah blah \\
\vspace{1cm}
to scale to the font, use ex
(the height of a lowercase "x") as the unit, and there are various predefined lengths related to the line spacing available, you might be particularly interested in baselineskip
.
If lib/__init__.py
defines the Helper class then in settings.py you can use:
from . import Helper
This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__
.
(Confirmed with python 2.7.10, running on Windows.)
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
The return true
part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder()
, like so:
// Called on 'Return' pressed. Return false to ignore.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).
For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.
yes it's possible to print a string to the console.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string strMytestString("hello world");
cout << strMytestString;
return 0;
}
stdafx.h isn't pertinent to the solution, everything else is.
Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.
Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close
private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
And that should be it.
The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.
Try the unix "wc" command. I don't mean use it, I mean download the source and see how they do it. It's probably in c, but you can easily port the behavior to java. The problem with making your own is to account for the ending cr/lf problem.
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
You could do this, where td
is your series of timedeltas. The division converts the nanosecond deltas into day deltas, and the conversion to int drops to whole days.
import numpy as np
(td / np.timedelta64(1, 'D')).astype(int)
Important note
The following discussion assumes that we are talking about code structured as in the example above: no matter which alternative is chosen, an exception will cause the method to logically stop doing whatever it was in the middle of.
As long as you intend to do the same thing no matter which statement in the try
block throws an exception, then it's certainly better to use a single try
/catch
. For example:
function createCar()
{
try {
install_engine();
install_brakes();
} catch (Exception $e) {
die("I could not create a car");
}
}
Multiple try
/catch
blocks are useful if you can and intend to handle the failure in a manner specific to what exactly caused it.
function makeCocktail()
{
try {
pour_ingredients();
stir();
} catch (Exception $e) {
die("I could not make you a cocktail");
}
try {
put_decorative_umbrella();
} catch (Exception $e) {
echo "We 're out of umbrellas, but the drink itself is fine"
}
}
No, TypeScript doesn't have a natural way of setting defaults for properties of an object defined like that where one has a default and the other does not. You could define a richer structure:
class Name {
constructor(public first : string,
public last: string = "Smith") {
}
}
And use that in place of the inline type definition.
function sayName(name: Name) {
alert(name.first + " " + name.last);
}
You can't do something like this unfortunately:
function sayName(name : { first: string; last?:string }
/* and then assign a default object matching the signature */
= { first: null, last: 'Smith' }) {
}
As it would only set the default if name
was undefined
.
Using the usual grouper recipe, you could do:
Python 2:
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))
Python 3:
d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))
If you want all the li tags in an array even when they are in different ul tags then you can simply do
var lis = document.getElementByTagName('li');
and if you want to get particular div tag li's then:
var lis = document.getElementById('divID').getElementByTagName('li');
else if you want to search a ul first and then its li tags then you can do:
var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
var lis=uls[i].getElementsByTagName('li');
for(var j=0;j<lis.length;j++){
console.log(lis[j].innerHTML);
}
}
Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:
<input type="text" name="name" autofocus="autofocus" id="xax" />
If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded..
For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html
I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the asizeof
module in particular goes back to 2.2!
For example, using hughdbrown's example but with from pympler import asizeof
at the start and print asizeof.asizeof(v)
at the end, I see (system Python 2.5 on MacOSX 10.5):
$ python pymp.py
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32
Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.
You may have to use $HTTP_SERVER_VARS['server_ADDR']
if you are not getting anything from above answers and if you are using older version of PHP
Here's the LLVM header.
// -*- C++ -*-
//===--------------------------- __nullptr --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_NULLPTR
#define _LIBCPP_NULLPTR
#include <__config>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifdef _LIBCPP_HAS_NO_NULLPTR
_LIBCPP_BEGIN_NAMESPACE_STD
struct _LIBCPP_TEMPLATE_VIS nullptr_t
{
void* __lx;
struct __nat {int __for_bool_;};
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t() : __lx(0) {}
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}
template <class _Tp>
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
operator _Tp* () const {return 0;}
template <class _Tp, class _Up>
_LIBCPP_INLINE_VISIBILITY
operator _Tp _Up::* () const {return 0;}
friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator==(nullptr_t, nullptr_t) {return true;}
friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator!=(nullptr_t, nullptr_t) {return false;}
};
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t __get_nullptr_t() {return nullptr_t(0);}
#define nullptr _VSTD::__get_nullptr_t()
_LIBCPP_END_NAMESPACE_STD
#else // _LIBCPP_HAS_NO_NULLPTR
namespace std
{
typedef decltype(nullptr) nullptr_t;
}
#endif // _LIBCPP_HAS_NO_NULLPTR
#endif // _LIBCPP_NULLPTR
(a great deal can be uncovered with a quick grep -r /usr/include/*`
)
One thing that jumps out is the operator *
overload (returning 0 is a lot friendlier than segfaulting...).
Another thing is it doesn't look compatible with storing an address at all. Which, compared to how it goes slinging void*'s and passing NULL results to normal pointers as sentinel values, would obviously reduce the "never forget, it might be a bomb" factor.
You can get the results by the name of the process using
ps -C chrome -o %cpu,%mem,cmd
the -C
option allows you to use process name without knowing it's pid.
The solution I've found was:
$text = 'Line one\n\nLine two');
$text = explode('\n', $text);
foreach ($text as $txt){
$pdf->Write($txt);
$pdf->Ln();
}
So this way, you may have any number of \n in any position, if you're getting this text dinamically from the database, it will break lines correctrly.
You may not get "xuxu p1 p2 p3 p4" as it seems. But when you are in PowerShell and you set
PS > set-executionpolicy Unrestricted -scope currentuser
You can run those scripts like this:
./xuxu p1 p2 p3 p4
or
.\xuxu p1 p2 p3 p4
or
./xuxu.ps1 p1 p2 p3 p4
I hope that makes you a bit more comfortable with PowerShell.
weight values 0-1 share distribution of available space (after setting layout_width="0px") in proportion to the weight value. View elements with weight not specified (no weight entry) get weight 0 which means they get no expansion.
A simple alternative with no weight entries needed is to attach marquee to a view with text which tells it to expand from minimum needed for the text (wrap_content) to space available EditText: android:layout_width="wrap_content" android:ellipsize="marquee"
I was having the same issue, I made the table fixed and then specified my td width. If you have th you can do those as well.
<style>
table {
table-layout: fixed;
word-wrap: break-word;
}
</style>
<td width="10%" /td>
I didn't have any luck with .table-nonfluid.
\t
in a string marks an escape sequence for a tab character. For a literal \
, use \\
.
If you just want to convert a relative path with optional parameters I created an extension method for IHttpContextAccessor
public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
var request = httpContextAccessor.HttpContext.Request;
var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();
if (parameters != null)
{
url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
}
return url;
}
private static Dictionary<string, string> ToDictionary(object obj)
{
var json = JsonConvert.SerializeObject(obj);
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
You can then call the method from your service/view using the injected IHttpContextAccessor
var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });
document.getElementById("link").getAttribute("href");
If you have more than one <a>
tag, for example:
<ul>_x000D_
<li>_x000D_
<a href="1"></a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="2"></a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="3"></a>_x000D_
</li>_x000D_
</ul>
_x000D_
You can do it like this: document.getElementById("link")[0].getAttribute("href");
to access the first array of <a>
tags, or depends on the condition you make.
It's actually very easy in jQuery:
$("#ddl_1").clone().attr("id",newId).appendTo("body");
Change .appendTo() of course...
If you'd like to call this method directly on an NSDate object and get the timestamp as a string in milliseconds without any decimal places, define this method as a category:
@implementation NSDate (MyExtensions)
- (NSString *)unixTimestampInMilliseconds
{
return [NSString stringWithFormat:@"%.0f", [self timeIntervalSince1970] * 1000];
}
I had a similar problem after starting a new IntelliJ project. I found that the "module compile output path" for my module was not properly specified. When I assigned the path in the module's "compile output path" to the proper location, the problem was solved. The compile output path is assigned in the Project settings. Under Modules, select the module involved and select the Paths tab...
Paths tab in the Project Settings | Modules dialog
...I sent the compiler output to a folder named "output" that is present in the parent Project folder.
You can try this code
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script>
function initialize()
{
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);
var markers = [
['title-1', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.120850, '<p> Hello - 1 </p>'],
['title-2', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.420850, '<p> Hello - 2 </p>'],
['title-3', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.720850, '<p> Hello - 3 </p>'],
['title-4', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.020850, '<p> Hello - 4 </p>'],
['title-5', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.320850, '<p> Hello - 5 </p>']
];
var infoWindow = new google.maps.InfoWindow(), marker, i;
var testMarker = [];
var status = [];
for( i = 0; i < markers.length; i++ )
{
var title = markers[i][0];
var loan = markers[i][1];
var lat = markers[i][2];
var long = markers[i][3];
var add = markers[i][4];
var iconGreen = 'img/greenMarker.png'; //green marker
var iconRed = 'img/redMarker.png'; //red marker
var infoWindowContent = loan + "\n" + placeId + add;
var position = new google.maps.LatLng(lat, long);
bounds.extend(position);
marker = new google.maps.Marker({
map: map,
title: title,
position: position,
icon: iconGreen
});
testMarker[i] = marker;
status[i] = 1;
google.maps.event.addListener(marker, 'click', ( function toggleBounce( i,status,testMarker)
{
return function()
{
infoWindow.setContent(markers[i][1]+markers[i][4]);
if( status[i] === 1 )
{
testMarker[i].setIcon(iconRed);
status[i] = 0;
}
for( var k = 0; k < markers.length ; k++ )
{
if(k != i)
{
testMarker[k].setIcon(iconGreen);
status[i] = 1;
}
}
infoWindow.open(map, testMarker[i]);
}
})( i,status,testMarker));
map.fitBounds(bounds);
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event)
{
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="mapDiv" style="width:820px; height:300px"></div>
Use Date.Add
and add a New TimeSpan
with the new time you want to add
DateTime dt = DateTime.Now
dt.Date.Add(new TimeSpan(12,15,00))
If anyone experiences the error for the same reason why I experience it, here's my solution:
if you had Html.AntiForgeryToken();
change it to @Html.AntiForgeryToken()
I have seen this problem when the user had set up a scheduled task to run under his account. He forgot to update the password on the task after he changed his account password. The scheduled task was trying to logon with the old password and kept locking out his account.
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
This error occurs when versions of NodeJS and Node Sass are not matched.
you can resolve your issue by doing as below:
- Step 1: Remove Nodejs from your computer
- Step 2: Reinstall Nodejs version 14.15.1.
- Step 3: Uninstall Node sass by run the command npm uninstall node-sass
- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]
After all steps, you can run command ng serve -o
to run your application.
To put it on one line:
currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.
If you set fetchType=EAGER
This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.
If you set fetchType=LAZY
the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.
You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.
For the second part of the question - how to get hibernate to generate optimised SQL?
Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.
Thanks @Mladen Janjetovic,
Your suggestion worked for me in mac with ampps installed.
Copied: http://curl.haxx.se/ca/cacert.pem
To: /Applications/AMPPS/extra/etc/openssl/certs/cacert.pem
And updated php.ini
with that path and restarted Apache:
[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo="/Applications/AMPPS/extra/etc/openssl/certs/cacert.pem"
openssl.cafile="/Applications/AMPPS/extra/etc/openssl/certs/cacert.pem"
And applied same setting in windows AMPPS installation and it worked perfectly in it too.
[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo="C:/Ampps/php/extras/ssl/cacert.pem"
openssl.cafile="C:/Ampps/php/extras/ssl/cacert.pem"
: Same for wamp.
[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo="C:/wamp/bin/php/php5.6.16/extras/ssl/cacert.pem"
openssl.cafile="C:/wamp/bin/php/php5.6.16/extras/ssl/cacert.pem"
If you are looking for generating new SSL certificate using SAN for localhost, steps on this post worked for me on Centos 7 / Vagrant / Chrome Browser
.
Use the download attribute.
var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
quit()
: Quits this driver, closing every associated window that was open.
close()
: Close the current window, quitting the browser if it's the last window currently open.
I use it everywhere. On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.
I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.
My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:
<IfModule mod_rewrite.c>
# Turn on URL rewriting
RewriteEngine On
# If your website begins from a folder e.g localhost/my_project then
# you have to change it to: RewriteBase /my_project/
# If your site begins from the root e.g. example.local/ then
# let it as it is
RewriteBase /
# Protect application and system files from being viewed when the index.php is missing
RewriteCond $1 ^(application|system|private|logs)
# Rewrite to index.php/access_denied/URL
RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]
# Allow these directories and files to be displayed directly:
RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)
# No rewriting
RewriteRule ^(.*)$ - [PT,L]
# Rewrite to index.php/URL
RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>
Simply use title in tag like
<i class="fa fa-edit" title="Edit Mode"></i>
This will show 'Edit Mode' when hover that icon.
It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.
If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.
from the sendmail manpage :
-f <address>
This option sets the address of the envelope sender of a
locally-generated message (also known as the return path).
The option can normally be used only by a trusted user, but
untrusted_set_sender can be set to allow untrusted users to
use it. [...]
You can always disable the use of pre-compiled headers in the project settings.
Instructions for VS 2010 (should be similar for other versions of VS):
Select your project, use the "Project -> Properties" menu and go to the "Configuration Properties -> C/C++ -> Precompiled Headers" section, then change the "Precompiled Header" setting to "Not Using Precompiled Headers" option.
If you are only trying to setup a minimal Visual Studio project for simple C++ command-line programs (such as those developed in introductory C++ programming classes), you can create an empty C++ project.
Here is an example code
import unicodedata
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
The unique name identifier applies to radio buttons:
<input type="radio" />
change your checkboxes to radio and everything should be working
You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:
<?php
$filename = $_GET['file'];
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
exit;
} elseif ( ! file_exists( $filename ) )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
exit;
};
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
None of these solutions worked for me. I had to uninstall Android Studio all together, then remove all Android Studio related files (user files), then reinstall it again.
Adding to t3chb0t's excellent answer - Use these PowerShell commands to install all VSCode extensions in a folder:
cd C:\PathToFolderWithManyDownloadedExtensionFiles
Get-ChildItem . -Filter *.vsix | ForEach-Object { code --install-extension $_.FullName }
Then, reload VSCode to complete the installation.
It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15
I have 3 spinners
Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);
And also I have a Async-Tack class.
Here is my spinner loading code
RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();
RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();
RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();
This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.
Here is my Async-task class
public class RequestSend extends AsyncTask<String, String, String > {
private ProgressDialog dialog = null;
public Spinner spin;
public String where;
public String title;
Context con;
Activity activity;
String[] items;
public RequestSend(Context activityContext) {
con = activityContext;
dialog = new ProgressDialog(activityContext);
this.activity = activityContext;
}
@Override
protected void onPostExecute(String result) {
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
} catch (NullPointerException e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle(title);
dialog.setMessage("Wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... Strings) {
try {
Send_Request();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void Send_Request() throws JSONException {
try {
String DataSendingTo = "http://www.example.com/AppRequest/" + where;
//HttpClient
HttpClient httpClient = new DefaultHttpClient();
//Post header
HttpPost httpPost = new HttpPost(DataSendingTo);
//Adding data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("authorized","001"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line) ;
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
items = new String[finalResult.length()];
// looping through All details and store in public String array
for(int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
items[i]=c.getString("data_name");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I know this is kind of old question, but I thought maybe someone like my trick. Especially since this solution not limited to a specific number of items.
# Convert to an array
_ITEMS=($(echo "12|23|11" | tr '|' '\n'))
# Output array items
for _ITEM in "${_ITEMS[@]}"; do
echo "Item: ${_ITEM}"
done
The output will be:
Item: 12
Item: 23
Item: 11
Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
And, your client code should look like this:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
FWIW the removal of Apache library was foreshadowed a while ago. Our good friend Jesse Wilson gave us a clue back in 2011: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Google stopped working on ApacheHTTPClient a while ago, so any library that is still relying upon that should be put onto the list of deprecated libraries unless the maintainers update their code.
<rant>
I can't tell you how many technical arguments I've had with people who insisted on sticking with Apache HTTP client. There are some major apps that are going to break because management at my not-to-be-named previous employers didn't listen to their top engineers or knew what they were talking about when they ignored the warning ... but, water under the bridge.
I win.
</rant>
Try this
#dimScreen {
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0;
left: 0;
}
after looking at some other threads I came up with this solution to add icons to the buttons in a confirm dialog, which seems to work well in version 1.8.1 and can be modified to do other styling:
$("#confirmBox").dialog({
modal:true,
autoOpen:false,
buttons: {
"Save": function() { ... },
"Cancel": function() { ... }
}
});
var buttons = $('.ui-dialog-buttonpane').children('button');
buttons.removeClass('ui-button-text-only').addClass('ui-button-text-icon');
$(buttons[0]).append("<span class='ui-icon ui-icon-check'></span>");
$(buttons[1]).append("<span class='ui-icon ui-icon-close'></span>");
I'd be interested in seeing if there was a better way to do it, but this seems pretty efficient.
in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().
$filedate = date_create(date("Y-m-d", filectime($file)));
becomes
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
that worked for me.
Complete snippet for deleting files by number of days:
$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
$extension = substr($file, -3, 3);
if ($extension == 'jpg') // in case you only want specific files deleted
{
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
$today = date_create(date("Y-m-d"));
$days = date_diff($filedate, $today, true);
if ($days->days > 1)
{
unlink($directory.$file);
}
}
}
The below command worked for me
sudo service postgresql restart
You can keep note of below possibilities:
null
.However with multiple null
keys and values it will only take a null key value pair once.
Map<String, String> codes = new HashMap<String, String>();
codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");
for(String key:codes.keySet()){
System.out.println(key);
System.out.println(codes.get(key));
}
output will be :
null //key of the 1st entry
null //value of 1st entry
C1
Acathan
null
only onceoptions.put(null, null);
Person person = sample.searchPerson(null);
It depends on the implementation of your searchPerson
method
if you want multiple values to be null
, you can implement accordingly
Map<String, String> codes = new HashMap<String, String>();
codes.put(null, null);
codes.put("X1",null);
codes.put("C1", "Acathan");
codes.put("S1",null);
for(String key:codes.keySet()){
System.out.println(key);
System.out.println(codes.get(key));
}
output:
null
null
X1
null
S1
null
C1
Acathan
Starting at Python 3.3 it is straight forward: https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal
>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80
This is what I have done. (Adapt from all of your answers)
<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />
It works. Thanks to all of you. :)
For Rails 5.2.4.1, I had to
app.extend app._routes.named_routes.path_helpers_module
app.whatever_path
I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.
Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.
Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:
$('iframe_dl').src="/app?download=1&filename=" + the_filename
Server slurps the file, unlinks it, and sends the stream to the client, with these headers:
Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'
Works like a charm.
Just another way of doing it.
[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]
You can do this to only monitor own properties of the object:
var arr = [];
for (var key in p) {
if (p.hasOwnProperty(key)) {
arr.push(p[key]);
}
}
Semantically what you are trying is invalid html, table
element cannot have a div
element as a direct child. What you can do is, get your div
element inside a td
element and than try to hide it
A sed
script that will only replace the first occurrence of "Apple" by "Banana"
Example
Input: Output:
Apple Banana
Apple Apple
Orange Orange
Apple Apple
This is the simple script: Editor's note: works with GNU sed
only.
sed '0,/Apple/{s/Apple/Banana/}' input_filename
The first two parameters 0
and /Apple/
are the range specifier. The s/Apple/Banana/
is what is executed within that range. So in this case "within the range of the beginning (0
) up to the first instance of Apple
, replace Apple
with Banana
. Only the first Apple
will be replaced.
Background: In traditional sed
the range specifier is also "begin here" and "end here" (inclusive). However the lowest "begin" is the first line (line 1), and if the "end here" is a regex, then it is only attempted to match against on the next line after "begin", so the earliest possible end is line 2. So since range is inclusive, smallest possible range is "2 lines" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU
sed adds its own extension of allowing specifying start as the "pseudo" line 0
so that the end of the range can be line 1
, allowing it a range of "only the first line" if the regex matches the first line.
Or a simplified version (an empty RE like //
means to re-use the one specified before it, so this is equivalent):
sed '0,/Apple/{s//Banana/}' input_filename
And the curly braces are optional for the s
command, so this is also equivalent:
sed '0,/Apple/s//Banana/' input_filename
All of these work on GNU sed
only.
You can also install GNU sed on OS X using homebrew brew install gnu-sed
.
Do this:
function changeHeight() { document.getElementById('chartdiv').style.height = "200px" } <button type="button" onClick="changeHeight();"> Click Me!</button>
A copy of System.Management.Automation.dll is installed when you install the windows SDK (a suitable, recent version of it, anyway). It should be in C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\
From grep --help
, but also see man grep:
Exit status is 0 if any line was selected, 1 otherwise; if any error occurs and -q was not given, the exit status is 2.
if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
echo exists
else
echo not found
fi
You may want to use a more specific regex, such as ^MYSQL_ROLE=master$
, to avoid that string in comments, names that merely start with "master", etc.
This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.
For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccess
but this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error
. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.
I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css
,js
and php
files even more like images
or whatever you have.
You can use the @helper Razor directive:
@helper WelcomeMessage(string username)
{
<p>Welcome, @username.</p>
}
Then you invoke it like this:
@WelcomeMessage("John Smith")
I have implemented MultipartReader NuGet package for ASP.NET 4 for reading multipart form data. It is based on Multipart Form Data Parser, but it supports more than one file.
An updated visual for those wanting to compare some of the recent answers (I wanted to compare the purrr to dplyr solution). Basically I combined answers from @TheVTM and @rmf.
Code:
library(microbenchmark)
library(data.table)
library(tidyverse)
dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
c=rep(LETTERS,10),d=rep(LETTERS,10))
}
mb <- microbenchmark(
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
purrr::map_df(dflist, bind_rows),
do.call("rbind",dflist),
times=500)
ggplot2::autoplot(mb)
Session Info:
sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Package Versions:
> packageVersion("tidyverse")
[1] ‘1.1.1’
> packageVersion("data.table")
[1] ‘1.10.0’
you can create user with name web2vi
and grant all privilage
You can do this with a single grep instruction, using Perl mode and \K
to reset the match buffer, so you get only the branch name.
$ git branch | grep -oP "^\*\s+\K\S+$"
master
You don't appear to have write permission to the /tmp
directory on your server. This is a bit weird, but you can work around it. Before the call to session_start()
put in a call to session_save_path()
and give it the name of a directory writable by the server. Details are here.
In my case I was missing new
inside the type definition.
some-js-component.d.ts
file:
import * as React from "react";
export default class SomeJSXComponent extends React.Component<any, any> {
new (props: any, context?: any)
}
and inside the tsx
file where I was trying to import the untyped component:
import SomeJSXComponent from 'some-js-component'
const NewComp = ({ asdf }: NewProps) => <SomeJSXComponent withProps={asdf} />
Before doing that Download Node Js 8.11.3 from the URL: download
Open command prompt and run this:
npm install -g [email protected]
use this version this is the stable version which works along with cordova 7.1.0
for installing cordova use : • npm install -g [email protected]
• Run command
• Cordova platform remove android (if you have old android code or code is having some issue)
• Cordova platform add android : for building android app in cordova Running: Corodva run android
lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
None of the above solutions worked for me on Windows 8
But the following command works fine
SHIFT + Q
For those of you looking for unicode alphanumeric matching, you might want to do something like:
^[\p{L} \p{Nd}_]+$
Further reading at http://unicode.org/reports/tr18/ and at http://www.regular-expressions.info/unicode.html
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
As an addition to LukeP code for Web Forms users (not MVC) if you want to simplify the access in the code behind of your pages, just add the code below to a base page and derive the base page in all your pages:
Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
Get
Return DirectCast(MyBase.User, CustomPrincipal)
End Get
End Property
So in your code behind you can simply access:
User.FirstName or User.LastName
What I'm missing in a Web Form scenario, is how to obtain the same behaviour in code not tied to the page, for example in httpmodules should I always add a cast in each class or is there a smarter way to obtain this?
Thanks for your answers and thank to LukeP since I used your examples as a base for my custom user (which now has User.Roles
, User.Tasks
, User.HasPath(int)
, User.Settings.Timeout
and many other nice things)
Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
My solution using standard <ul>
and <i>
inside <li>
<ul>
<li><i class="fab fa-cc-paypal"></i> <div>Paypal</div></li>
<li><i class="fab fa-cc-apple-pay"></i> <div>Apple Pay</div></li>
<li><i class="fab fa-cc-stripe"></i> <div>Stripe</div></li>
<li><i class="fab fa-cc-visa"></i> <div>VISA</div></li>
</ul>
ES8 way made easy:
const obj = { x: 'xxx', y: 1 };_x000D_
let arr = Object.values(obj); // ['xxx', 1]_x000D_
console.log(arr);
_x000D_