Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.
C:\Windows\SysWOW64>regsvr32 "c:\dll.name"
I've been using ant32's answer above for several years. However I've found that is thorws an error in python 3 because mogrify
returns a byte string.
Converting explicitly to bytse strings is a simple solution for making code python 3 compatible.
args_str = b','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute(b"INSERT INTO table VALUES " + args_str)
First of all create colors for selected item. Here https://stackoverflow.com/a/30594875/1462969 good example. It helps you to change color of icon. For changing background of all selected item add in your values\style.xml file this
<item name="selectableItemBackground">@drawable/selectable_item_background</item>
Where selectable_item_background should be declared in drawable/selectable_item_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/accent_translucent"
android:state_pressed="true" />
<item android:drawable="@android:color/transparent" />
</selector>
Where color can be declared in style.xml
<color name="accent_translucent">#80FFEB3B</color>
And after this
// The main navigation menu with user-specific actions
mainNavigationMenu_ = (NavigationView) findViewById(R.id.main_drawer);
mainNavigationMenu_.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mainNavigationMenu_.getMenu().findItem(itemId).setChecked(true);
return true;
}
});
As you see I used this mainNavigationMenu_.getMenu().findItem(itemId).setChecked(true); to set selected item. Here navigationView
<android.support.design.widget.NavigationView
android:id="@+id/main_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/header_main_navigation_menu"
app:itemIconTint="@color/state_list"
app:itemTextColor="@color/primary"
app:menu="@menu/main_menu_drawer"/>
You might take a look at this:
https://github.com/michaelmoussa/ng-boolean-radio/
This guy wrote a custom directive to get around the issue that "true" and "false" are strings, not booleans.
Firstly, in general:
If these .h
files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h
extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.
Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.
Basically, compiling hello.h
as a standalone translation unit equivalent to creating a degenerate dummy.c
file consisting only of #include "hello.h"
directive, and feeding that dummy.c
file to the compiler. It will compile, but it will serve no meaningful purpose.
Secondly, specifically for GCC:
Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h
extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h
file.
You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html
So, this is the reason you might see .h
files being fed directly to GCC.
Go to %appdata%\Notepad++ folder.
The macro definitions are held in shortcuts.xml inside the <Macros>
tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.
it doenst work for me but it prints the correct element to the console
this is the code:
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
console.log(el); //print element to console
el.dispatchEvent(ev);
}
click(400, 400);
For those still looking how to get GatesDa's answer to work: You can just reference the case object after declaring it to instantiate it:
trait Enum[A] {
trait Value { self: A =>
_values :+= this
}
private var _values = List.empty[A]
def values = _values
}
sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
case object EUR extends Currency;
EUR //THIS IS ONLY CHANGE
case object GBP extends Currency; GBP //Inline looks better
}
How to use in
or out
or ref
in C#?
C#
have the same functionality but with some boundaries.in
arguments cannot be modified by the called method.ref
arguments may be modified.ref
must be initialized before being used by caller it can be read and updated in the method.out
arguments must be modified by the caller.out
arguments must be initialized in the methodin
arguments must be initialized before being passed in a method call. However, the called method may not assign a value or modify the argument.You can't use the in
, ref
, and out
keywords for the following kinds of methods:
async
modifier.yield return
or yield break
statement.For Unit Tests, the System variable is not instantiated yet when I do "mvn clean install" because there is no server running the application. So in order to set the System properties, I need to do it in pom.xml. Like so:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
<configuration>
<systemPropertyVariables>
<propertyName>propertyValue</propertyName>
<MY_ENV_VAR>newValue</MY_ENV_VAR>
<ENV_TARGET>olqa</ENV_TARGET>
<buildDirectory>${project.build.directory}</buildDirectory>
</systemPropertyVariables>
</configuration>
</plugin>
To capitalize, you can do the following with edit text:
To make first letter capital of every word:
android:inputType="textCapWords"
To make first letter capital of every sentence:
android:inputType="textCapSentences"
To make every letter capital:
android:inputType="textCapCharacters"
But this will only make changes to keyboard and user can change the mode to write letter in small case.
So this approach is not much appreciated if you really want the data in capitalize format, add following class first:
public class CapitalizeFirstLetter {
public static String capitaliseName(String name) {
String collect[] = name.split(" ");
String returnName = "";
for (int i = 0; i < collect.length; i++) {
collect[i] = collect[i].trim().toLowerCase();
if (collect[i].isEmpty() == false) {
returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
}
}
return returnName.trim();
}
public static String capitaliseOnlyFirstLetter(String data)
{
return data.substring(0,1).toUpperCase()+data.substring(1);
}
}
And then,
Now to capitalize every word:
CapitalizeFirstLetter.capitaliseName(name);
To capitalize only first word:
CapitalizeFirstLetter.capitaliseOnlyFirstLetter(data);
This works in browser and nodejs Live browser demo
const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
const chain = cpFetch(url, {timeout: 10000})
.then(response => response.json())
.then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms
Ruby provides a built-in function for checking the length of a string. Say it's called s
:
if s.length <= 25
# We're OK
else
# Too long
end
Loading the file from: {project}/src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml" })
@WebAppConfiguration
public class TestClass {
@Test
public void test() {
// test definition here..
}
}
Here is a complete solution(returns 0 if number is overflown):
public int reverse(int x) {
boolean flag = false;
// Helpful to check if int is within range of "int"
long num = x;
// if the number is negative then turn the flag on.
if(x < 0) {
flag = true;
num = 0 - num;
}
// used for the result.
long result = 0;
// continue dividing till number is greater than 0
while(num > 0) {
result = result*10 + num%10;
num= num/10;
}
if(flag) {
result = 0 - result;
}
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
}
return (int) result;
}
You can query the all_tab_columns
view in the database.
SELECT table_name, column_name, data_type, data_length FROM all_tab_columns where table_name = 'CUSTOMER'
You could also just run
go build
in your project folder myproject/go/src/myprog
Then you can just type
./myprog
to run your app
Depending on what you want you might be interested in the SPL Object Storage class.
http://php.net/manual/en/class.splobjectstorage.php
It lets you use objects as keys, has an interface to count, get the hash and other goodies.
$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';
$s[$o1] = 'baz';
$s[$o2] = 'bingo';
echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'
Here is a simple way that looks good in any L&F:
public class HintTextField extends JTextField {
public HintTextField(String hint) {
_hint = hint;
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (getText().length() == 0) {
int h = getHeight();
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Insets ins = getInsets();
FontMetrics fm = g.getFontMetrics();
int c0 = getBackground().getRGB();
int c1 = getForeground().getRGB();
int m = 0xfefefefe;
int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1);
g.setColor(new Color(c2, true));
g.drawString(_hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);
}
}
private final String _hint;
}
I was receiving the same error when not specifying the app
name before pattern name.
In my case:
app-name
: Blog
pattern-name
: post-delete
reverse_lazy('Blog:post-delete')
worked.
You can pass small bits of key/value pair data via the query string:
res.redirect('/?error=denied');
And javascript on the home page can access that and adjust its behavior accordingly.
Note that if you don't mind /category
staying as the URL in the browser address bar, you can just render directly instead of redirecting. IMHO many times people use redirects because older web frameworks made directly responding difficult, but it's easy in express:
app.post('/category', function(req, res) {
// Process the data received in req.body
res.render('home.jade', {error: 'denied'});
});
As @Dropped.on.Caprica commented, using AJAX eliminates the URL changing concern.
Unfortunately, as far as I know, the requests library is not equipped for performing asynchronous requests. You can wrap async/await
syntax around requests
, but that will make the underlying requests no less synchronous. If you want true async requests, you must use other tooling that provides it. One such solution is aiohttp
(Python 3.5.3+). It works well in my experience using it with the Python 3.7 async/await
syntax. Below I write three implementations of performing n web requests using
sync_requests_get_all
) using the Python requests
libraryasync_requests_get_all
) using the Python requests
library wrapped in Python 3.7 async/await
syntax and asyncio
async_aiohttp_get_all
) with the Python aiohttp
library wrapped in Python 3.7 async/await
syntax and asyncio
import time
import asyncio
import requests
import aiohttp
from types import SimpleNamespace
durations = []
def timed(func):
"""
records approximate durations of function calls
"""
def wrapper(*args, **kwargs):
start = time.time()
print(f'{func.__name__:<30} started')
result = func(*args, **kwargs)
duration = f'{func.__name__:<30} finished in {time.time() - start:.2f} seconds'
print(duration)
durations.append(duration)
return result
return wrapper
async def fetch(url, session):
"""
asynchronous get request
"""
async with session.get(url) as response:
response_json = await response.json()
return SimpleNamespace(**response_json)
async def fetch_many(loop, urls):
"""
many asynchronous get requests, gathered
"""
async with aiohttp.ClientSession() as session:
tasks = [loop.create_task(fetch(url, session)) for url in urls]
return await asyncio.gather(*tasks)
@timed
def sync_requests_get_all(urls):
"""
performs synchronous get requests
"""
# use session to reduce network overhead
session = requests.Session()
return [SimpleNamespace(**session.get(url).json()) for url in urls]
@timed
def async_requests_get_all(urls):
"""
asynchronous wrapper around synchronous requests
"""
loop = asyncio.get_event_loop()
# use session to reduce network overhead
session = requests.Session()
async def async_get(url):
return session.get(url)
async_tasks = [loop.create_task(async_get(url)) for url in urls]
return loop.run_until_complete(asyncio.gather(*async_tasks))
@timed
def asnyc_aiohttp_get_all(urls):
"""
performs asynchronous get requests
"""
loop = asyncio.get_event_loop()
return loop.run_until_complete(fetch_many(loop, urls))
if __name__ == '__main__':
# this endpoint takes ~3 seconds to respond,
# so a purely synchronous implementation should take
# little more than 30 seconds and a purely asynchronous
# implementation should take little more than 3 seconds.
urls = ['https://postman-echo.com/delay/3']*10
sync_requests_get_all(urls)
async_requests_get_all(urls)
asnyc_aiohttp_get_all(urls)
print('----------------------')
[print(duration) for duration in durations]
On my machine, this is the output:
sync_requests_get_all started
sync_requests_get_all finished in 30.92 seconds
async_requests_get_all started
async_requests_get_all finished in 30.87 seconds
asnyc_aiohttp_get_all started
asnyc_aiohttp_get_all finished in 3.22 seconds
----------------------
sync_requests_get_all finished in 30.92 seconds
async_requests_get_all finished in 30.87 seconds
asnyc_aiohttp_get_all finished in 3.22 seconds
You can use the following 3 ways to create ArrayList from Array.
String[] array = {"a", "b", "c", "d", "e"};
//Method 1
List<String> list = Arrays.asList(array);
//Method 2
List<String> list1 = new ArrayList<String>();
Collections.addAll(list1, array);
//Method 3
List<String> list2 = new ArrayList<String>();
for(String text:array) {
list2.add(text);
}
using sklearn library preprocessing class
from sklearn.impute import SimpleImputer
missingvalues = SimpleImputer(missing_values = np.nan, strategy = 'mean', axis = 0)
missingvalues = missingvalues.fit(x[:,1:3])
x[:,1:3] = missingvalues.transform(x[:,1:3])
Note: In the recent version parameter missing_values
value change to np.nan
from NaN
If you want to use global variable i of file1.c in file2.c, then below are the points to remember:
This gives you the needed results:
string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM" string
You could also use CultureInfo.CreateSpecificCulture("en-US")
as not all cultures will display AM/PM.
You can use File.WriteAllBytes
What helped me was that I created a separate NSCharacterSet
and used it on an UTF-8 encoded string i.e. textToEncode to generate the required result:
var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&?,:;@+=$*()")
let utfedCharacterSet = String(utf8String: textToEncode.cString(using: .utf8)!)!
let encodedStr = utfedCharacterSet.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
let paramUrl = "https://api.abc.eu/api/search?device=true&query=\(escapedStr)"
This is how I add css using jQuery ajax. Hope it helps someone..
$.ajax({
url:"site/test/style.css",
success:function(data){
$("<style></style>").appendTo("head").html(data);
}
})
Though this question is meanwhile closed, I believe it is worth mentioning how this atrocity came into existence. In a way, you may blame the C# spec, which states that a double must have a precision of 15 or 16 digits (the result of IEEE-754). A bit further on (section 4.1.6) it's stated that implementations are allowed to use higher precision. Mind you: higher, not lower. They are even allowed to deviate from IEEE-754: expressions of the type x * y / z
where x * y
would yield +/-INF
but would be in a valid range after dividing, do not have to result in an error. This feature makes it easier for compilers to use higher precision in architectures where that'd yield better performance.
But I promised a "reason". Here's a quote (you requested a resource in one of your recent comments) from the Shared Source CLI, in clr/src/vm/comnumber.cpp
:
"In order to give numbers that are both friendly to display and round-trippable, we parse the number using 15 digits and then determine if it round trips to the same value. If it does, we convert that NUMBER to a string, otherwise we reparse using 17 digits and display that."
In other words: MS's CLI Development Team decided to be both round-trippable and show pretty values that aren't such a pain to read. Good or bad? I'd wish for an opt-in or opt-out.
The trick it does to find out this round-trippability of any given number? Conversion to a generic NUMBER structure (which has separate fields for the properties of a double) and back, and then compare whether the result is different. If it is different, the exact value is used (as in your middle value with 6.9 - i
) if it is the same, the "pretty value" is used.
As you already remarked in a comment to Andyp, 6.90...00
is bitwise equal to 6.89...9467
. And now you know why 0.0...8818
is used: it is bitwise different from 0.0
.
This 15 digits barrier is hard-coded and can only be changed by recompiling the CLI, by using Mono or by calling Microsoft and convincing them to add an option to print full "precision" (it is not really precision, but by the lack of a better word). It's probably easier to just calculate the 52 bits precision yourself or use the library mentioned earlier.
EDIT: if you like to experiment yourself with IEE-754 floating points, consider this online tool, which shows you all relevant parts of a floating point.
Try this....
ul.list-group li {
padding-left: 13px;
position: relative;
}
ul.list-group li:before {
left: 0 !important;
position: absolute;
}
You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.
Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.
"Cannot have multiple items selected in a DropDownList"
If a dedicated script seems like too much overhead, you can spawn separate processes explicitly with sh -c
. For example:
CMD sh -c 'mini_httpd -C /my/config -D &' \
&& ./content_computing_loop
class Rectangle : public Area<int> {
};
ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send
Um... your minutes should be corrected... 'i' is for minutes. Not months. :) (I had the same problem for something too.
$now = date("Y-m-d H:i:s");
$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours
Well, most convenient and safest way is to use JBoss update site within Eclipse software updates (Help -> Software Updates... -> Add Site...):
The latest stable release update site for JBoss Tools
There you can find Hibernate tools together with other handy JBoss plugins.
Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print item
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']
I'm not super fond of the interval thingies. When I want to defer jquery, or anything actually, it usually goes something like this.
Start with:
<html>
<head>
<script>var $d=[];var $=(n)=>{$d.push(n)}</script>
</head>
Then:
<body>
<div id="thediv"></div>
<script>
$(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
Then finally:
<script>for(var f in $d){$d[f]();}</script>
</body>
<html>
Or the less mind-boggling version:
<script>var def=[];function defer(n){def.push(n)}</script>
<script>
defer(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>for(var f in def){def[f]();}</script>
And in the case of async you could execute the pushed functions on jquery onload.
<script async onload="for(var f in def){def[f]();}"
src="jquery.min.js" type="text/javascript"></script>
Alternatively:
function loadscript(src, callback){
var script = document.createElement('script');
script.src = src
script.async = true;
script.onload = callback;
document.body.appendChild(script);
};
loadscript("jquery.min", function(){for(var f in def){def[f]();}});
Free read-only viewers:
tail
." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.Free editors:
Builtin programs (no installation required):
MORE
, not the Unix more
. A console program that allows you to view a file, one screen at a time.Web viewers:
Paid editors:
The ternary operator ? :
is to return a value, don't use it when you want to use if
for flow control.
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
would work good enough.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.
The default iterator for the JObject is as a dictionary iterating over key/value pairs.
JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
Just a note of a peculiarity I faced:
Consider:
db server: 192.168.0.101
web server: 192.168.0.102
If you have a user defined in mysql.user as 'user'@'192.168.0.102'
with password1 and another 'user'@'192.168.0.%'
with password2,
then,
if you try to connect to the db server from the web server as 'user' with password2,
it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102'
authentication is used over the wildcard 'user'@'192.168.0.%'
authentication.
If I understand correctly, something has already sent out from header.php (maybe some HTML) so the headers have been set. You may need to recheck your header.php file for any part that may output HTML or spaces before your first
EDIT: I am now sure that it is caused from header.php since you have those HTML output. You can fix this by remove the "include('header.php');" line and copy the following code to your file instead.
include('class.user.php');
include('class.Connection.php');
$date = date('Y-m-j');
To write a byte array to a file use the method
public void write(byte[] b) throws IOException
from BufferedOutputStream class.
java.io.BufferedOutputStream implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.
For your example you need something like:
String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
bos.write(encoded);
}
// catch and handle exceptions...
SELECT
B.Title, B.Edition, B.Year, B.Pages, B.Rating --from Books
, C.Category --from Categories
, P.Publisher --from Publishers
, W.LastName --from Writers
FROM Books B
JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID
When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.
If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.
Dim returnVal As Variant
returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")
'if the user clicked Cancel, Close or Esc the False
'is translated to the variant as a vbNullString
Select Case True
Case Len(returnVal) = 0
'no value but user clicked OK - clear the target cell
Range("A2").ClearContents
Case Else
'returned a value with OK, save it
Range("A2") = returnVal
End Select
¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.
Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.
You should generally use urllib2, since this makes things a bit easier at times by accepting Request objects and will also raise a URLException on protocol errors. With Google App Engine though, you can't use either. You have to use the URL Fetch API that Google provides in its sandboxed Python environment.
this happened to me a few days ago. I did a fresh installation and it still happened. as far as everyone sees and based on your server specs. most likely it is an infinite loop. it could be not on the PHP code itself but on the requests made to Apache.
lets say when you access this url http://localhost/mysite/page_with_multiple_requests
Check your Apache's access log if it receives multiple requests. trace that request and check out the code that might cause a 'bottleneck' to the system (mine's exec() when using sendmail). The bottleneck im talking about doesn't need to be an 'infinite loop'. It could be a function that takes sometime to finish. or maybe some of php's 'program execution functions'
You might need to check ajax requests too (the ones that execute when the page loads). if that ajax request redirects to the same url
e.g. httpx://localhost/mysite/page_with_multiple_requests
it would 'redo' the requests all over again
it would help if you post the random lines or the code itself where the script ends maybe there is a 'loop' code somewhere there. imho php won't just call random lines for nothing.
http://blog.piratelufi.com/2012/08/browser-sending-multiple-requests-at-once/
set.seed
is a base function that it is able to generate (every time you want) together other functions (rnorm
, runif
, sample
) the same random value.
Below an example without set.seed
> set.seed(NULL)
> rnorm(5)
[1] 1.5982677 -2.2572974 2.3057461 0.5935456 0.1143519
> rnorm(5)
[1] 0.15135371 0.20266228 0.95084266 0.09319339 -1.11049182
> set.seed(NULL)
> runif(5)
[1] 0.05697712 0.31892399 0.92547023 0.88360393 0.90015169
> runif(5)
[1] 0.09374559 0.64406494 0.65817582 0.30179009 0.19760375
> set.seed(NULL)
> sample(5)
[1] 5 4 3 1 2
> sample(5)
[1] 2 1 5 4 3
Below an example with set.seed
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
You have to install MongoDB
database server first in your system and start it.
Use the below link to install MongoDB
I am using Visual Studio 2017 15.4.0 version. Especially when i started use lightweight solution option, this offline thing happened to me. I tried to above solutions which are:
Then from File -> Source Control -> Advanced -> Change Source Control. I saw my files. I select them and then chose bind option. That worked for me.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript"><!--
function getVal(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
alert(targ.innerHTML);
}
onload = function() {
var t = document.getElementById("main").getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
</script>
<body>
<table id="main"><tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr><tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr><tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr></table>
</body>
</html>
Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
Even at the time of this question, over 3 years ago, Sage (which is completely free) existed and was pretty good at graph theory. But, in 2012 it is about the best graph theory tool there is. Thus, Sage already has a huge amount of graph theory material built in, including other free and open source stuff that is out there. So, simply messing around with various things to learn more is easy as no programming is required.
And, if you are interested in the programming part as well, first Sage is open source so you can see any code that already exists. And, second, you can re-program any function you want if you really want to practice, or you can be the first to program something that does not already exist. In the latter case, you can even submit that new functionality and make Sage better for all other users.
At this time, this answer may not be that useful to the OP (since it has been 3 years), but hopefully it is useful to any one else who sees this question in the future.
Use ng-submit and just wrap both inputs in separate form tags:
<div ng-controller="mycontroller">
<form ng-submit="myFunc()">
<input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
</form>
<br />
<form ng-submit="myFunc()">
<input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
</form>
</div>
Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.
Look at the following commands (especially the commented block).
DROP TABLE foo;
DROP TABLE bar;
CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);
INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;
-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a; -- 8.2 or later
SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5); -- replace 5 by SELECT MAX result
INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');
SELECT * FROM foo;
SELECT * FROM bar;
Both the answers provided above work fine.
If you want to just label the data points above the bar, you could use plt.annotate()
My code:
import numpy as np
import matplotlib.pyplot as plt
n = [1,2,3,4,5,]
s = [i**2 for i in n]
line = plt.bar(n,s)
plt.xlabel('Number')
plt.ylabel("Square")
for i in range(len(s)):
plt.annotate(str(s[i]), xy=(n[i],s[i]), ha='center', va='bottom')
plt.show()
By specifying a horizontal and vertical alignment of 'center'
and 'bottom'
respectively one can get centered annotations.
You can also override the deployment repository on the command line:
-Darguments=-DaltDeploymentRepository=myreposid::default::http://my/url/releases
Lifecycle hooks, like OnInit()
work with Directives and Components. They do not work with other types, like a service in your case. From docs:
A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.
I will break answer on three paragraphs.
Part 1:
git stash
(To save your un-committed changes in a "stash". Note: this removes changes from working tree!)
git checkout some_branch
(change to intended branch -- in this case some_branch
)
git stash list
(list stashes)
You can see:
stash@{0}: WIP on {branch_name}: {SHA-1 of last commit} {last commit of you branch}
stash@{0}: WIP on master: 085b095c6 modification for test
git stash apply
(to apply stash to working tree in current branch)
git stash apply stash@{12}
(if you will have many stashes you can choose what stash will apply -- in this case we apply stash 12
)
git stash drop stash@{0}
(to remove from stash list -- in this case stash 0
)
git stash pop stash@{1}
(to apply selected stash and drop it from stash list)
Part 2:
You can hide your changes with this command but it is not necessary.
You can continue on the next day without stash.
This commands for hide your changes and work on different branches or for implementation some realisation of your code and save in stashes without branches and commitsor your custom case!
And later you can use some of stashes and check wich is better.
Part 3:
Stash command for local hide your changes.
If you want work remotely you must commit and push.
Pymongo 3.9+
update()
is now deprecated and you should use replace_one()
, update_one()
, or update_many()
instead.
In my case I used update_many()
and it solved my issue:
db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)
From documents
update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None) filter: A query that matches the documents to update. update: The modifications to apply. upsert (optional): If True, perform an insert if no documents match the filter. bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False. collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above. array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+. session (optional): a ClientSession.
The standard Python library module random has what you want:
normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.
For the algorithm itself, take a look at the function in random.py in the Python library.
In Python, how do you get the last element of a list?
To just get the last element,
pass -1
to the subscript notation:
>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'
Indexes and slices can take negative integers as arguments.
I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python"
, -1
references the last element, the character, 'n'
:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
>>> p = 'Python'
>>> p[-1]
'n'
This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable - not just lists):
>>> *head, last = a_list
>>> last
'three'
The variable name, head is bound to the unnecessary newly created list:
>>> head
['zero', 'one', 'two']
If you intend to do nothing with that list, this would be more apropos:
*_, last = a_list
Or, really, if you know it's a list (or at least accepts subscript notation):
last = a_list[-1]
A commenter said:
I wish Python had a function for first() and last() like Lisp does... it would get rid of a lot of unnecessary lambda functions.
These would be quite simple to define:
def last(a_list):
return a_list[-1]
def first(a_list):
return a_list[0]
Or use operator.itemgetter
:
>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)
In either case:
>>> last(a_list)
'three'
>>> first(a_list)
'zero'
If you're doing something more complicated, you may find it more performant to get the last element in slightly different ways.
If you're new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.
I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I'm leaving a caveat out.
A slice of a list returns a new list - so we can slice from -1 to the end if we are going to want the element in a new list:
>>> a_slice = a_list[-1:]
>>> a_slice
['three']
This has the upside of not failing if the list is empty:
>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
... do_something(tail)
Whereas attempting to access by index raises an IndexError
which would need to be handled:
>>> empty_list[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
But again, slicing for this purpose should only be done if you need:
for
loopsAs a feature of Python, there is no inner scoping in a for
loop.
If you're performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:
>>> def do_something(arg): pass
>>> for item in a_list:
... do_something(item)
...
>>> item
'three'
This is not semantically the last thing in the list. This is semantically the last thing that the name, item
, was bound to.
>>> def do_something(arg): raise Exception
>>> for item in a_list:
... do_something(item)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'
Thus this should only be used to get the last element if you
We can also mutate our original list by removing and returning the last element:
>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']
But now the original list is modified.
(-1
is actually the default argument, so list.pop
can be used without an index argument):
>>> a_list.pop()
'two'
Only do this if
These are valid use-cases, but not very common.
I don't know why you'd do it, but for completeness, since reversed
returns an iterator (which supports the iterator protocol) you can pass its result to next
:
>>> next(reversed([1,2,3]))
3
So it's like doing the reverse of this:
>>> next(iter([1,2,3]))
1
But I can't think of a good reason to do this, unless you'll need the rest of the reverse iterator later, which would probably look more like this:
reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)
use_later = list(reverse_iterator)
and now:
>>> use_later
[2, 1]
>>> last_element
3
The current accepted answer by crack is deprecated in Symfony 2.3 and will be removed by 3.0. It should be moved to the constructor:
public function __construct($environment, $debug) {
date_default_timezone_set('Europe/Warsaw');
parent::__construct($environment, $debug);
}
I just had to do this and this was my manual solution:
If you don't know what the PRIMARY field is, look back at your phpmyadmin page, click on the 'Structure' tab and at the bottom of the page under 'Indexes' it will show you which 'Field' has a 'Keyname' value 'PRIMARY'.
Kind of a long way around, but if you don't want to deal with markup and just need to duplicate a single row there you go.
As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost';
does not work is quite simple : There is no grant called USAGE
.
The actual named grants are in the MySQL Documentation
The grant USAGE
is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user
where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE
. Running DROP USER 'phpmyadmin'@'localhost';
should work just fine. Under the hood, it's really doing this:
DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;
Therefore, the removal of a row from mysql.user
constitutes running REVOKE USAGE
, even though REVOKE USAGE
cannot literally be executed.
Install git ( on Windows you have to use git bash console). Type:
file *
for all files in the current directory , or
file */*
for the files in all subdirectories
The toString method on an array only prints out the memory address, which you are getting. You have to loop though the array and print out each item by itself
for(int i : array) {
System.println(i);
}
@Dan,
Do I not need msdtc enabled for transactions to work?
Only distributed transactions - Those that involve more than a single connection. Make doubly sure you are only opening a single connection within the transaction and it won't escalate - Performance will be much better too.
simple add this line into your parent layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true">
<EditText
android:inputType="text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".
It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.
In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):
Inspect element and then click on the three white dots in the left gutter:
The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl+Mousewheel zoom.
Under Help | Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:
Complete the installation and restart Eclipse, then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl+- and Ctrl+= to zoom (although you may have to unbind those keys from Eclipse first).
To get Ctrl+MouseWheel zooming, you can use AutoHotkey with the following script:
; Ctrl+MouseWheel zooming in Eclipse.
; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
; Thank you for the unique window class, SWT/Eclipse.
#IfWinActive ahk_class SWT_Window0
^WheelUp:: Send ^{=}
^WheelDown:: Send ^-
#IfWinActive
To read a specific set of columns from a dataset you, there are several other options:
1) With fread
from the data.table
-package:
You can specify the desired columns with the select
parameter from fread
from the data.table
package. You can specify the columns with a vector of column names or column numbers.
For the example dataset:
library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))
Alternatively, you can use the drop
parameter to indicate which columns should not be read:
dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))
All result in:
> data
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
UPDATE: When you don't want fread
to return a data.table, use the data.table = FALSE
-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)
2) With read.csv.sql
from the sqldf
-package:
Another alternative is the read.csv.sql
function from the sqldf
package:
library(sqldf)
dat <- read.csv.sql("data.txt",
sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
sep = "\t")
3) With the read_*
-functions from the readr
-package:
library(readr)
dat <- read_table("data.txt",
col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')
From the documentation an explanation for the used characters with col_types
:
each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column
I have used similar code for downloading logs from servers. I debug my code and discovered that implementation of URLConnection which is returned is sun.net.www.protocol.http.HttpURLConnection.
Abstract class java.net.URLConnection have two attributes connectTimeout and readTimeout and setters are in abstract class. Believe or not implementation sun.net.www.protocol.http.HttpURLConnection have same attributes connectTimeout and readTimeout without setters and attributes from implementation class are used in getInputStream method. So there is no use of setting connectTimeout and readTimeout because they are never used in getInputStream method. In my opinion this is bug in sun.net.www.protocol.http.HttpURLConnection implementation.
My solution for this was to use HttpClient and Get request.
What we have done was extending org.springframework.web.context.ContextLoaderListener
to print something when the context starts.
public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener
{
private static final Logger logger = LoggerFactory.getLogger( ContextLoaderListener.class );
public ContextLoaderListener()
{
logger.info( "Starting application..." );
}
}
Configure the subclass then in web.xml
:
<listener>
<listener-class>
com.mycomp.myapp.web.context.ContextLoaderListener
</listener-class>
</listener>
let hours = time / 3600
let minutes = (time / 60) % 60
let seconds = time % 60
return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)
A few options:
(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.
(2) The documentation mentions "the underlying writer
instance" ... so just use it (example at the end).
dw.writer.writerow(dw.fieldnames)
(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer
Writing data:
w.writerow([d[k] for k in fieldnames])
or
w.writerow([d.get(k, restval) for k in fieldnames])
Instead of the extrasaction
"functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
============
>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python26\lib\csv.py", line 144, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\python26\lib\csv.py", line 141, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>
Another way when working with incoming data (like from an ajax call):
var new_div = $(data).hide();
$('#old_div').append(new_div);
new_div.slideDown();
The reason for that error is that you are trying to copy a folder which requires -r option also to cp Thanks
def isint(str)
return !!(str =~ /^[-+]?[1-9]([0-9]*)?$/)
end
You can use DateTime
import org.joda.time.DateTime
Option 1 : with yyyyMMddHHmmss
DateTime.now().toString("yyyyMMddHHmmss")
Will give 20190205214430
Option 2 : yyyy-dd-M--HH-mm-ss
DateTime.now().toString("yyyy-dd-M--HH-mm-ss")
will give 2019-05-2--21-43-32
In MainActivity
private static android.support.v4.app.FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
}
public void secondFragment() {
fragmentManager
.beginTransaction()
.setCustomAnimations(R.anim.right_enter, R.anim.left_out)
.replace(R.id.frameContainer, new secondFragment(), "secondFragmentTag").addToBackStack(null)
.commit();
}
In FirstFragment call SecondFrgment Like this:
new MainActivity().secondFragment();
try this
public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
and in tne edit text
final String emailText = email.getText().toString();
EMAIL_ADDRESS_PATTERN.matcher(emailText).matches()
The answer which I was looking for:
( exec "path/to/script" )
As mentioned, exec
replaces the shell without creating a new process. However, we can put it in a subshell, which is done using the parantheses.
EDIT:
Actually ( "path/to/script" )
is enough.
Shared service is a good solution for this issue. If you want to store some activity information too, you can add Shared Service to your main modules (app.module) provider list.
@NgModule({
imports: [
...
],
bootstrap: [
AppComponent
],
declarations: [
AppComponent,
],
providers: [
SharedService,
...
]
});
Then you can directly provide it to your components,
constructor(private sharedService: SharedService)
With Shared Service you can either use functions or you can create a Subject to update multiple places at once.
@Injectable()
export class SharedService {
public clickedItemInformation: Subject<string> = new Subject();
}
In your list component you can publish clicked item information,
this.sharedService.clikedItemInformation.next("something");
and then you can fetch this information at your detail component:
this.sharedService.clikedItemInformation.subscribe((information) => {
// do something
});
Obviously, the data that list component shares can be anything. Hope this helps.
In VS code 'User Settings', you can edit visible colours using the following tags(this is a sample and there are much more tags),
"workbench.colorCustomizations": {
"list.inactiveSelectionBackground": "#C5DEF0",
"sideBar.background": "#F8F6F6",
"sideBar.foreground": "#000000",
"editor.background": "#FFFFFF",
"editor.foreground": "#000000",
"sideBarSectionHeader.background": "#CAC9C9",
"sideBarSectionHeader.foreground": "#000000",
"activityBar.border": "#FFFFFF",
"statusBar.background": "#102F97",
"scrollbarSlider.activeBackground": "#77D4CB",
"scrollbarSlider.hoverBackground": "#8CE6DA",
"badge.background": "#81CA91"}
If you want to edit some C++ color tokens, use the following tag,
"editor.tokenColorCustomizations": {
"numbers": "#2247EB",
"comments": "#6D929C",
"functions": "#0D7C28"
}
Solution without try&catch and without new imports:
if len(driver.find_elements_by_id('blah')) > 0: #pay attention: find_element*s*
driver.find_element_by_id('blah').click #pay attention: find_element
You can add multiple li in ol tag that has attribute as class with value "carousel-indicators" and with data-slide-to has sequential values like 0 to 6 or 0 to 9.
than you just need to copy and paste the div which has attribute as class with value "item".
This works for me.
<div data-ride="carousel" class="carousel slide" id="myCarousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li class="" data-slide-to="0" data-target="#myCarousel"></li>
<li data-slide-to="1" data-target="#myCarousel" class=""></li>
<li data-slide-to="2" data-target="#myCarousel" class="active"></li>
<li data-slide-to="3" data-target="#myCarousel" class=""></li>
<li data-slide-to="4" data-target="#myCarousel" class=""></li>
<li data-slide-to="5" data-target="#myCarousel" class=""></li>
<li data-slide-to="6" data-target="#myCarousel" class=""></li>
</ol>
<div role="listbox" class="carousel-inner">
<div class="item active">
<img alt="First slide" src="images/carousel/11.jpg"
class="first-slide">
</div>
<div class="item">
<img alt="Second slide" src="images/carousel/22.jpg"
class="second-slide">
</div>
<div class="item">
<img alt="Third slide" src="images/carousel/33.jpg"
class="third-slide">
</div>
<div class="item">
<img alt="Third slide" src="images/carousel/44.jpeg"
class="fourth-slide">
</div>
<div class="item">
<img alt="Third slide" src="images/carousel/55.jpg"
class="third-slide">
</div>
<div class="item">
<img alt="Third slide" src="images/carousel/66.jpg"
class="third-slide">
</div>
<div class="item">
<img alt="Third slide" src="images/carousel/77.jpg"
class="third-slide">
</div>
</div>
<a data-slide="prev" role="button" href="#myCarousel"
class="left carousel-control"> <span aria-hidden="true"
class="glyphicon glyphicon-chevron-left"></span> <span
class="sr-only">Previous</span>
</a> <a data-slide="next" role="button" href="#myCarousel"
class="right carousel-control"> <span aria-hidden="true"
class="glyphicon glyphicon-chevron-right"></span> <span
class="sr-only">Next</span>
</a>
</div>
You could apply the function isdigit() on every character in the String. Or you could use regular expressions.
Also I found How do I find one number in a string in Python? with very suitable ways to return numbers. The solution below is from the answer in that question.
number = re.search(r'\d+', yourString).group()
Alternatively:
number = filter(str.isdigit, yourString)
For further Information take a look at the regex docu: http://docs.python.org/2/library/re.html
Edit: This Returns the actual numbers, not a boolean value, so the answers above are more correct for your case
The first method will return the first digit and subsequent consecutive digits. Thus 1.56 will be returned as 1. 10,000 will be returned as 10. 0207-100-1000 will be returned as 0207.
The second method does not work.
To extract all digits, dots and commas, and not lose non-consecutive digits, use:
re.sub('[^\d.,]' , '', yourString)
This example may help:
Controller class:
@RestController
@RequestMapping("/abc/dev")
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MyController {
//Setter Injection
@Resource(name="configBlack")
public void setColor(Color c) {
System.out.println("Injecting setter");
this.blackColor = c;
}
public Color getColor() {
return this.blackColor;
}
public MyController() {
super();
}
Color nred;
Color nblack;
//Constructor injection
@Autowired
public MyController(@Qualifier("constBlack")Color b, @Qualifier("constRed")Color r) {
this.nred = r;
this.nblack = b;
}
private Color blackColor;
//Field injection
@Autowired
private Color black;
//Field injection
@Resource(name="configRed")
private Color red;
@RequestMapping(value = "/customers", produces = { "application/text" }, method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.CREATED)
public String createCustomer() {
System.out.println("Field injection red: " + red.getName());
System.out.println("Field injection: " + black.getName());
System.out.println("Setter injection black: " + blackColor.getName());
System.out.println("Constructor inject nred: " + nred.getName());
System.out.println("Constructor inject nblack: " + nblack.getName());
MyController mc = new MyController();
mc.setColor(new Red("No injection red"));
System.out.println("No injection : " + mc.getColor().getName());
return "Hello";
}
}
Interface Color:
public interface Color {
public String getName();
}
Class Red:
@Component
public class Red implements Color{
private String name;
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Red(String name) {
System.out.println("Red color: "+ name);
this.name = name;
}
public Red() {
System.out.println("Red color default constructor");
}
}
Class Black:
@Component
public class Black implements Color{
private String name;
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Black(String name) {
System.out.println("Black color: "+ name);
this.name = name;
}
public Black() {
System.out.println("Black color default constructor");
}
}
Config class for creating Beans:
@Configuration
public class Config {
@Bean(name = "configRed")
public Red getRedInstance() {
Red red = new Red();
red.setName("Config red");
return red;
}
@Bean(name = "configBlack")
public Black getBlackInstance() {
Black black = new Black();
black.setName("config Black");
return black;
}
@Bean(name = "constRed")
public Red getConstRedInstance() {
Red red = new Red();
red.setName("Config const red");
return red;
}
@Bean(name = "constBlack")
public Black getConstBlackInstance() {
Black black = new Black();
black.setName("config const Black");
return black;
}
}
BootApplication (main class):
@SpringBootApplication
@ComponentScan(basePackages = {"com"})
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
}
Run Application and hit URL: GET 127.0.0.1:8080/abc/dev/customers/
Output:
Injecting setter
Field injection red: Config red
Field injection: null
Setter injection black: config Black
Constructor inject nred: Config const red
Constructor inject nblack: config const Black
Red color: No injection red
Injecting setter
No injection : No injection red
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0
, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes
import matplotlib.pyplot as plt
plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
There was a feature request for that in vscode repo. But it was marked as extension-candidate
and closed. So, here is the extension: Indent One space
Unlike the answer below that tells you to use Ctrl+[ this extension indents code by ONE whtespace ???.
To create setup projects in Visual Studio 2012 with InstallShield Limited Edition, watch this video.
The InstallShield limited edition that cannot install services.
"ISLE is by far the worst installer option and the upgraded, read - paid for, version is cumbersome to use at best and impossible in most situations. InnoSetup, Nullsoft, Advanced, WiX, or just about any other installer is better. If you did a survey you would see that nobody is using ISLE. I don't know why you guys continue to associate with InstallShield. It damages your credibility. Any developer worth half his weight in salt knows ISLE is worthless and when you stand behind it we have to question Microsoft's judgment."
By Edward Miller (comments in Visual Studio Installer Projects Extension).
The WiX Toolset, which, while powerful is exceeding user-unfriendly and has a steep learning curve. There is even a downloadable template for installing Windows services (ref. VS2012: Installer for Windows services?).
For Visual Studio 2013, see blog post Creating installers with Visual Studio.
I found a good short method that seems to work well...
Dim x, y As Integer
x = 3: y = 5
ActiveSheet.Cells(y, x).Select
ActiveCell.Value = "Tada"
In this example we are selecting 3 columns over and 5 rows down, then putting "Tada" in the cell.
Although this has been answer https://stackoverflow.com/a/28375912/5413283, and regarding padding it is not mentioned in the original answer but here https://stackoverflow.com/a/33697157/5413283.
i am just adding here for visual presentation and a cleaner code.
Create a new parent div and add the bootstrap collapse. Remove the classes from the textarea
<div class="collapse" id="collapseOne"> <!-- bootstrap class on parent -->
<textarea class="form-control" rows="4"></textarea>
</div> <!-- // bootstrap class on parent -->
If you want to have spaces around, wrap textarea
with padding. Do not add margin
, it has the same issue.
<div class="collapse" id="collapseOne"> <!-- bootstrap class on parent -->
<div class="py-4"> <!-- padding for textarea -->
<textarea class="form-control" rows="4"></textarea>
</div> <!-- // padding for textarea -->
</div> <!-- // bootstrap class on parent -->
Same as bootstrap 4. Wrap the textare
with collapse
class.
<div class="collapse" id="collapseOne"> <!-- bootstrap class on parent -->
<textarea class="form-control" rows="4"></textarea>
</div> <!-- // bootstrap class on parent -->
And for padding
Bootstrap 3 does not have p-* classes like Bootstrap 4 . So you need to create your own. Do not use padding
it will not work, use margin
.
#collapseOne textarea {
margin: 10px 0 10px 0;
}
What does the letter 'N' on a relationship line in an Entity Relationship diagram mean? Any number
M:N
M - ordinality - describes the minimum (ordinal vs mandatory)
N - cardinality - describes the miximum
1:N (n=0,1,2,3...) one to zero or more
M:N (m and n=0,1,2,3...) zero or more to zero or more (many to many)
1:1 one to one
Find more here: https://www.smartdraw.com/entity-relationship-diagram/
I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.
myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
if(totalPercentage >= 100 && totalBytesSent) {
// All done! Call func here
}
});
Well, I am posting this after such a long time but this will the easiest of all.
To add text at the beginning/a-certain-place-from-start for all lines, just click there and do ALT+C and you will get the below box. Type in your text and click OK and it's done.
To add a certain text at end of all lines, do CTRL+F, and choose REPLACE. You will get the below box. Put in '$' in 'find what' and in 'replace with' type in your text.Make sure you choose 'regular expression' in the search mode (left down). Finally click 'replace all' and you are done.
I had this same problem using DOM data in a Rails view created via the scaffold generator. By default the view omits <th>
elements for the last three columns (which contain links to show, hide, and destroy records). I found that if I added in titles for those columns in a <th>
element within the <thead>
that it fixed the problem.
I can't say if this is the same problem you're having since I can't see your html. If it is not the same problem, you can use the chrome debugger to figure out which column it is erroring out on by clicking on the error in the console (which will take you to the code it is failing on), then adding a conditional breakpoint (at col==undefined
). When it stops you can check the variable i
to see which column it is currently on which can help you figure out what is different about that column from the others. Hope that helps!
Does this really make sense?
There is no "first" record in a relational database, you can only delete one random record.
I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.
To match multiple occurrences, one might do something like this:
iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]
This would return a list of the two indices for the original string.
Oracle 10g has functions that allow the use of POSIX-compliant regular expressions in SQL:
See the Oracle Database SQL Reference for syntax details on this functions.
Take a look at Regular expressions in Perl with examples.
Code :
select * from tbl where regexp_like(col, '^(ABC|XYZ|PQR)');
Take a look at the Google solution. Here is a deletion method only.
ListViewRemovalAnimation project code and Video demonstration
It needs Android 4.1+ (API 16). But we have 2014 outside.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
In addition to the answers above, you can check the type of object using type(plt.subplots())
which returns a tuple, on the other hand, type(plt.subplot())
returns matplotlib.axes._subplots.AxesSubplot
which you can't unpack.
For me I quit Skype, which was occupying port 80, then Apache ran happily on port 80, than I ran Skype and it picked another port this time.
You need a loop over the lines of a file, you need to learn about string methods
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...
For the future, try to ask more focused questions if you can,
the & is the default value for DEFINE, which allows you to use substitution variables. I like to turn it off using
SET DEFINE OFF
then you won't have to worry about escaping or CHR(38).
This is how I solved the problem. Add below code in your AndroidMainfest.xml
<activity android:name=".YourClass"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
Another common cause of this error on the Mac is Apple's quarantine flag.
ls
the directory containing the resource(s) in question. If you see the extended attribute indicator, i.e., the little @
symbol at the end of the permissions block (e.g. -rw-r--r--@
) then the file could be quarantined.
Try ls -la@e
and look for com.apple.quarantine
The following command will remove the quarantine:
xattr -d com.apple.quarantine /path/to/file
Usually this is an OpenSSL version mismatch error, between Apache and PHP. In case Apache loads PHP as a DSO module, its own OpenSSL versions (dlls and libs) will be used. So, in case the PHP extension requires a newer version, it may not find the appropriate interface inside the Apache-loaded DLLS and it will fail to work.
Since you need the PHP extension to load, you need the relevant DLL files to be at least the version of what the PHP module asks for. Supposing that you 're using lastest builds for both Apache and PHP and both having been built with the same MVC version, you can copy the following files:
from the PHP root folder to the Apache2/bin folder, in case you 're confident that the PHP build is newer than the Apache build.
In the opposite case, you can copy the same files from the Apache BIN to the PHP root.
In any case, backup the contents of the APache and PHP folders beforehand.
Adding the PHP path as an enviromental variable will give priority to this path for loading the relevant DLLs and may solve the problem. However, you lose in server portability. Additionally, if you have also added the Apache PATH as a variable and the OpenSSL versions are way different (up to loading different linked DLL files), a lot of shit may happen.
Update:
As of MySQL 5.7 you can use DROP USER IF EXISTS
statement.
Ref: https://dev.mysql.com/doc/refman/5.7/en/drop-user.html
Syntax:
DROP USER [IF EXISTS] user [, user] ...
Example:
DROP USER IF EXISTS 'jeffrey'@'localhost';
FYI (and for older version of MySQL), this is a better solution...!!!
The following SP will help you to remove user 'tempuser'@'%'
by executing CALL DropUserIfExistsAdvanced('tempuser', '%');
If you want to remove all users named 'tempuser'
(say 'tempuser'@'%'
, 'tempuser'@'localhost'
and 'tempuser'@'192.168.1.101'
) execute SP like CALL DropUserIfExistsAdvanced('tempuser', NULL);
This will delete all users named tempuser
!!! seriously...
Now please have a look on mentioned SP DropUserIfExistsAdvanced
:
DELIMITER $$
DROP PROCEDURE IF EXISTS `DropUserIfExistsAdvanced`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `DropUserIfExistsAdvanced`(
MyUserName VARCHAR(100)
, MyHostName VARCHAR(100)
)
BEGIN
DECLARE pDone INT DEFAULT 0;
DECLARE mUser VARCHAR(100);
DECLARE mHost VARCHAR(100);
DECLARE recUserCursor CURSOR FOR
SELECT `User`, `Host` FROM `mysql`.`user` WHERE `User` = MyUserName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET pDone = 1;
IF (MyHostName IS NOT NULL) THEN
-- 'username'@'hostname' exists
IF (EXISTS(SELECT NULL FROM `mysql`.`user` WHERE `User` = MyUserName AND `Host` = MyHostName)) THEN
SET @SQL = (SELECT mResult FROM (SELECT GROUP_CONCAT("DROP USER ", "'", MyUserName, "'@'", MyHostName, "'") AS mResult) AS Q LIMIT 1);
PREPARE STMT FROM @SQL;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END IF;
ELSE
-- check whether MyUserName exists (MyUserName@'%' , MyUserName@'localhost' etc)
OPEN recUserCursor;
REPEAT
FETCH recUserCursor INTO mUser, mHost;
IF NOT pDone THEN
SET @SQL = (SELECT mResult FROM (SELECT GROUP_CONCAT("DROP USER ", "'", mUser, "'@'", mHost, "'") AS mResult) AS Q LIMIT 1);
PREPARE STMT FROM @SQL;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END IF;
UNTIL pDone END REPEAT;
END IF;
FLUSH PRIVILEGES;
END$$
DELIMITER ;
Usage:
CALL DropUserIfExistsAdvanced('tempuser', '%');
to remove user 'tempuser'@'%'
CALL DropUserIfExistsAdvanced('tempuser', '192.168.1.101');
to remove user 'tempuser'@'192.168.1.101'
CALL DropUserIfExistsAdvanced('tempuser', NULL);
to remove all users named 'tempuser'
(eg., say 'tempuser'@'%'
, 'tempuser'@'localhost'
and 'tempuser'@'192.168.1.101'
)
After 2 hrs of net surfing Finally For me the problem was fixed by creating a folder pip, with a file: pip.ini in C:\Users<username>\AppData\Roaming\ e.g:
C:\Users\<username>\AppData\Roaming\pip\pip.ini
Inside it I wrote:
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
I restarted python, and then pip permanently trusted these sites, and used them to download packages from.
If you can't find the AppData Folder on windows, write %appdata% in file explorer and it should appear.
If you haven't created the form and want to change the queryset you can do:
formmodel.base_fields['myfield'].queryset = MyModel.objects.filter(...)
This is pretty useful when you are using generic views!
Two options:
Use a NumericUpDown
instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value.
Handle the appropriate keyboard events to prevent anything but numeric input. I've had success with this two event handlers on a standard TextBox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
You can remove the check for '.'
(and the subsequent check for more than one '.'
) if your TextBox shouldn't allow decimal places. You could also add a check for '-'
if your TextBox should allow negative values.
If you want to limit the user for number of digit, use: textBox1.MaxLength = 2; // this will allow the user to enter only 2 digits
If you tried all the above solutions and still have problems, consider using the method ResolveClientUrl() of ASP.NET .
A script for Example :
Instead of using
<script src="~/dist/js/app.min.js" ></script>
Use the method
<script src="<%= ResolveClientUrl("~/dist/js/app.min.js") %>" ></script>
This was my solution that worked for a friend I was helping!
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
They are simply showed like this:
_______________________
| <<enumeration>> |
| DaysOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
|_____________________|
And then just have an association between that and your class.
If you or another dev will not work on branchB further, I think it's better to keep commits in order to make reverts without headaches. So ;
git checkout branchA
git pull --rebase branchB
It's important that branchB shouldn't be used anymore.
For more ; https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/
Above mentioned answers are correct but what if you are doing a heavy process after losing the focus from the relevant component. For that, I came with a solution with two flags where the focus out event process will only take place when losing the focus from relevant component only.
isFocusInsideComponent = false;
isComponentClicked = false;
@HostListener('click')
clickInside() {
this.isFocusInsideComponent = true;
this.isComponentClicked = true;
}
@HostListener('document:click')
clickout() {
if (!this.isFocusInsideComponent && this.isComponentClicked) {
// do the heavy process
this.isComponentClicked = false;
}
this.isFocusInsideComponent = false;
}
Hope this will help you. Correct me If have missed anything.
The m_
prefix is often used for member variables - I think its main advantage is that it helps create a clear distinction between a public property and the private member variable backing it:
int m_something
public int Something => this.m_something;
It can help to have a consistent naming convention for backing variables, and the m_
prefix is one way of doing that - one that works in case-insensitive languages.
How useful this is depends on the languages and the tools that you're using. Modern IDEs with strong refactor tools and intellisense have less need for conventions like this, and it's certainly not the only way of doing this, but it's worth being aware of the practice in any case.
You can use the MultilineLabel component in the Jide Open Source Components.
If you are trying to replace a fragment within a fragment with the fragmentManager
but you are not inflating the parent fragment that can cause an issue.
In BaseFragment.java OnCreateView
:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new DifferentFragment())
.commit();
}
return super.onCreateView(inflater, container, savedInstanceState);
Replace super.onCreateView(inflater, container, savedInstanceState);
with inflating the correct layout for the fragment:
return inflater.inflate(R.layout.base_fragment, container, false);
It's common to use find/ replace to disable formulas whilst performing manipulations. For example, copy with transpose. The formula is disabled by placing some placeholder (e.g. "$=") in front of it. Find replace can get rid of these once the manipulation is complete.
This vba just automates the find/ replace for the active sheet.
' toggle forumlas on active sheet as active/ inactive
' by use of "$=" prefix
Sub toggle_active_formulas()
Dim current_calc_method As String
initial_calc_method = Application.Calculation
Application.Calculation = xlCalculationManual
Dim predominant As Integer
Dim c As Range
For Each c In ActiveSheet.UsedRange.Cells
If c.HasFormula Then
predominant = predominant + 1
ElseIf "$=" = Left(c.Value, 2) Then
predominant = predominant - 1
End If
Next c
If predominant > 0 Then
For Each c In ActiveSheet.UsedRange.Cells
On Error Resume Next
If c.HasFormula Then
c.Value = "$" & c.Formula
End If
Next c
Else
For Each c In ActiveSheet.UsedRange.Cells
On Error Resume Next
If "$=" = Left(c.Value, 2) Then
c.Formula = Right(c.Value, Len(c.Value) - 1)
End If
Next c
End If
Application.Calculation = initial_calc_method
End Sub
To unset the $_POST
variable, redeclare it as an empty array:
$_POST = array();
In build.gradle
add
wrapper { gradleVersion = '6.0' }
I created an ExecutionTime class out of phihag answer that you can use out of box:
class ExecutionTime
{
private $startTime;
private $endTime;
public function start(){
$this->startTime = getrusage();
}
public function end(){
$this->endTime = getrusage();
}
private function runTime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
public function __toString(){
return "This process used " . $this->runTime($this->endTime, $this->startTime, "utime") .
" ms for its computations\nIt spent " . $this->runTime($this->endTime, $this->startTime, "stime") .
" ms in system calls\n";
}
}
usage:
$executionTime = new ExecutionTime();
$executionTime->start();
// code
$executionTime->end();
echo $executionTime;
Note: In PHP 5, the getrusage function only works in Unix-oid systems. Since PHP 7, it also works on Windows.
There is a new chronology.sty by Levi Wiseman. The documentation (pdf) says:
Most timeline packages and solutions for LATEX are used to convey a lot of information and are therefore designed vertically. If you are just attempting to assign labels to dates, a more traditional timeline might be more appropriate. That's what chronology is for.
Here is some example code:
\documentclass{article}
\usepackage{chronology}
\begin{document}
\begin{chronology}[5]{1983}{2010}{3ex}[\textwidth]
\event{1984}{one}
\event[1985]{1986}{two}
\event{\decimaldate{25}{12}{2001}}{three}
\end{chronology}
\end{document}
Which produces this output:
You can use Id of the field as well
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
//'checked' event code
return;
}
//'unchecked' event code
});
On https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest I found this snippet that uses internal js module:
async function sha256(message) {
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
return hashHex;
}
Note that crypto.subtle
in only available on https
or localhost
- for example for your local development with python3 -m http.server
you need to add this line to your /etc/hosts
:
0.0.0.0 localhost
Reboot - and you can open localhost:8000
with working crypto.subtle
.
Even if we interchange @Component or @Repository or @service
It will behave the same , but one aspect is that they wont be able to catch some specific exception related to DAO instead of Repository if we use component or @ service
You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm
Through this command you will become the owner of the file.
Or, you can be a member of a group that owns this file and then you can use chmod.
But, talk with your sysadmin.
Using Integer.parseIn(String), you can parse string value into integer. Also you need to catch exception in case if input string is not a proper number.
int x = 0;
try {
x = Integer.parseInt("100"); // Parse string into number
} catch (NumberFormatException e) {
e.printStackTrace();
}
jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/
after that everything worked very well, even without any "-extension RANDR" switch.
TL;DR
The @Autowired
annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.
Full explanation
The @Autowired
annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies
you have to put this tag in your XML (application context file):
<context:component-scan base-package="com.mycompany.movies" />
This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component
(for simple bean) or @Controller
(for a servlet control) or @Repository
(for DAO
classes) and these classes are somewhere under the package com.mycompany.movies
, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration
class (or any combination of the three).
The @Autowired
annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder
it understands (by the prefix set
+ the @Autowired
annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder
, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception
. To avoid the Exception
, you can use the @Qualifier
annotation and tell it which of the two beans to inject in the following manner:
@Qualifier("redBean")
class Red implements Color {
// Class code here
}
@Qualifier("blueBean")
class Blue implements Color {
// Class code here
}
Or if you prefer to declare the beans in your XML, it would look something like this:
<bean id="redBean" class="com.mycompany.movies.Red"/>
<bean id="blueBean" class="com.mycompany.movies.Blue"/>
In the @Autowired
declaration, you need to also add the @Qualifier
to tell which of the two color beans to inject:
@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
this.color = color;
}
If you don't want to use two annotations (the @Autowired
and @Qualifier
) you can use @Resource
to combine these two:
@Resource(name="redBean")
public void setColor(Color color) {
this.color = color;
}
The @Resource
(you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.
I'll just add two more comments:
@Inject
instead of @Autowired
because it is not Spring-specific and is part of the JSR-330
standard.@Inject
/ @Autowired
on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException
when you need to actually use the bean.Update: To complete the picture, I created a new question about the @Configuration
class.
It mostly depends on the (other) activity in the database. Operations like this effectively freeze the entire database for other sessions. Another consideration is the datamodel and the presence of constraints,triggers, etc.
My first approach is always: create a (temp) table with a structure similar to the target table (create table tmp AS select * from target where 1=0), and start by reading the file into the temp table. Then I check what can be checked: duplicates, keys that already exist in the target, etc.
Then I just do a "do insert into target select * from tmp" or similar.
If this fails, or takes too long, I abort it and consider other methods (temporarily dropping indexes/constraints, etc)
I would like to point out to you that .val() also works with selects to select the current selected value.
You can use following css to make an element middle aligned styled with position: absolute
:
.element {
transform: translateX(-50%);
position: absolute;
left: 50%;
}
With CSS having only left: 50%
we will have following effect:
While combining left: 50%
with transform: translate(-50%)
we will have following:
.hero { _x000D_
background-color: #e15915;_x000D_
position: relative;_x000D_
height: 320px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
.hero:after {_x000D_
border-right: solid 50px transparent;_x000D_
border-left: solid 50px transparent;_x000D_
border-top: solid 50px #e15915;_x000D_
transform: translateX(-50%);_x000D_
position: absolute;_x000D_
z-index: -1;_x000D_
content: '';_x000D_
top: 100%;_x000D_
left: 50%;_x000D_
height: 0;_x000D_
width: 0;_x000D_
}
_x000D_
<div class="hero">_x000D_
_x000D_
</div>
_x000D_
To color each cell based on its current integer value, the following should work, if you have a recent version of Excel. (Older versions don't handle rgb as well)
Sub Colourise()
'
' Colourise Macro
'
' Colours all selected cells, based on their current integer rgb value
' For e.g. (it's a bit backward from what you might expect)
' 255 = #ff0000 = red
' 256*255 = #00ff00 = green
' 256*256*255 #0000ff = blue
' 255 + 256*256*255 #ff00ff = magenta
' and so on...
'
' Keyboard Shortcut: Ctrl+Shift+C (or whatever you want to set it to)
'
For Each cell In Selection
If WorksheetFunction.IsNumber(cell) Then
cell.Interior.Color = cell.Value
End If
Next cell
End Sub
If instead of a number you have a string then you can split the string into three numbers and combine them using rgb().
This code can do the trick as well, using the SCSS syntax
.parent {
& > * {
margin-right: 15px;
&:last-child {
margin-right: 0;
}
}
}
You can do in this way:
Integer i = 1;
new BigInteger("" + i);
@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000
If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:
...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'
or
...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06'
AND usagetime < '2012-09-03 08:03:07'
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Official npm page suggest a structured method to update angular version for both global and local scenarios.
1.First of all, you need to uninstall the current angular from your system.
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
npm uninstall -g @angular/cli
2.Clean up the cache
npm cache clean
EDIT
As pointed out by @candidj
npm cache clean
is renamed as npm cache verify
from npm 5 onwards
3.Install angular globally
npm install -g @angular/cli@latest
4.Local project setup if you have one
rm -rf node_modules
npm install --save-dev @angular/cli@latest
npm install
Please check the same down on the link below:
https://www.npmjs.com/package/@angular/cli#updating-angular-cli
This will solve the problem.
Here is my extension method for Control
, using LINQ, as an adaptation of @PsychoCoder version:
It takes a list of type instead that allows you to not need multiple calls of GetAll
to get what you want. I currently use it as an overload version.
public static IEnumerable<Control> GetAll(this Control control, IEnumerable<Type> filteringTypes)
{
var ctrls = control.Controls.Cast<Control>();
return ctrls.SelectMany(ctrl => GetAll(ctrl, filteringTypes))
.Concat(ctrls)
.Where(ctl => filteringTypes.Any(t => ctl.GetType() == t));
}
Usage:
// The types you want to select
var typeToBeSelected = new List<Type>
{
typeof(TextBox)
, typeof(MaskedTextBox)
, typeof(Button)
};
// Only one call
var allControls = MyControlThatContainsOtherControls.GetAll(typeToBeSelected);
// Do something with it
foreach(var ctrl in allControls)
{
ctrl.Enabled = true;
}
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
I have been looking at this. On populating the drop down anchors, I have given them a class and data attributes, so when needing to do an action you can do:
<li><a class="dropDownListItem" data-name="Fred Smith" href="#">Fred</a></li>
and then in the jQuery doing something like:
$('.dropDownListItem').click(function(e) {
var name = e.currentTarget;
console.log(name.getAttribute("data-name"));
});
So if you have dynamically generated list items in your dropdown and need to use the data that isn't just the text value of the item, you can use the data attributes when creating the dropdown listitem and then just give each item with the class the event, rather than referring to the id's of each item and generating a click event.
Try using the ISO string
var isodate = new Date().toISOString()
See also: method definition at MDN.
String[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories);
The following code changes the hexadecimal string to a byte array by parsing the string byte-by-byte.
public static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
}
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
Given your current table structure this is not currently possible in DynamoDB. The huge challenge is to understand that the Hash key of the table (partition) should be treated as creating separate tables. In some ways this is really powerful (think of partition keys as creating a new table for each user or customer, etc...).
Queries can only be done in a single partition. That's really the end of the story. This means if you want to query by date (you'll want to use msec since epoch), then all the items you want to retrieve in a single query must have the same Hash (partition key).
I should qualify this. You absolutely can scan
by the criterion you are looking for, that's no problem, but that means you will be looking at every single row in your table, and then checking if that row has a date that matches your parameters. This is really expensive, especially if you are in the business of storing events by date in the first place (i.e. you have a lot of rows.)
You may be tempted to put all the data in a single partition to solve the problem, and you absolutely can, however your throughput will be painfully low, given that each partition only receives a fraction of the total set amount.
The best thing to do is determine more useful partitions to create to save the data:
Do you really need to look at all the rows, or is it only the rows by a specific user?
Would it be okay to first narrow down the list by Month, and do multiple queries (one for each month)? Or by Year?
If you are doing time series analysis there are a couple of options, change the partition key to something computated on PUT
to make the query
easier, or use another aws product like kinesis which lends itself to append-only logging.
I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536
Assuming that you want all rows for which there is another row with the exact same Chromosome
and Locus
:
You can achieve this by joining the table to itself, but only returning the columns from one "side" of the join.
The trick is to set the join condition to "the same locus and chromosome":
select left.*
from Genes left
inner join Genes right
on left.Locus = right.Locus and
left.Chromosome = right.Chromosome and left.ID != right.ID
You can also easily extend this by adding a filter in a where
-clause.
I spent some time on this to get the right information.
So here is the detailed information step by step.
Environment : Windows 7
TomCat version : 7.0
IDE : Eclipse
Configurations to be added for enabling remote debugging with in tomcat is
-Xdebug
-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n
I don't recommend above configuration fro non windows environment. To add the above configuration double click on tomcat server which will be available in server view. Find the below screen shot.
Now add the above runtime environment configuration to tomcat. For this check below screenshot.
Now got to Arugments tab in Edit launch configuration properties as show in below screen shot.
GoTo VM arguments section add these lines.
-Xdebug
-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n
Now got to debug button available on eclipse toolbar.
In Debug configurations find "Remote Java Application" and double click on it.
In Name field enter any name which you like to.
From project field using browse button select the project which you want to perform remote debug.
The hostname is nothing but the host address. Here i'm working locally so it is "localhost".
Last the Port column the value should be 8000. Apart from Name and Project text fields other two columns Host and port will be filled by eclipse itself if not make you have same values as mentioned. Check Screen shot for info.
Now right click on TomcatServer in server console select Add and Remove from context menu. From this dialog you can add the project to server.
Now run the Tomcat sever.
Now run the TomCatDebugConfiguration from Debug Tool.
Last open internal or external browser and run your project. If the execution control reached the break points then the eclipse will prompt for debug perspective.
if any interested I've made a typescript version:
interface IResizeImageOptions {
maxSize: number;
file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
const file = settings.file;
const maxSize = settings.maxSize;
const reader = new FileReader();
const image = new Image();
const canvas = document.createElement('canvas');
const dataURItoBlob = (dataURI: string) => {
const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
const max = bytes.length;
const ia = new Uint8Array(max);
for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
return new Blob([ia], {type:mime});
};
const resize = () => {
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
let dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise((ok, no) => {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = (readerEvent: any) => {
image.onload = () => ok(resize());
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
})
};
and here's the javascript result:
var resizeImage = function (settings) {
var file = settings.file;
var maxSize = settings.maxSize;
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
};
usage is like:
resizeImage({
file: $image.files[0],
maxSize: 500
}).then(function (resizedImage) {
console.log("upload resized image")
}).catch(function (err) {
console.error(err);
});
or (async
/await
):
const config = {
file: $image.files[0],
maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")
I faced the Invalid parameter: redirect_uri problem problem while following spring boot and keycloak example available at http://www.baeldung.com/spring-boot-keycloak. when adding the client from the keycloak server we have to provide the redirect URI for that client so that keycloak server can perform the redirection. When I faced the same error multiple times, I followed copying correct URL from keycloak server console and provided in the valid Redirect URIs space and it worked fine!
-l
(that's a lower-case L).
Try this: Open IIS Manager, change application pool's advance setting, change Enable 32 bit Application to false.
Several other answer give the solution using MAX. In some scenarios using an agregate function is either not possilbe, or not performant.
The alternative that I use a lot is to use a correlated sub-query in the join...
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.id = (
SELECT id FROM `cars` WHERE BelongsToUser = users.id ORDER BY carPrice DESC LIMIT 1
)
WHERE `id`='4'
You need to use the CONCAT()
function in MySQL for string concatenation:
UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;
You can do this with the following SQL:
SELECT STUFF
(
(
SELECT ',' + s.FirstName
FROM Employee s
ORDER BY s.FirstName FOR XML PATH('')
),
1, 1, ''
) AS Employees
Using source or $0 will not give you the real path of your script. You could use the process id of the script to retrieve its real path
ls -l /proc/$$/fd |
grep "255 ->" |
sed -e 's/^.\+-> //'
I am using this script and it has always served me well :)
The problem is that null is not considered equal to itself, hence the clause never matches.
You need to check for null explicitly:
SELECT CASE WHEN last_name is NULL THEN first_name ELSE first_name + ' ' + last_name
This will work for RecyclerView
with header as well.
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
private int headerNum;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge, int headerNum) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
this.headerNum = headerNum;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view) - headerNum; // item position
if (position >= 0) {
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
} else {
outRect.left = 0;
outRect.right = 0;
outRect.top = 0;
outRect.bottom = 0;
}
}
}
}
A cleaner way to do this:
class Book {
public Title: string;
public Price: number;
public Description: string;
constructor(public BookId: number, public Author: string){}
}
Then
var bks: Book[] = [
new Book(1, "vamsee")
];
You could try this:
List<Int32> copy = new List<Int32>(original);
or if you're using C# 3 and .NET 3.5, with Linq, you can do this:
List<Int32> copy = original.ToList();
Robocopy is designed for reliable copying with many copy options, file selection restart, etc.
/xf
to excludes files and /e
for subdirectories:
robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this
points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
Use a for
loop to iterate through your array. For each string, create a new option
element, assign the string as its innerHTML
and value
, and then append it to the select
element.
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
UPDATE: Using createDocumentFragment
and forEach
If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment
acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild
operation so that the DOM only updates once, instead of n
times.
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();
cuisines.forEach(function(cuisine, index) {
var opt = document.createElement('option');
opt.innerHTML = cuisine;
opt.value = cuisine;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
You need to give the body
and the html
a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.
Updated fiddle: http://jsfiddle.net/j8bsS/5/
just use <br>
ex:
<textarea>
blablablabla <br> kakakakakak <br> fafafafafaf
</textarea>
result:
blablablabla
kakakakakak
fafafafafaf
Other people have suggested using in.nextLine()
to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.
You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.
in = new Scanner(System.in);
If you do this, don't call in.close()
first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt();
System.in probably shouldn't be closed during your program.
(The above approach is specific to System.in. It might not be appropriate for other input streams.)
If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.
I'm not sure if it will add deleted files, but git add .
from the root will add all untracked files.
Use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
You can even improve your form processing by stripping all tags with strip_tags()
and remove all white spaces with trim()
:
function processText($text) {
$text = strip_tags($text);
$text = trim($text);
$text = htmlspecialchars($text);
return $text;
}
echo processText($_POST['contact_list']);
I'd fought with this a long time $('#myelement').val(x)
just wasn't working ... until I realized the #
construction requires an ID, not a NAME. So if ".val(x)
doesn't work!" is your problem, check your element and be sure it has an ID!
It's an embarrassing gotcha, but I felt I had to share to save others much hair-tearing.
Assuming you have empty values of types one approach would be this:
var x = (((objectA ?? A.Empty).PropertyOfB ?? B.Empty).PropertyOfC ?? C.Empty).PropertyOfString;
I'm a big fan of C# but a very nice thing in new Java (1.7?) is the .? operator:
var x = objectA.?PropertyOfB.?PropertyOfC.?PropertyOfString;
The essence of object oriented programming is encapsulating logic together with the data it operates on.
Instance methods are the logic, instance fields are the data. Together, they form an object.
public class Foo
{
private String foo;
public Foo(String foo){ this.foo = foo; }
public getFoo(){ return this.foo; }
public static void main(String[] args){
System.out.println( getFoo() );
}
}
What could possibly be the result of running the above program?
Without an object, there is no instance data, and while the instance methods exist as part of the class definition, they need an object instance to provide data for them.
In theory, an instance method that does not access any instance data could work in a static context, but then there isn't really any reason for it to be an instance method. It's a language design decision to allow it anyway rather than making up an extra rule to forbid it.
Make a call to the DB searching with myid (Id of the row) and get back specific columns:
var columns = db.Notifications
.Where(x => x.Id == myid)
.Select(n => new { n.NotificationTitle,
n.NotificationDescription,
n.NotificationOrder });
//note: use of stop function to prevent animation build-ups if called repeatedly
//subtracting container height brings scrollTo position to container bottom
scrollUp = function() {
$("#scroller").stop().animate({ scrollTop: 0 }, "slow");
}
scrollDown = function() {
var scroller = $('#scroller');
var height = scroller[0].scrollHeight - $(scroller).height();
$(scroller).stop().animate({ scrollTop: height }, "slow");
}
Here what I DO on MY PC I install all software that i usually used in G: partian not C: if my operating system is fall (win 10) , Do not need to reinstall them again and lost time , Then How windows work it update PATH automatic if you install any new programe or pice of softwore ,
SO
I must update PATH like these HERE! all my software i usually used
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\HashiCorp\Vagrant\bin;G:\xampp\php;G:\xampp\mysql\bin;G:\Program Files (x86)\heroku\bin;G:\Program Files (x86)\Git\bin;G:\Program Files (x86)\composer;G:\Program Files (x86)\nodejs;G:\Program Files (x86)\Sublime Text 3;G:\Program Files (x86)\Microsoft VS Code\bin;G:\Program Files (x86)\cygwin64\bin
Below is the way we are going within our developing application.
import java.text.SimpleDateFormat
String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)
println(dateAdded)
The output looks like
Sun Nov 11 09:30:31 GMT 2018
In your example, we could adjust a bit to meet your need. If I were you, I will do:
String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)
I hope this would help you much.
You can use the IF
statement in a new cell to replace text, such as:
=IF(A4="C", "Other", A4)
This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.
EDIT
Assuming that the Employee_Count
values are in B1-B10, you can use this:
=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)
This function doesn't even require the data to be sorted; the LARGE
function will find the 10th largest number in the series, and then the rest of the formula will compare against that.
This was how added my headers in my flask application and it worked perfectly
@app.after_request
def add_header(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
return response
try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)
I am using this with Beautifulsoup 4.8.1 to get the value of all class attributes of certain elements:
from bs4 import BeautifulSoup
html = "<td class='val1'/><td col='1'/><td class='val2' />"
bsoup = BeautifulSoup(html, 'html.parser')
for td in bsoup.find_all('td'):
if td.has_attr('class'):
print(td['class'][0])
Its important to note that the attribute key retrieves a list even when the attribute has only a single value.
Try this
rails destroy model Rating
It will remove model, migration, tests and fixtures
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ]
will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ]
.
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)
In your case, I would use shell form
ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"
select definition from pg_views where viewname = 'my_view'
Sometimes you can play with padding and margin top, add line-height, etc.
See fiddle.
Style and text forked from @aspirinemaga
.parent
{
width:300px;
line-height:30px;
border:1px solid red;
padding-top:20px;
}
the easiest way is this. Inside your ListArrayAdapter just do this
if(your condition here) rowView.setBackgroundColor(Color.parseColor("#20FFFFFF"));
don't over complicate
Edit: if you're using .Net 4.5 or later this is built-in to the framework
For earlier versions or for more control you can use Windows' shell functions as outlined here on CodeProject by Gerald Gibson Jr.
I have copied the article text below as written (original license: public domain)
Compress Zip files with Windows Shell API and C
Introduction
This is a follow up article to the one that I wrote about decompressing Zip files. With this code you can use the Windows Shell API in C# to compress Zip files and do so without having to show the Copy Progress window shown above. Normally when you use the Shell API to compress a Zip file, it will show a Copy Progress window even when you set the options to tell Windows not to show it. To get around this, you move the Shell API code to a separate executable and then launch that executable using the .NET Process class being sure to set the process window style to 'Hidden'.
Background
Ever needed to compress Zip files and needed a better Zip than what comes with many of the free compression libraries out there? I.e. you needed to compress folders and subfolders as well as files. Windows Zipping can compress more than just individual files. All you need is a way to programmatically get Windows to silently compress these Zip files. Of course you could spend $300 on one of the commercial Zip components, but it's hard to beat free if all you need is to compress folder hierarchies.
Using the code
The following code shows how to use the Windows Shell API to compress a Zip file. First you create an empty Zip file. To do this create a properly constructed byte array and then save that array as a file with a '.zip' extension. How did I know what bytes to put into the array? Well I just used Windows to create a Zip file with a single file compressed inside. Then I opened the Zip with Windows and deleted the compressed file. That left me with an empty Zip. Next I opened the empty Zip file in a hex editor (Visual Studio) and looked at the hex byte values and converted them to decimal with Windows Calc and copied those decimal values into my byte array code. The source folder points to a folder you want to compress. The destination folder points to the empty Zip file you just created. This code as is will compress the Zip file, however it will also show the Copy Progress window. To make this code work, you will also need to set a reference to a COM library. In the References window, go to the COM tab and select the library labeled 'Microsoft Shell Controls and Automation'.
//Create an empty zip file
byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(args[1]);
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;
//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(args[0]);
Shell32.Folder DestFlder = sc.NameSpace(args[1]);
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);
//Ziping a file using the Windows Shell API
//creates another thread where the zipping is executed.
//This means that it is possible that this console app
//would end before the zipping thread
//starts to execute which would cause the zip to never
//occur and you will end up with just
//an empty zip file. So wait a second and give
//the zipping thread time to get started
System.Threading.Thread.Sleep(1000);
The sample solution included with this article shows how to put this code into a console application and then launch this console app to compress the Zip without showing the Copy Progress window.
The code below shows a button click event handler that contains the code used to launch the console application so that there is no UI during the compress:
private void btnUnzip_Click(object sender, System.EventArgs e)
{
//Test to see if the user entered a zip file name
if(txtZipFileName.Text.Trim() == "")
{
MessageBox.Show("You must enter what" +
" you want the name of the zip file to be");
//Change the background color to cue the user to what needs fixed
txtZipFileName.BackColor = Color.Yellow;
return;
}
else
{
//Reset the background color
txtZipFileName.BackColor = Color.White;
}
//Launch the zip.exe console app to do the actual zipping
System.Diagnostics.ProcessStartInfo i =
new System.Diagnostics.ProcessStartInfo(
AppDomain.CurrentDomain.BaseDirectory + "zip.exe");
i.CreateNoWindow = true;
string args = "";
if(txtSource.Text.IndexOf(" ") != -1)
{
//we got a space in the path so wrap it in double qoutes
args += "\"" + txtSource.Text + "\"";
}
else
{
args += txtSource.Text;
}
string dest = txtDestination.Text;
if(dest.EndsWith(@"\") == false)
{
dest += @"\";
}
//Make sure the zip file name ends with a zip extension
if(txtZipFileName.Text.ToUpper().EndsWith(".ZIP") == false)
{
txtZipFileName.Text += ".zip";
}
dest += txtZipFileName.Text;
if(dest.IndexOf(" ") != -1)
{
//we got a space in the path so wrap it in double qoutes
args += " " + "\"" + dest + "\"";
}
else
{
args += " " + dest;
}
i.Arguments = args;
//Mark the process window as hidden so
//that the progress copy window doesn't show
i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(i);
p.WaitForExit();
MessageBox.Show("Complete");
}