What you suggest is impossible. You will always have collisions.
In order to map two objects to another single set, the mapped set must have a minimum size of the number of combinations expected:
Assuming a 32-bit integer, you have 2147483647 positive integers. Choosing two of these where order doesn't matter and with repetition yields 2305843008139952128 combinations. This does not fit nicely in the set of 32-bit integers.
You can, however fit this mapping in 61 bits. Using a 64-bit integer is probably easiest. Set the high word to the smaller integer and the low word to the larger one.
"I mean the number of digits in an integer, i.e. "123" has a length of 3"
int i = 123;
// the "length" of 0 is 1:
int len = 1;
// and for numbers greater than 0:
if (i > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (len = 0; i > 0; len++) {
i = i / 10;
}
}
// and that's our "length":
std::cout << len;
outputs 3
99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...
You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.
<style>
.hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>
<iframe name="hiddenFrame" class="hide"></iframe>
<form action="receiver.pl" method="post" target="hiddenFrame">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...
Since I don't know how to control only the list marker size with CSS and no one's offered this yet, you can use :before
content to generate the bullets:
li {
list-style: none;
font-size: 20px;
}
li:before {
content:"·";
font-size:120px;
vertical-align:middle;
line-height:20px;
}
Demo: http://jsfiddle.net/4wDL5/
The markers are limited to appearing "inside" with this particular CSS, although you could change it. It's definitely not the best option (browser must support generated content, so no IE6 or 7), but it might be the easiest - plus you can choose any character you want for the marker.
If you go the image route, see list-style-image
.
$(".various").fancybox({
fitToView : false,
width : '100%',
height : '100%',
maxWidth : 850,
maxHeight : 550,
fitToView : false,
padding : 20,
autoSize : true,
closeClick : true,
openEffect : 'none',
closeEffect : 'none',
overflow : 'hidden',
scrolling : 'no'
});
typeof(IMyInterface).IsAssignableFrom(typeof(MyType));
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
The answer from Judah did not work for me (or is not complete) as the application was exiting after the first BeginOutputReadLine();
This works for me as a complete snippet, reading the constant output of a ping:
var process = new Process();
process.StartInfo.FileName = "ping";
process.StartInfo.Arguments = "google.com -t";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.OutputDataReceived += (sender, a) => Console.WriteLine(a.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
This problem is because you have made changes locally to file/s and the same file/s exists with changes in the Git repository, so before pull/push you will need stash local changes:
To overwrite local changes of a single file:
git reset file/to/overwrite
git checkout file/to/overwrite
To overwrite all the local changes (changes in all files):
git stash
git pull
git stash pop
Also this problem may be because of you are on a branch which is not merged with the master branch.
In my case I want to make sure that absolutely everything in the web view opens Safari except the initial load and so I use...
- (BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if(inType != UIWebViewNavigationTypeOther) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
I wanted similar richness in colors for HTML elements, I was surprised to find that CSS now supports hsl() colors, so a full solution for me is below:
Also see How to automatically generate N "distinct" colors? for more alternatives more similar to this.
function colorByHashCode(value) {_x000D_
return "<span style='color:" + value.getHashCode().intToHSL() + "'>" + value + "</span>";_x000D_
}_x000D_
String.prototype.getHashCode = function() {_x000D_
var hash = 0;_x000D_
if (this.length == 0) return hash;_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
hash = this.charCodeAt(i) + ((hash << 5) - hash);_x000D_
hash = hash & hash; // Convert to 32bit integer_x000D_
}_x000D_
return hash;_x000D_
};_x000D_
Number.prototype.intToHSL = function() {_x000D_
var shortened = this % 360;_x000D_
return "hsl(" + shortened + ",100%,30%)";_x000D_
};_x000D_
_x000D_
document.body.innerHTML = [_x000D_
"javascript",_x000D_
"is",_x000D_
"nice",_x000D_
].map(colorByHashCode).join("<br/>");
_x000D_
span {_x000D_
font-size: 50px;_x000D_
font-weight: 800;_x000D_
}
_x000D_
In HSL its Hue, Saturation, Lightness. So the hue between 0-359 will get all colors, saturation is how rich you want the color, 100% works for me. And Lightness determines the deepness, 50% is normal, 25% is dark colors, 75% is pastel. I have 30% because it fit with my color scheme best.
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
Now that the question scope has been corrected, I might add something in this regard as well:
There are many comparisons between Apache Solr and ElasticSearch available, so I'll reference those I found most useful myself, i.e. covering the most important aspects:
Bob Yoplait already linked kimchy's answer to ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?, which summarizes the reasons why he went ahead and created ElasticSearch, which in his opinion provides a much superior distributed model and ease of use in comparison to Solr.
Ryan Sonnek's Realtime Search: Solr vs Elasticsearch provides an insightful analysis/comparison and explains why he switched from Solr to ElasticSeach, despite being a happy Solr user already - he summarizes this as follows:
Solr may be the weapon of choice when building standard search applications, but Elasticsearch takes it to the next level with an architecture for creating modern realtime search applications. Percolation is an exciting and innovative feature that singlehandedly blows Solr right out of the water. Elasticsearch is scalable, speedy and a dream to integrate with. Adios Solr, it was nice knowing you. [emphasis mine]
The Wikipedia article on ElasticSearch quotes a comparison from the reputed German iX magazine, listing advantages and disadvantages, which pretty much summarize what has been said above already:
Advantages:
- ElasticSearch is distributed. No separate project required. Replicas are near real-time too, which is called "Push replication".
- ElasticSearch fully supports the near real-time search of Apache Lucene.
- Handling multitenancy is not a special configuration, where with Solr a more advanced setup is necessary.
- ElasticSearch introduces the concept of the Gateway, which makes full backups easier.
Disadvantages:
Only one main developer[not applicable anymore according to the current elasticsearch GitHub organization, besides having a pretty active committer base in the first place]No autowarming feature[not applicable anymore according to the new Index Warmup API]
They are completely different technologies addressing completely different use cases, thus cannot be compared at all in any meaningful way:
Apache Solr - Apache Solr offers Lucene's capabilities in an easy to use, fast search server with additional features like faceting, scalability and much more
Amazon ElastiCache - Amazon ElastiCache is a web service that makes it easy to deploy, operate, and scale an in-memory cache in the cloud.
[emphasis mine]
Maybe this has been confused with the following two related technologies one way or another:
ElasticSearch - It is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top of Apache Lucene.
Amazon CloudSearch - Amazon CloudSearch is a fully-managed search service in the cloud that allows customers to easily integrate fast and highly scalable search functionality into their applications.
The Solr and ElasticSearch offerings sound strikingly similar at first sight, and both use the same backend search engine, namely Apache Lucene.
While Solr is older, quite versatile and mature and widely used accordingly, ElasticSearch has been developed specifically to address Solr shortcomings with scalability requirements in modern cloud environments, which are hard(er) to address with Solr.
As such it would probably be most useful to compare ElasticSearch with the recently introduced Amazon CloudSearch (see the introductory post Start Searching in One Hour for Less Than $100 / Month), because both claim to cover the same use cases in principle.
add apache.commons dependency on your pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
And below code works.
StringUtils.substringBetween(String mydata, String "'", String "'")
My case may not be typical but what I wanted to do was to have certain columns in a TABLE
completely "inert": impossible to tab into them, and impossible to select anything in them. I had found class "unselectable" from other SO answers:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
This actually prevents the user using the mouse to put the focus in the TD
... but I couldn't find a way on SO to prevent tabbing into cells. The TDs
in my TABLE
actually each has a DIV
as their sole child, and using console.log
I found that in fact the DIVs
would get the focus (without the focus first being obtained by the TDs
).
My solution involves keeping track of the "previously focused" element (anywhere on the page):
window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
window.prevFocus = window.currFocus;
window.currFocus = document.activeElement;
});
I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...
The simplest answer is then just to do this (to the sole DIV
child in every newly created TD
):
...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
window.prevFocus.focus();
});
So far so good. It should be clear that this would work if you just have a TD
(with no DIV
child).
Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.
css:
.navbar-header {
float: left;
padding: 15px;
text-align: center;
width: 100%;
}
.navbar-brand {float:none;}
html:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<a class="navbar-brand" href="#">Brand</a>
</div>
</nav>
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floatingpoint types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:
Name Width in Bits Range
double 64 1 .7e–308 to 1.7e+308
float 32 3 .4e–038 to 3.4e+038
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don't require a large degree of precision.
Here are some example float variable declarations:
float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is my solution and it's also working, when element shows into the viewport
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
var firEvent = false,
objectPosTop = $('.go-counterTeaser').offset().top;
//when element shows at bottom
var elementViewInBottom = objectPosTop - winHeight;
$(window).on('scroll', function() {
var currentPosition = $(document).scrollTop();
//when element position starting in viewport
if (currentPosition > elementViewInBottom && firEvent === false) {
firEvent = true;
animationCounter();
}
});
}
//counter function will animate by using external js also add seprator "."
function animationCounter(){
$('.numberBlock h2').each(function () {
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator('.');
var counterValv = $(this).text();
$(this).animateNumber(
{
number: counterValv,
numberStep: comma_separator_number_step
}
);
});
}
https://jsfiddle.net/uosahmed/frLoxm34/9/
Here is a plunker showing how you can use it with the ngClass
directive.
I'm demonstrating with div
s instead of img
s though.
Template:
<ul>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>
TS:
export class App {
selectedIndex = -1;
setSelected(id: number) {
this.selectedIndex = id;
}
}
Python3 Supported Code
with closing(requests.get(PHISHTANK_URL, stream=True})) as r:
reader = csv.reader(codecs.iterdecode(r.iter_lines(), 'utf-8'), delimiter=',', quotechar='"')
for record in reader:
print (record)
You can turn off Java access restrictions for reflection so that private means nothing.
The setAccessible(true)
call does that.
The only restriction is that a ClassLoader may disallow you from doing that.
See Subverting Java Access Protection for Unit Testing (Ross Burton) for a way to do this in Java.
As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT
. I've commented most of it.
The Setup
class GlobalKeyboardHookEventArgs : HandledEventArgs
{
public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }
public GlobalKeyboardHookEventArgs(
GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
GlobalKeyboardHook.KeyboardState keyboardState)
{
KeyboardData = keyboardData;
KeyboardState = keyboardState;
}
}
//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;
// EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
// the logging mechanism.
/// <summary>
///
/// </summary>
/// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
public GlobalKeyboardHook(Keys[] registeredKeys = null)
{
RegisteredKeys = registeredKeys;
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
if (_windowsHookHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// because we can unhook only in the same thread, not in garbage collector thread
if (_windowsHookHandle != IntPtr.Zero)
{
if (!UnhookWindowsHookEx(_windowsHookHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = IntPtr.Zero;
// ReSharper disable once DelegateSubtraction
_hookProc -= LowLevelKeyboardProc;
}
}
if (_user32LibraryHandle != IntPtr.Zero)
{
if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_user32LibraryHandle = IntPtr.Zero;
}
}
~GlobalKeyboardHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr _windowsHookHandle;
private IntPtr _user32LibraryHandle;
private HookProc _hookProc;
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events are
/// associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">hook type</param>
/// <param name="lpfn">hook procedure</param>
/// <param name="hMod">handle to application instance</param>
/// <param name="dwThreadId">thread identifier</param>
/// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="hhk">handle to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="hHook">handle to current hook</param>
/// <param name="code">hook code passed to hook procedure</param>
/// <param name="wParam">value passed to hook procedure</param>
/// <param name="lParam">value passed to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct LowLevelKeyboardInputEvent
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualCode;
// EDT: added a conversion from VirtualCode to Keys.
/// <summary>
/// The VirtualCode converted to typeof(Keys) for higher usability.
/// </summary>
public Keys Key { get { return (Keys)VirtualCode; } }
/// <summary>
/// A hardware scan code for the key.
/// </summary>
public int HardwareScanCode;
/// <summary>
/// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
/// </summary>
public int Flags;
/// <summary>
/// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
/// </summary>
public int TimeStamp;
/// <summary>
/// Additional information associated with the message.
/// </summary>
public IntPtr AdditionalInformation;
}
public const int WH_KEYBOARD_LL = 13;
//const int HC_ACTION = 0;
public enum KeyboardState
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SysKeyDown = 0x0104,
SysKeyUp = 0x0105
}
// EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
public static Keys[] RegisteredKeys;
const int KfAltdown = 0x2000;
public const int LlkhfAltdown = (KfAltdown >> 8);
public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool fEatKeyStroke = false;
var wparamTyped = wParam.ToInt32();
if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
{
object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;
var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);
// EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
// Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
// has to be null for the event to get fired.
var key = (Keys)p.VirtualCode;
if (RegisteredKeys == null || RegisteredKeys.Contains(key))
{
EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
handler?.Invoke(this, eventArguments);
fEatKeyStroke = eventArguments.Handled;
}
}
return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
}
The Usage differences can be seen here
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private GlobalKeyboardHook _globalKeyboardHook;
private void buttonHook_Click(object sender, EventArgs e)
{
// Hooks only into specified Keys (here "A" and "B").
_globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });
// Hooks into all keys.
_globalKeyboardHook = new GlobalKeyboardHook();
_globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
// EDT: No need to filter for VkSnapshot anymore. This now gets handled
// through the constructor of GlobalKeyboardHook(...).
if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
{
// Now you can access both, the key and virtual code
Keys loggedKey = e.KeyboardData.Key;
int loggedVkCode = e.KeyboardData.VirtualCode;
}
}
}
Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.
Just running the SELECT
statement will have no effect on the data. You have to use an UPDATE
statement with the REPLACE
to make the change occur:
UPDATE photos
SET caption = REPLACE(caption,'"','\'')
Here is a working sample: http://sqlize.com/7FjtEyeLAh
The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1
if both phone numbers exist in Table2
. You may want to do a LEFT JOIN
so that all rows from Table1
are selected. If the phone numbers don't match, then the SomeOtherField
s would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL
The second method could have a problem: what happens if Table2
has both PhoneNumber1
and PhoneNumber2
? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.
Creating a 350 characters GUID:
dbms_random.STRING ('a', 350) - returning string in mixed case alpha characters
dbms_random.STRING ('x', 350) - returning string in uppercase alpha-numeric characters
Remove Get Parameters From Current Page
<?php
$url_dir=$_SERVER['REQUEST_URI'];
$url_dir_no_get_param= explode("?",$url_dir)[0];
echo $_SERVER['HTTP_HOST'].$url_dir_no_get_param;
Do statement as below:
ActiveSheet.Cells(ActiveWindow.SplitRow+1,ActiveWindow.SplitColumn+1).Select
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.
The method ConvertToList that is posted below and uses reflection works perfectly for me. Thanks.
I made a slight modification to make it work with conversions on the T property types.
public List<T> ConvertToList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
{
PropertyInfo pI = objT.GetType().GetProperty(pro.Name);
pro.SetValue(objT, row[pro.Name] == DBNull.Value ? null : Convert.ChangeType(row[pro.Name], pI.PropertyType));
}
}
return objT;
}).ToList();
}
Hope it helps. Regards.
Try adding this to your dependencies:
compile 'org.apache.httpcomponents:httpclient:4.4-alpha1'
And generally if you want to use a library and you are searching for the Gradle dependency line you can use Gradle Please
EDIT: Check this one too.
I have been trying to achieve this by using 1 row single entry but I ended that Invoke command did not worked successfully because it is killing the process immediately after starting despite it can work if you are entering the session and waiting enough before exiting.
The only working way I could find, for example, to run a command with arguments and space on the remote machine HFVMACHINE1 (running Windows 7) is the following:
([WMICLASS]"\\HFVMACHINE1\ROOT\CIMV2:win32_process").Create('c:\Program Files (x86)\Thinware\vBackup\vBackup.exe -v HFSVR12-WWW')
React Router v4
There's a couple of things that I needed to get this working smoothly.
The doc page on auth workflow has quite a lot of what is required.
However I had three issues
props.history
come from?Route
componentprops
?I ended up using:
<Route render>
which gets you props.history
which can then be passed down to the children.render={routeProps => <MyComponent {...props} {routeProps} />}
to combine other props
from this answer on 'react-router - pass props to handler component'N.B. With the render
method you have to pass through the props from the Route
component explicitly. You also want to use render
and not component
for performance reasons (component
forces a reload every time).
const App = (props) => (
<Route
path="/home"
render={routeProps => <MyComponent {...props} {...routeProps}>}
/>
)
const MyComponent = (props) => (
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
fakeAuth.signout(() => props.history.push('/foo'))
}}>Sign out</button>
)
One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match })
i.e. Object destructuring, which meant initially I didn't realise that Route
passes down three props, match
, location
and history
I think some of the other answers here are assuming that everything is done via JavaScript classes.
Here's an example, plus if you don't need to pass any props
through you can just use component
class App extends React.Component {
render () {
<Route
path="/home"
component={MyComponent}
/>
}
}
class MyComponent extends React.Component {
render () {
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
this.fakeAuth.signout(() => this.props.history.push('/foo'))
}}>Sign out</button>
}
}
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
1- Comment out bind 127.0.0.1
2- set requirepass yourpassword
then check if the firewall blocked your port
iptables -L -n
service iptables stop
Please post your Model Class.
To check the errors in your ModelState
use the following code:
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
OR: You can also use
var errors = ModelState.Values.SelectMany(v => v.Errors);
Place a break point at the above line and see what are the errors in your ModelState
.
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
String
A simple regex. See: How to check if a string contains only digits in Java. Use javax.constraints.Pattern.
I use this short format for github repositories:
yarn add github_user/repository_name#commit_hash
You are may be on the wrong owl's doc version.
autoPlay is for 1st version
autoplay is for 2nd version
I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.
UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.
UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.
In case anyone in the future is interested, here's what I came up with:
1. Create a custom directive for the <head>
element:
app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!angular.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
delete scope.routeStyles[sheet];
});
}
if(next && next.$$route && next.$$route.css){
if(!angular.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
This directive does the following things:
$compile
) an html string that creates a set of <link />
tags for every item in the scope.routeStyles
object using ng-repeat
and ng-href
.<link />
elements to the <head>
tag.$rootScope
to listen for '$routeChangeStart'
events. For every '$routeChangeStart'
event, it grabs the "current" $$route
object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head>
tag. It also grabs the "next" $$route
object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head>
tag.ng-repeat
part of the compiled <link />
tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles
object.Note: this requires that your ng-app
attribute is on the <html>
element, not on <body>
or anything inside of <html>
.
2. Specify which stylesheets belong to which routes using the $routeProvider
:
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/some/route/1', {
templateUrl: 'partials/partial1.html',
controller: 'Partial1Ctrl',
css: 'css/partial1.css'
})
.when('/some/route/2', {
templateUrl: 'partials/partial2.html',
controller: 'Partial2Ctrl'
})
.when('/some/route/3', {
templateUrl: 'partials/partial3.html',
controller: 'Partial3Ctrl',
css: ['css/partial3_1.css','css/partial3_2.css']
})
}]);
This config adds a custom css
property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart'
event as .$$route
. So when listening to the '$routeChangeStart'
event, we can grab the css
property that we specified and append/remove those <link />
tags as needed. Note that specifying a css
property on the route is completely optional, as it was omitted from the '/some/route/2'
example. If the route doesn't have a css
property, the <head>
directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3'
example above, where the css
property is an array of relative paths to the stylesheets needed for that route.
3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.
Hope that helps someone else who might be struggling with this issue as much as I was.
You can chnage font size by ctrl + mousewheel.
OR
tools --> options --> environment --> font and color.
Detail with screenshot is mentonied here
check if file exist in side the document/catchimage path :
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
// ur code here
} else {
// ur code here**
}
Pro single
Easy to find.
Hunting down exclusion rules can be quite difficult if I have multiple gitignore, at several levels in the repo.
With multiple files, you also typically wind up with a fair bit of duplication.
Pro multiple
Scopes "knowledge" to the part of the file tree where it is needed.
Since Git only tracks files, an empty .gitignore is the only way to commit an "empty" directory.
(And before Git 1.8, the only way to exclude a pattern like my/**.example
was to create my/.gitignore
in with the pattern **.foo
. This reason doesn't apply now, as you can do /my/**/*.example
.)
I much prefer a single file, where I can find all the exclusions. I've never missed per-directory .svn, and I won't miss per-directory .gitignore either.
That said, multiple gitignores are quite common. If you do use them, at least be consistent in their use to make them reasonable to work with. For example, you may put them in directories only one level from the root.
There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError
will be raised by the .index
method only, because it's the only code you have there!
To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index
will not raise this type of error for any other issues. Not that I can think of any.
To prevent the problem from occurring, you must perform a graceful shutdown of the server from the command line rather than powering off the server.
shutdown -h now
This will stop the running services before powering down the machine.
Based on Centos, an additional method for getting it back up again when you run into this problem is to move mysql.sock:
mv /var/lib/mysql/mysql.sock /var/lib/mysql/mysql.sock.bak
service mysqld start
Restarting the service creates a new entry called mqsql.sock
NOT STRICTLY RELATED TO TYPESCRIPT
Just to add to all the above answers, we can also use the shorthand syntax
var result = uemail || '';
This will give you the email if uemail
variable has some value and it will simply return an empty string if uemail
variable is undefined.
This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.
this also works in a pinch
from flask import Flask, jsonify
from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')
app = Flask(__name__)
@app.route('/')
def index():
return 'Flask is running!'
@app.route('/data')
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
return jsonify(data)
#if __name__ == '__main__':
# app.run()
if __name__ == '__main__':
app.run(host='127.0.0.1', debug=True, ssl_context=context)
Some example of code that I did for my project. Basically you add tags to your entity. Imagine you have input text, on entering Tag name you get drop-down menu with preloaded tags to choose from, you navigate with arrows and select with Enter:
HTML + AngularJS v1.2.0-rc.3
<div>
<form ng-submit="addTag(newTag)">
<input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
data-toggle="dropdown"
ng-change="preloadTags()"
ng-keydown="navigateTags($event)">
<div ng-show="preloadedTags.length > 0">
<nav class="dropdown">
<div class="dropdown-menu preloadedTagPanel">
<div ng-repeat="preloadedTag in preloadedTags"
class="preloadedTagItemPanel"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemPanelActive' : '' "
ng-click="selectTag(preloadedTag)"
tabindex="{{ $index }}">
<a class="preloadedTagItem"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemActive' : '' "
ng-click="selectTag(preloadedTag)">{{ preloadedTag.label }}</a>
</div>
</div>
</nav>
</div>
</form>
</div>
Controller.js
$scope.preloadTags = function () {
var newTag = $scope.newTag;
if (newTag && newTag.trim()) {
newTag = newTag.trim().toLowerCase();
$http(
{
method: 'GET',
url: 'api/tag/gettags',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
params: {'term': newTag}
}
)
.success(function (result) {
$scope.preloadedTags = result;
$scope.preloadedTagsIndex = -1;
}
)
.error(function (data, status, headers, config) {
}
);
} else {
$scope.preloadedTags = {};
$scope.preloadedTagsIndex = -1;
}
};
function checkIndex(index) {
if (index > $scope.preloadedTags.length - 1) {
return 0;
}
if (index < 0) {
return $scope.preloadedTags.length - 1;
}
return index;
}
function removeAllActiveTags() {
for (var x = 0; x < $scope.preloadedTags.length; x++) {
if ($scope.preloadedTags[x].activeTag) {
$scope.preloadedTags[x].activeTag = false;
}
}
}
$scope.navigateTags = function ($event) {
if (!$scope.newTag || $scope.preloadedTags.length == 0) {
return;
}
if ($event.keyCode == 40) { // down
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 38) { // up
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 13) { // enter
removeAllActiveTags();
$scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
}
};
$scope.selectTag = function (preloadedTag) {
$scope.addTag(preloadedTag.label);
};
CSS + Bootstrap v2.3.2
.preloadedTagPanel {
background-color: #FFFFFF;
display: block;
min-width: 250px;
max-width: 700px;
border: 1px solid #666666;
padding-top: 0;
border-radius: 0;
}
.preloadedTagItemPanel {
background-color: #FFFFFF;
border-bottom: 1px solid #666666;
cursor: pointer;
}
.preloadedTagItemPanel:hover {
background-color: #666666;
}
.preloadedTagItemPanelActive {
background-color: #666666;
}
.preloadedTagItem {
display: inline-block;
text-decoration: none;
margin-left: 5px;
margin-right: 5px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 20px;
padding-right: 10px;
color: #666666 !important;
font-size: 11px;
}
.preloadedTagItem:hover {
background-color: #666666;
}
.preloadedTagItemActive {
background-color: #666666;
color: #FFFFFF !important;
}
.dropdown .preloadedTagItemPanel:last-child {
border-bottom: 0;
}
I use WinForms and my way to use File.Exists(string path) is the next one:
public bool FileExists(string fileName)
{
var workingDirectory = Environment.CurrentDirectory;
var file = $"{workingDirectory}\{fileName}";
return File.Exists(file);
}
fileName must include the extension like myfile.txt
Detect OS Version:
public static string OS_Name()
{
return (string)(from x in new ManagementObjectSearcher(
"SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
}
You can easily pick image from asset without UIImage(named: "green-square-Retina")
.
Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.
See this Stackoverflow answer for reference.
You're saying you have this:
char array[20]; char string[100];
array[0]='1';
array[1]='7';
array[2]='8';
array[3]='.';
array[4]='9';
And you'd like to have this:
string[0]= "178.9"; // where it was stored 178.9 ....in position [0]
You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).
Now if you want to copy the first x characters out of array
to string
you can do that with memcpy()
:
memcpy(string, array, x);
string[x] = '\0';
I think it is not possible. Theoretically: select performs two sorts of things:
narrow/broaden the set (set-theory);
mapping the result.
The first one can be seen as a horizontal diminishing opposed to the where-clause which can be seen as a vertical diminishing. On the other hand, a join can augment the set horizontally where a union can augment the set vertically.
augmentation diminishing
horizontal join/select select
vertical union where/inner-join
The second one is a mapping. A mapping, is more a converter. In SQL it takes some fields and returns zero or more fields. In the select, you can use some aggregate functions like, sum, avg etc. Or take all the columnvalues an convert them to string. In C# linq, we say that a select accepts an object of type T and returns an object of type U.
I think the confusion comes by the fact that you can do: select 'howdy' from <table_name>
. This feature is the mapping, the converter part of the select. You are not printing something, but converting! In your example:
SELECT "
WHERE 1 = 1
you are converting nothing/null into "Hello world"
and you narrow the set of nothing / no table into one row, which, imho make no sense at all.
You may notice that, if you don't constrain the number of columns, "Hello world"
is printed for each available row in the table. I hope, you understand why by now. Your select takes nothing from the available columns and creates one column with the text: "Hello world"
.
So, my answer is NO. You can't just leave out the from-clause because the select always needs table-columns to perform on.
Yes, I was late, but I can add for Assemble users: you can use buil-in "parseJSON"
helper http://assemble.io/helpers/helpers-data.html. (Discovered in https://github.com/assemble/assemble/issues/416).
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
This function returns the mode or modes of a function no matter how many, as well as the frequency of the mode or modes in the dataset. If there is no mode (ie. all items occur only once), the function returns an error string. This is similar to A_nagpal's function above but is, in my humble opinion, more complete, and I think it's easier to understand for any Python novices (such as yours truly) reading this question to understand.
def l_mode(list_in):
count_dict = {}
for e in (list_in):
count = list_in.count(e)
if e not in count_dict.keys():
count_dict[e] = count
max_count = 0
for key in count_dict:
if count_dict[key] >= max_count:
max_count = count_dict[key]
corr_keys = []
for corr_key, count_value in count_dict.items():
if count_dict[corr_key] == max_count:
corr_keys.append(corr_key)
if max_count == 1 and len(count_dict) != 1:
return 'There is no mode for this data set. All values occur only once.'
else:
corr_keys = sorted(corr_keys)
return corr_keys, max_count
Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit()
.
For example:
admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()
user = User.query.get(5)
user.name = 'New Name'
db.session.commit()
Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long
value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate
, unlike java.util.Date
, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime
:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:
choco install winflexbison
...which at the time of writing contains Bison 2.7 & Flex 2.6.3.
There is also winflexbison3
which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.
Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.
Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x
Edit: The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six
, released on November 2018.
In Python 3.7 a new keyword argument capture_output
was introduced for subprocess.run
. Enabling the short and simple:
import subprocess
p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8")
assert p.stdout == 'hello world!\n'
Swift 3
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
cell.selectionStyle = .none
return cell
}
Swift 2
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
cell.selectionStyle = .None
return cell
}
You can use below command to open it in VIM editor.
export VISUAL=vim; crontab -e
Note: Please make sure VIM editor is installed on your server.
This could be as simple as a template conflict. Revert to default template in System/Configuration/Design/Themes.
You can use NullableValueTypes (like int?) for this. The code would be like this:
private void Example(int? arg1, int? arg2)
{
if(!arg1.HasValue)
{
//do something
}
if(!arg2.HasValue)
{
//do something else
}
}
You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.
Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.
Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.
The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.
Don't forget to edit the file. Open file /etc/default/tomcat7
and change
#AUTHBIND=no
to
AUTHBIND=yes
then restart.
I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version
for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.
Sourced from a combination of places:
https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx
Bash 4+ tested - This is the correct way to search for size 0:
find /path/to/dir -size 0 -type f -name "*.xml"
Search for multiple file extensions of size 0:
find /path/to/dir -size 0 -type f \( -iname \*.css -o -iname \*.js \)
Note: If you removed the \( ... \) the results would be all of the files that meet this requirement hence ignoring the size 0.
Works for me-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
now, for dplyr
, adding a distinct counter.
df %>%
group_by(aa, bb) %>%
summarise(first=head(value,1), count=n_distinct(value))
You create groups, them summarise within groups.
If data is numeric, you can use:
first(value)
[there is also last(value)
] in place of head(value, 1)
see: http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html
Full:
> df
Source: local data frame [16 x 3]
aa bb value
1 1 1 GUT
2 1 1 PER
3 1 2 SUT
4 1 2 GUT
5 1 3 SUT
6 1 3 GUT
7 1 3 PER
8 2 1 221
9 2 1 224
10 2 1 239
11 2 2 217
12 2 2 221
13 2 2 224
14 3 1 GUT
15 3 1 HUL
16 3 1 GUT
> library(dplyr)
> df %>%
> group_by(aa, bb) %>%
> summarise(first=head(value,1), count=n_distinct(value))
Source: local data frame [6 x 4]
Groups: aa
aa bb first count
1 1 1 GUT 2
2 1 2 SUT 2
3 1 3 SUT 3
4 2 1 221 3
5 2 2 217 3
6 3 1 GUT 2
A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...
[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]
The simple way:
The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):
sudo nano /etc/rc.local
Add the following and save:
#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &
The better way to do this would be to create a Daemon via Upstart:
sudo nano /etc/init/TheNameOfYourDaemon.conf
add the following:
description "My Daemon Job"
author "Your Name"
start on runlevel [2345]
pre-start script
echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script
exec /bin/sh TheNameOfYourScript.sh > /dev/null &
Save this.
Confirm that it looks ok:
init-checkconf /etc/init/TheNameOfYourDaemon.conf
Now reboot the machine:
sudo reboot
Now when you boot up your system, you can see the log file stating that your Daemon is running:
cat /var/log/TheNameOfYourDaemonJobLog.log
• Now you may start/stop/restart/get the status of your Daemon via:
restart: this will stop, then start a service
sudo service TheNameOfYourDaemonrestart restart
start: this will start a service, if it's not running
sudo service TheNameOfYourDaemonstart start
stop: this will stop a service, if it's running
sudo service TheNameOfYourDaemonstop stop
status: this will display the status of a service
sudo service TheNameOfYourDaemonstatus status
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
Return data as XML
SELECT CONVERT(XML, [Data]) AS [Value]
FROM [dbo].[FormData]
WHERE [UID] LIKE '{my-uid}'
Make sure you set a reasonable limit in the SSMS options window, depending on the result you're expecting.
This will work if the text you're returning doesn't contain unencoded characters like &
instead of &
that will cause the XML conversion to fail.
Returning data using PowerShell
For this you will need the PowerShell SQL Server module installed on the machine on which you'll be running the command.
If you're all set up, configure and run the following script:
Invoke-Sqlcmd -Query "SELECT [Data] FROM [dbo].[FormData] WHERE [UID] LIKE '{my-uid}'" -ServerInstance "database-server-name" -Database "database-name" -Username "user" -Password "password" -MaxCharLength 10000000 | Out-File -filePath "C:\db_data.txt"
Make sure you set the -MaxCharLength
parameter to a value that suits your needs.
I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH
or PATH
every time you want to use a different interpreter. Sure, from the command line, activate my-environment
works, but OP specifically asked about double-clicking.
In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe
to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.
You can do as @rmobis has specified in his answer, [Adding something more into it]
Using order by
twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by
:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As @rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate
in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
You could also use the parse_date_time
function from the lubridate
package:
library(lubridate)
day<-"31/08/2011"
as.Date(parse_date_time(day,"dmy"))
[1] "2011-08-31"
parse_date_time
returns a POSIXct object, so we use as.Date
to get a date object. The first argument of parse_date_time
specifies a date vector, the second argument specifies the order in which your format occurs. The orders
argument makes parse_date_time
very flexible.
Try this:
$("input[type=checkbox]").prop('checked', true).uniform();
This is one of those things that can be difficult to search for if you don't already know where to look.
[
is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.
There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.
[
is equivalent to the test
command, except that [
requires ]
as its last argument, and test
does not.
Assuming the bash documentation is installed on your system, if you type info bash
and search for 'test'
or '['
(the apostrophes are part of the search), you'll find the documentation for the [
command, also known as the test
command. If you use man bash
instead of info bash
, search for ^ *test
(the word test
at the beginning of a line, following some number of spaces).
Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne
, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, !=
is the string inequality operator.
You can also find bash documentation on the web.
test
and [
)-ne
is under "arg1 OP arg2")test
The official definition of the test
command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).
Another solution that wasn't mentioned:
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
Alternatively, using the .contains()
method:
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
Paresh Mayani's answer is mostly correct. Simply use a Broadcast Intent to let the system and all the other apps choose in what way the content is going to be shared.
To share text use the following code:
String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));
Using the Datejs library, this can be as easy as:
Date.parse("05/05/2010").toString("MMMM yyyy");
// parse date convert to
// string with
// custom format
I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...
I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops. In a recent case I used the following solution:
$("#content").on('click', '#replace', (function(event){
return confirm('Are you sure you want to do that?')
}));
Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!
Here's what I've got so far (found it on the page Ben Alpert mentioned):
SELECT REPLACE(
SUBSTRING(
SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId` + 1)
, LENGTH(SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId`)
) + 1)
, ','
, ''
)
FROM `clients` c INNER JOIN `clientenrols` e USING (`clientId`)
Set the html and body tags height
to 100%
and remove the margin around the body:
html, body {
height: 100%;
margin: 0px; /* Remove the margin around the body */
}
Now set the position
of your div to fixed
:
#dimScreen
{
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0px;
left: 0px;
z-index: 1000; /* Now the div will be on top */
}
I am running Postgres 9.6 where I had to export a particular schema along with data.
I used the following command:
pg_dump.exe -U username -d databasename -n schemaname > C:\mylocation\mydumpfilename.dmp
If you want only the schema without data, use the switch s
instead of n
Below is the pg_dump switch list:
C:\Program Files\PostgreSQL\9.6\bin>pg_dump --help
pg_dump dumps a database as a text file or to other formats.
Usage:
pg_dump [OPTION]... [DBNAME]
General options:
-f, --file=FILENAME output file or directory name
-F, --format=c|d|t|p output file format (custom, directory, tar,
plain text (default))
-j, --jobs=NUM use this many parallel jobs to dump
-v, --verbose verbose mode
-V, --version output version information, then exit
-Z, --compress=0-9 compression level for compressed formats
--lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock
-?, --help show this help, then exit
Options controlling the output content:
-a, --data-only dump only the data, not the schema
-b, --blobs include large objects in dump
-c, --clean clean (drop) database objects before recreating
-C, --create include commands to create database in dump
-E, --encoding=ENCODING dump the data in encoding ENCODING
-n, --schema=SCHEMA dump the named schema(s) only
-N, --exclude-schema=SCHEMA do NOT dump the named schema(s)
-o, --oids include OIDs in dump
-O, --no-owner skip restoration of object ownership in
plain-text format
-s, --schema-only dump only the schema, no data
-S, --superuser=NAME superuser user name to use in plain-text format
-t, --table=TABLE dump the named table(s) only
-T, --exclude-table=TABLE do NOT dump the named table(s)
-x, --no-privileges do not dump privileges (grant/revoke)
--binary-upgrade for use by upgrade utilities only
--column-inserts dump data as INSERT commands with column names
--disable-dollar-quoting disable dollar quoting, use SQL standard quoting
--disable-triggers disable triggers during data-only restore
--enable-row-security enable row security (dump only content user has
access to)
--exclude-table-data=TABLE do NOT dump data for the named table(s)
--if-exists use IF EXISTS when dropping objects
--inserts dump data as INSERT commands, rather than COPY
--no-security-labels do not dump security label assignments
--no-synchronized-snapshots do not use synchronized snapshots in parallel jobs
--no-tablespaces do not dump tablespace assignments
--no-unlogged-table-data do not dump unlogged table data
--quote-all-identifiers quote all identifiers, even if not key words
--section=SECTION dump named section (pre-data, data, or post-data)
--serializable-deferrable wait until the dump can run without anomalies
--snapshot=SNAPSHOT use given snapshot for the dump
--strict-names require table and/or schema include patterns to
match at least one entity each
--use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead of
ALTER OWNER commands to set ownership
Connection options:
-d, --dbname=DBNAME database to dump
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port number
-U, --username=NAME connect as specified database user
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
--role=ROLENAME do SET ROLE before dump
If no database name is supplied, then the PGDATABASE environment
variable value is used.
Report bugs to <[email protected]>.
The difference is that Thread.start()
starts a thread that calls the run()
method, while Runnable.run()
just calls the run()
method on the current thread.
I was able to achieve this with the following :
Swift 3
override func didMoveToParentViewController(parent: UIViewController?) {
super.didMoveToParentViewController(parent)
if parent == nil {
println("Back Button pressed.")
delegate?.goingBack()
}
}
Swift 4
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if parent == nil {
debugPrint("Back Button pressed.")
}
}
No need of custom back button.
The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill
For files in folder named /files
for i in `IFS="";find /files -name *\ *`
do
echo $i
done > /tmp/list
while read line
do
mv "$line" `echo $line | sed 's/ /_/g'`
done < /tmp/list
rm /tmp/list
One interesting example of a binary tree that hasn't been mentioned is that of a recursively evaluated mathematical expression. It's basically useless from a practical standpoint, but it is an interesting way to think of such expressions.
Basically each node of the tree has a value that is either inherent to itself or is evaluated by recursively by operating on the values of its children.
For example, the expression (1+3)*2
can be expressed as:
*
/ \
+ 2
/ \
1 3
To evaluate the expression, we ask for the value of the parent. This node in turn gets its values from its children, a plus operator and a node that simply contains '2'. The plus operator in turn gets its values from children with values '1' and '3' and adds them, returning 4 to the multiplication node which returns 8.
This use of a binary tree is akin to reverse polish notation in a sense, in that the order in which operations are performed is identical. Also one thing to note is that it doesn't necessarily have to be a binary tree, it's just that most commonly used operators are binary. At its most basic level, the binary tree here is in fact just a very simple purely functional programming language.
There's been some work done on the postgresql JDBC Driver, related to this behaviour:
see https://github.com/pgjdbc/pgjdbc/pull/477
It is now possible, by setting
autosave=alwaysin the connection (see https://jdbc.postgresql.org/documentation/head/connect.html) to avoid the 'current transaction is aborted' syndroma.
That is known as a textbox watermark, and it is done via JavaScript.
or if you use jQuery, a much better approach:
You should also use the style 'color' and not 'font-color'
<?php
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
}
}
?>
In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.
You must sort your data according your needs (es. in reverse order) and use select top query
The usual way to use assertRaises
is to call a function:
self.assertRaises(TypeError, test_function, args)
to test that the function call test_function(args) raises a TypeError.
The problem with self.testListNone[:1]
is that Python evaluates the expression immediately, before the assertRaises
method is called. The whole reason why test_function
and args
is passed as separate arguments to self.assertRaises
is to allow assertRaises
to call test_function(args)
from within a try...except
block, allowing assertRaises
to catch the exception.
Since you've defined self.testListNone = None
, and you need a function to call, you might use operator.itemgetter like this:
import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))
since
operator.itemgetter(self.testListNone,slice(None,1))
is a long-winded way of saying self.testListNone[:1]
, but which separates the function (operator.itemgetter
) from the arguments.
(function () {
"use strict";
angular.module("myApp")
.controller("LoginCtrl", LoginCtrl);
function LoginCtrl($scope, $log, loginSrv, notify) {
$scope.validateUser = function () {
loginSrv.validateLogin($scope.username, $scope.password)
.then(function (data) {
if (data.isValidUser) {
window.location.href = '/index.html';
}
else {
$log.error("error handler message");
}
})
}
} }());
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
Annotation based approach is better. But sometimes manual operation is needed. For this purpose you can use without method of ObjectWriter.
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String jsonText = writer.writeValueAsString(sourceObject);
There is the GeoLocation API, but browser support is rather thin on the ground at present. Most sites that care about such things use a GeoIP database (with the usual provisos about the inaccuracy of such a system). You could also look at third party services requiring user cooperation such as FireEagle.
One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data
or application/x-www-form-urlencoded
:
<form onsubmit='return false'>
<!-- ... -->
</form>
According to https://forums.oracle.com/forums/thread.jspa?messageID=6594485� Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
You can also remove rows and columns by feeding a vector of logical boolean values to the matrix. This handles the situation where you have multiple non-contiguous rows or non-contiguous columns that need to be deleted.
# TRUE = Keep a row/column
# FALSE = Delete a row/column
#
# FALSE for rows 4, 5, and 6
# Row: 1 2 3 4 5 6 7 8 9 10
rows_to_keep <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
# FALSE for columns 7, 8, and 9
# Column: 1 2 3 4 5 6 7 8 9 10
cols_to_keep <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE)
To remove just the rows:
t1 <- t1[rows_to_keep,]
To remove just the columns:
t1 <- t1[,cols_to_keep]
To remove both the rows and columns:
t1 <- t1[rows_to_keep, cols_to_keep]
This coding technique is useful if you don't know in advance what rows or columns you need to remove. The rows_to_keep
and cols_to_keep
vectors can be calculated as appropriate by your code.
Using ios_base::sync_with_stdio(false);
is sufficient to decouple the C
and C++
streams. You can find a discussion of this in Standard C++ IOStreams and Locales, by Langer and Kreft. They note that how this works is implementation-defined.
The cin.tie(NULL)
call seems to be requesting a decoupling between the activities on cin
and cout
. I can't explain why using this with the other optimization should cause a crash. As noted, the link you supplied is bad, so no speculation here.
You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).
I assume your table looks somewhat like this
TABLE
================================
| group_id | user_ids | name |
--------------------------------
| 1 | 1,4,6 | group1 |
--------------------------------
| 2 | 4,5,1 | group2 |
so in your table of user groups, each row represents one group and in user_ids
column you have set of user ids assigned to that group.
Normalized version of this table would look like this
GROUP
=====================
| id | name |
---------------------
| 1 | group1 |
---------------------
| 2 | group2 |
GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1 | 1 |
----------------------
| 1 | 4 |
----------------------
| 1 | 6 |
----------------------
| 2 | 4 |
----------------------
| ...
Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:
/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);
/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);
/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;
/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;
/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;
/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;
This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment
, when you want to remove assignment you just delete row in group_user_assignment
.
In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.
Here is sqlFiddle to play with.
Nine years later. If you know your time zone. I like the T
between date and time. And if you don't want microseconds.
Python <= 3.8
pip3 install pytz # needed!
python3
>>> import datetime
>>> import pytz
>>> datetime.datetime.now(pytz.timezone('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:23:28+01:00'
Tested on Ubuntu 18.04 and Python 3.6.9.
Python >= 3.9
pip3 install tzdata # only on Windows needed!
py -3
>>> import datetime
>>> import zoneinfo
>>> datetime.datetime.now(zoneinfo.ZoneInfo('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:39:36+01:00'
Tested on Windows 10 and Python 3.9.0.
After trying almost every key on my keyboard:
C:\Users\Tim>cd ^
Mehr? Desktop
C:\Users\Tim\Desktop>
So it seems to be the ^ key.
When an unauthorized request comes in, the entire request is URL encoded, and added as a query string to the request to the authorization form, so I can see where this may result in a problem given your situation.
According to MSDN, the correct element to modify to reset maxQueryStringLength in web.config is the <httpRuntime>
element inside the <system.web>
element, see httpRuntime Element (ASP.NET Settings Schema). Try modifying that element.
While you can use rand(42-10) + 10
to get a random number between 10
and 42
(where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:
rand(10...42) # => 13
Available for all versions of Ruby by requiring my backports
gem.
Ruby 1.9.2 also introduced the Random
class so you can create your own random number generator objects and has a nice API:
r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"
The Random
class itself acts as a random generator, so you call directly:
Random.rand(10...42) # => same as rand(10...42)
Notes on Random.new
In most cases, the simplest is to use rand
or Random.rand
. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.
If you use Random.new
, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.new
and use it everywhere else.
The cases where Random.new
is helpful are the following:
rand
/Random.rand
that the main programs might be relying onRandom
objects can marshalled)Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.
In the case the first arg is '-v', then do your conditional ps -ef
, else in all other cases throw the usage.
#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac
If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.
#!/bin/sh
usage ()
{
echo "usage: $0 [-v]"
exit 1
}
unset arg_match
for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done
if [ ! $arg_match ]
then
usage
fi
But, allow multiple occurrences of an argument is convenient to use in situations such as:
$ adduser -u:sam -s -f -u:bob -trace -verbose
We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:
$ adduser -u sam -s -f -u bob -trace -verbose
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
You can use drawables in
app:itemTextColor app:itemIconTint
then you can control the checked state and normal state using a drawable
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemHorizontalPadding="@dimen/margin_30"
app:itemIconTint="@drawable/drawer_item_color"
app:itemTextColor="@drawable/drawer_item_color"
android:theme="@style/NavigationView"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer_menu">
drawer_item_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/selectedColor" android:state_checked="true" />
<item android:color="@color/normalColor" />
</selector>
Here's how I do it:
Code:
let fs = require('fs');
let path = require('path');
let myController = (req, res) => {
let filename = 'myFile.ext';
let absPath = path.join(__dirname, '/my_files/', filename);
let relPath = path.join('./my_files', filename); // path relative to server root
fs.writeFile(relPath, 'File content', (err) => {
if (err) {
console.log(err);
}
res.download(absPath, (err) => {
if (err) {
console.log(err);
}
fs.unlink(relPath, (err) => {
if (err) {
console.log(err);
}
console.log('FILE [' + filename + '] REMOVED!');
});
});
});
};
If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure
I used the following stored procedure to return the value.
CREATE PROCEDURE usp_get_count
AS
BEGIN
DECLARE @VALUE int;
SET @VALUE=(SELECT COUNT(*) FROM tblCar);
RETURN @VALUE;
END
GO
Chrome DevTools has a Snippets panel where you can create and edit JavaScript code as you would in an editor, and execute it. Open DevTools, then select the Sources panel, then select the Snippets tab.
https://developers.google.com/web/tools/chrome-devtools/snippets
You don't have to do anything special, it should just be working.
When I have a fresh rails app with this controller:
class FooController < ApplicationController
def index
raise "error"
end
end
and go to http://127.0.0.1:3000/foo/
I am seeing the exception with a stack trace.
You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.
See config/initializers/backtrace_silencers.rb
in your Rails project
You need to tell SQLPlus which database you want to log on to. Host String needs to be either a connection string or an alias configured in your TNSNames.ora file.
You can also try the following project that aims to help use that api. It's here:https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils
How it works, definitly simply:
public class MainActivity extends ActionBarActivity implements DCACallBack{
/**
* Get the Google Direction between mDevice location and the touched location using the Walk
* @param point
*/
private void getDirections(LatLng point) {
GDirectionsApiUtils.getDirection(this, mDeviceLatlong, point, GDirectionsApiUtils.MODE_WALKING);
}
/*
* The callback
* When the direction is built from the google server and parsed, this method is called and give you the expected direction
*/
@Override
public void onDirectionLoaded(List<GDirection> directions) {
// Display the direction or use the DirectionsApiUtils
for(GDirection direction:directions) {
Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions);
GDirectionsApiUtils.drawGDirection(direction, mMap);
}
}
File -> Settings
Preferences->Project Interpreter->Python Interpreters
If it's not listed add it.
Kotlin's way -
fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
callBack(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
}
If your collection type is a List<stuff>
, then the best approach is probably the following:
prods.RemoveAll(s => s.ID == 1)
This only does one pass (iteration) over the list, so should be more efficient than other methods.
If your type is more generically an ICollection<T>
, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where
or Single
).
Swift 5
To make it easy, create a file "DispatchQueue+Extensions.swift" with this content :
import Foundation
typealias Dispatch = DispatchQueue
extension Dispatch {
static func background(_ task: @escaping () -> ()) {
Dispatch.global(qos: .background).async {
task()
}
}
static func main(_ task: @escaping () -> ()) {
Dispatch.main.async {
task()
}
}
}
Usage :
Dispatch.background {
// do stuff
Dispatch.main {
// update UI
}
}
I used to use Firebug, until Internet Explorer 8 came out. I'm not a huge fan of Internet Explorer, but after spending some time with the built-in developer tools, which includes a really nice debugger, it seems pointless to use anything else. I have to tip my hat to Microsoft they did a fantastic job on this tool.
You can instantiate an object from matplotlib.pyplot.axes
and call the set_ylim()
on it. It would be something like this:
import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)
It is very simple to do, open your PowerShell and write the following command if you have number of ps1 files. here you have to change the path with your path.
PS C:\Users> Get-ChildItem -Path "D:\downlod" -Recurse | Unblock-File
I found a solution that adds columns at runtime, and binds to a DataTable
.
Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me. Any suggestions?
xaml
<DataGrid
Name="dataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding}">
</DataGrid>
xaml.cs using System.Windows.Data;
if (table != null) // table is a DataTable
{
foreach (DataColumn col in table.Columns)
{
dataGrid.Columns.Add(
new DataGridTextColumn
{
Header = col.ColumnName,
Binding = new Binding(string.Format("[{0}]", col.ColumnName))
});
}
dataGrid.DataContext = table;
}
Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false
now:
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
if (type != null) {
// ...
}
return new TestBean();
}
Is adb installed? To check, run the following command in Terminal:
~/Library/Android/sdk/platform-tools/adb
If that prints output, skip these following install steps and go straight to the final Terminal command I list:
Run the following command on your Mac and restart your Terminal session:
echo export "PATH=~/Library/Android/sdk/platform-tools:$PATH" >> ~/.bash_profile
Note: If you've switched to zsh, the above command should use .zshenv
rather than .bash_profile
I'm using node modules copy-to module to create a single file to require all the files in our NodeJS-based system.
The code for our utility file looks like this:
/**
* Module dependencies.
*/
var copy = require('copy-to');
copy(require('./module1'))
.and(require('./module2'))
.and(require('./module3'))
.to(module.exports);
In all of the files, most functions are written as exports, like so:
exports.function1 = function () { // function contents };
exports.function2 = function () { // function contents };
exports.function3 = function () { // function contents };
So, then to use any function from a file, you just call:
var utility = require('./utility');
var response = utility.function2(); // or whatever the name of the function is
I was just looking for a solution to this, and the answers above didn't work in my case (and I have insufficient reputation to comment on them). It turns out that, at least for my use-case and the browser I was using (Chrome on OSX), the only thing that seemed to prevent caching was:
Cache-Control = 'no-store'
For completeness i'm now using all 3 of 'no-cache, no-store, must-revalidate'
So in my case (serving dynamically generated images out of Flask in Python), I had to do the following to hopefully work in as many browsers as possible...
def make_uncached_response(inFile):
response = make_response(inFile)
response.headers['Pragma-Directive'] = 'no-cache'
response.headers['Cache-Directive'] = 'no-cache'
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
I basically do like this, create new element and attach that to <head>
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
You may also use onload
event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.
x.onload=callback_function;
If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.
String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}
Give name and values to those submit buttons like:
<td>
<input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
</td>
<td>
<input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
</td>
and then in your php script you could check
if($_POST['mybutton'] == 'save')
{
///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
///do publish processing here
}
You can bind the mouseenter
and mouseleave
events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
note: do not use hover as that is deprecated
Here's my take on this problem.
I have defined a function 'index' which takes the number and the input index and outputs the digit at the desired index.
The enumerate method operates on the strings, therefore the number is first converted to a string. Since the indexing in Python starts from zero, but the desired functionality requires it to start with 1, therefore a 1 is placed in the enumerate function to indicate the start of the counter.
def index(number, i):
for p,num in enumerate(str(number),1):
if p == i:
print(num)
As a python neophyte, I just wanted to mention that if the data did actually look like this:
data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
then sorted()
would automatically sort by the second element in the tuple, as the first elements are all identical.
If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
DNS server usually have a standard of ports used. But if it's different, you could try nmap and do a port scan like so:
> nmap 127.0.0.1
This won't work anymore from 1.2.0-rc1. See this issue for more about it, in which I posted a comment describing a quick workaround. I'll share it here as well :
// Quick fix : replace the script tag you want to load by a <div load-script></div>.
// Then write a loadScript directive that creates your script tag and appends it to your div.
// Took me one minute.
// This means that in your view, instead of :
<script src="/path/to/my/file.js"></script>
// You'll have :
<div ng-load-script></div>
// And then write a directive like :
angular.module('myModule', []).directive('loadScript', [function() {
return function(scope, element, attrs) {
angular.element('<script src="/path/to/my/file.js"></script>').appendTo(element);
}
}]);
Not the best solution ever, but hey, neither is putting script tags in subsequent views. In my case I have to do this is order to use Facebook/Twitter/etc. widgets.
Old question but this answer might help someone.
If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden
, otherwise anything outside of it will be cut off.
Lists are slightly faster than sets when you just want to iterate over the values.
Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though.
It turns out tuples perform in almost exactly the same way as lists, except for their immutability.
Iterating
>>> def iter_test(iterable):
... for i in iterable:
... pass
...
>>> from timeit import timeit
>>> timeit(
... "iter_test(iterable)",
... setup="from __main__ import iter_test; iterable = set(range(10000))",
... number=100000)
12.666952133178711
>>> timeit(
... "iter_test(iterable)",
... setup="from __main__ import iter_test; iterable = list(range(10000))",
... number=100000)
9.917098999023438
>>> timeit(
... "iter_test(iterable)",
... setup="from __main__ import iter_test; iterable = tuple(range(10000))",
... number=100000)
9.865639209747314
Determine if an object is present
>>> def in_test(iterable):
... for i in range(1000):
... if i in iterable:
... pass
...
>>> from timeit import timeit
>>> timeit(
... "in_test(iterable)",
... setup="from __main__ import in_test; iterable = set(range(1000))",
... number=10000)
0.5591847896575928
>>> timeit(
... "in_test(iterable)",
... setup="from __main__ import in_test; iterable = list(range(1000))",
... number=10000)
50.18339991569519
>>> timeit(
... "in_test(iterable)",
... setup="from __main__ import in_test; iterable = tuple(range(1000))",
... number=10000)
51.597304821014404
In launchSettings.json, under iisSettings, set anonymousAuthentication to true:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4200/",
"sslPort": 0
}
}
Then, in Startup.cs, under ConfigureServices, before services.AddMvc, add:
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.WithHeaders(HeaderNames.AccessControlAllowHeaders, "Content-Type")
.AllowAnyMethod()
.AllowCredentials();
}));
and then, in configure method, before app.UseMvc() add:
app.UseCors("ApiCorsPolicy");
As of HTML5 it is OK to wrap <a>
elements around a <div>
(or any other block elements):
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).
Just have to make sure you don't put an <a>
within your <a>
( or a <button>
).
You'll need to deal with File System Object
. See this OpenTextFile
method sample.
The regex into selected answer fail for Unicode: 0x1d (with php 7.4)
a solution:
<?php
$ct = 'différents'."\r\n test";
// fail for Unicode: 0x1d
$ct = preg_replace('/[\x00-\x1F\x7F]$/u', '',$ct);
// work for Unicode: 0x1d
$ct = preg_replace( '/[^\P{C}]+/u', "", $ct);
// work for Unicode: 0x1d and allow line break
$ct = preg_replace( '/[^\P{C}\n]+/u', "", $ct);
echo $ct;
from: UTF 8 String remove all invisible characters except newline
You can clear te selection by
$('#object').empty();
But it wont turn you back to your placeholder.
So its a half solution
$array = str_split("$string");
will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use
do {
$array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );
because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
Django 1.11 delete all objects from a database table -
Entry.objects.all().delete() ## Entry being Model Name.
Refer the Official Django documentation here as quoted below - https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects
Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:
I myself tried the code snippet seen below within my somefilename.py
# for deleting model objects
from django.db import connection
def del_model_4(self):
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(model_4)
and within my views.py
i have a view that simply renders a html page ...
def data_del_4(request):
obj = calc_2() ##
obj.del_model_4()
return render(request, 'dc_dash/data_del_4.html') ##
it ended deleting all entries from - model == model_4 , but now i get to see a Error screen within Admin console when i try to asceratin that all objects of model_4 have been deleted ...
ProgrammingError at /admin/dc_dash/model_4/
relation "dc_dash_model_4" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "dc_dash_model_4"
Do consider that - if we do not go to the ADMIN Console and try and see objects of the model - which have been already deleted - the Django app works just as intended.
Where have you specified the mapping code (CreateMap)? Reference: Where do I configure AutoMapper?
If you're using the static Mapper method, configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications.
If the configuration isn't registered before calling the Map method, you will receive Missing type map configuration or unsupported mapping.
Note: I've only tested this in Chrome.
it adds a prototype function to the XMLHttpRequest .. XHR2,
in XHR 1 you probably just need to replace this.response
with this.responseText
Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
return JSON.parse(this.response);
},writable:false,enumerable:false});
to return the json in xhr2
xhr.onload=function(){
console.log(this.responseJSON());
}
EDIT
If you plan to use XHR with arraybuffer
or other response types then you have to check if the response is a string
.
in any case you have to add more checks e.g. if it's not able to parse the json.
Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
return (typeof this.response==='string'?JSON.parse(this.response):this.response);
},writable:false,enumerable:false});
how about this:
df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
out = np.argwhere(df.columns.isin(['apple', 'orange'])).ravel()
print(out)
[1 2]
Another method is has_key()
(if still using Python 2.X):
>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
I would recommend this (just found via search):
I solved my problem like this...
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message,
String keys, String msgId, String branchId) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationCompat.Builder nBuilder;
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Smart Share - " + keys)
.setLights(Color.BLUE, 500, 500).setContentText(message)
.setAutoCancel(true).setTicker("Notification from smartshare")
.setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })
.setSound(alarmSound);
String consumerid = null;
Integer position = null;
Intent resultIntent = null;
if (consumerid != null) {
if (msgId != null && !msgId.equalsIgnoreCase("")) {
if (key != null && key.equalsIgnoreCase("Yo! Matter")) {
ViewYoDataBase db_yo = new ViewYoDataBase(context);
position = db_yo.getPosition(msgId);
if (position != null) {
resultIntent = new Intent(context,
YoDetailActivity.class);
resultIntent.putExtra("id", Integer.parseInt(msgId));
resultIntent.putExtra("position", position);
resultIntent.putExtra("notRefresh", "notRefresh");
} else {
resultIntent = new Intent(context,
FragmentChangeActivity.class);
resultIntent.putExtra(key, key);
}
} else if (key != null && key.equalsIgnoreCase("Message")) {
resultIntent = new Intent(context,
FragmentChangeActivity.class);
resultIntent.putExtra(key, key);
}.
.
.
.
.
.
} else {
resultIntent = new Intent(context, FragmentChangeActivity.class);
resultIntent.putExtra(key, key);
}
} else {
resultIntent = new Intent(context, MainLoginSignUpActivity.class);
}
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
notify_no, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (notify_no < 9) {
notify_no = notify_no + 1;
} else {
notify_no = 0;
}
nBuilder.setContentIntent(resultPendingIntent);
NotificationManager nNotifyMgr = (NotificationManager) context
.getSystemService(context.NOTIFICATION_SERVICE);
nNotifyMgr.notify(notify_no + 2, nBuilder.build());
}
Two approaches are to write to a string buffer or to write lines to a list and join them later. I think the StringIO
approach is more pythonic, but didn't work before Python 2.6.
from io import StringIO
with StringIO() as s:
print("Hello", file=s)
print("Goodbye", file=s)
# And later...
with open('myfile', 'w') as f:
f.write(s.getvalue())
You can also use these without a ContextMananger
(s = StringIO()
). Currently, I'm using a context manager class with a print
function. This fragment might be useful to be able to insert debugging or odd paging requirements:
class Report:
... usual init/enter/exit
def print(self, *args, **kwargs):
with StringIO() as s:
print(*args, **kwargs, file=s)
out = s.getvalue()
... stuff with out
with Report() as r:
r.print(f"This is {datetime.date.today()}!", 'Yikes!', end=':')
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
@angular/material
has changed its folder structure. Now you need to use all the modules from their respective folders instead of just material
folder
For example:
import { MatDialogModule } from "@angular/material";
has now changed to
import { MatDialogModule } from "@angular/material/dialog";
You can check the following to find the correct path for your module
https://material.angular.io/components/categories
Just navigate to the API tab of required module and find the correct path like this
To expound more on @vrian's answer
To view the bootstrap version of a website in your web browser, do the following:
First Method:
boostrap.min.js
or boostrap.min.css
. It should look like this <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
Bootstrap v4.4.1 (https://getbootstrap.com/)
Second Method:
boostrap.min.css
Bootstrap v4.4.1 (https://getbootstrap.com/)
That's all
I hope this helps
I'll add this in here as my problem had something todo with my virtualenv
:
I hadn't activated my virtual environment and was trying to install my requirements, this ultimately led to my install failing and throwing this error message.
So make sure you activate your virtualenv!
%1 refers to the first argument passed in and can't be used in an iterator.
Try this:
@echo off
for %%i in (*.*) do echo %%i
You use uninstall the app and change the sharedPreferences name then run this application. I think it will resolve the issue.
A sample code to retrieve values from sharedPreferences you can use the following set of code,
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyValue, ""));
In jupyter notebook run:
!echo y | jupyter kernelspec uninstall unwanted-kernel
In anaconda prompt run:
jupyter kernelspec uninstall unwanted-kernel
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
echo -ne '\n' | <yourfinecommandhere>
or taking advantage of the implicit newline that echo generates (thanks Marcin)
echo | <yourfinecommandhere>
Now we can simply use the --sk
option:
--sk
,--skip-keypress
Don't wait for a keypress after each test
i.e. sudo rkhunter --sk --checkall
Content types are included in HTTP responses because the same, byte for byte sequence of values in the content could be interpreted in more than one way.(*)
Remember that http can transport more than just HTML (js, css and images are obvious examples), and in some cases, the receiver will not know what type of object it's going to receive.
(*) the obvious one here is XHTML - which is XML. If it's served with a content type of application/xml
, the receiver ought to just treat it as XML. If it's served up as application/xhtml+xml
, then it ought to be treated as XHTML.
I believe that the correct answer would be to make the two numbers (BigDecimals), have the same scale, then we can decide about their equality. For example, are these two numbers equal?
1.00001 and 1.00002
Well, it depends on the scale. On the scale 5 (5 decimal points), no they are not the same. but on smaller decimal precisions (scale 4 and lower) they are considered equal. So I suggest make the scale of the two numbers equal and then compare them.
String extends Object, which means an Object. Object o = a;
If you really want to get as Object, you may do like below.
String s = "Hi";
Object a =s;
If you are trying to keep a list
of list
s (similar to python
's list.append()
) then this might work:
a <- list(1,2,3)
b <- list(4,5,6)
c <- append(list(a), list(b))
> c
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[1]][[3]]
[1] 3
[[2]]
[[2]][[1]]
[1] 4
[[2]][[2]]
[1] 5
[[2]][[3]]
[1] 6
Try Foo.instance_methods.include? :bar
I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.
See also the comment in this post regarding pacman ifs.
This will do exactly what you done in php:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
I used fake UserAgent.
How to use:
from fake_useragent import UserAgent
import requests
ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)
Output:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>
This gem adds a Boolean class to Ruby with useful methods.
https://github.com/RISCfuture/boolean
Use:
require 'boolean'
Then your
true.is_a?(Boolean)
false.is_a?(Boolean)
will work exactly as you expect.
For Eclipse Mars use the similar approach as harshit.
1) Help -> Install New Software
2) Use url: http://download.oracle.com/otn_software/oepe/mars repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse
In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.
During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.
Eclipse 4.5.0 Mars JDK : 1.8
This approach seems more straightforward, avoiding the need to individually select each file:
# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours
or
# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours
Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull
I was able to bypass this error by invoking PowerShell like this:
powershell -executionpolicy bypass -File .\MYSCRIPT.ps1
That is, I added the -executionpolicy bypass
to the way I invoked the script.
This worked on Windows 7 Service Pack 1. I am new to PowerShell, so there could be caveats to doing that that I am not aware of.
[Edit 2017-06-26] I have continued to use this technique on other systems including Windows 10 and Windows 2012 R2 without issue.
Here is what I am using now. This keeps me from accidentally running the script by clicking on it. When I run it in the scheduler I add one argument: "scheduler" and that bypasses the prompt.
This also pauses the window at the end so I can see the output of PowerShell.
if NOT "%1" == "scheduler" (
@echo looks like you started the script by clicking on it.
@echo press space to continue or control C to exit.
pause
)
C:
cd \Scripts
powershell -executionpolicy bypass -File .\rundps.ps1
set psexitcode=%errorlevel%
if NOT "%1" == "scheduler" (
@echo Powershell finished. Press space to exit.
pause
)
exit /b %psexitcode%
I resolved this by arranging the order in which your JS is being loaded.
You need to have it as jQuery -> datePicker -> Init js
Call your JQuery in your header, datePicker script in head below your jquery and Init JS in footer
You also can create Firbase Dynamic links which will work as per your requirement. It supports multiple platforms. This link can be created, manually as well as via programming. You can then embed this link in QR code.
If the target app is installed, the link will redirect user to app. If its not installed it will redirect to Play Store/App store/Any other configured website.
Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli
:
$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1
I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.
Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.
The key here is the name
attribute of the f
object representing the opened file. You get it like that:
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'
Does it help?
yes it is possible you can use border-radius CSS property. For more info have a look at http://zeeshanmkhan.com/post/2/css-rounded-corner-gradient-drop-shadow-and-opacity
Relative sys.path example:
# /lib/my_module.py
# /src/test.py
if __name__ == '__main__' and __package__ is None:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module
Based on this answer.
Ok, there are a bunch of ways you can do that. Yes, you can use plain old JS. Just try:
let dt1 = new Date()
let dt2 = new Date()
Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
.plusYears(6)
.plusMonths(12)
.plusHours(2)
.plusMinutes(42)
.plusSeconds(12);
// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.
Use var
instead of int
for your clicks
variable generation and onClick
instead of click
as your function name:
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
In JavaScript variables are declared with the var
keyword. There are no tags like int
, bool
, string
... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.
And the name 'click' is reserved by JavaScript for function names so you have to use something else.
Did you try this?
UPDATE table
SET col1 = NULL
WHERE col1 = ''
As the commenters point out, you don't have to do ltrim()
or rtrim()
, and NULL
columns will not match ''
.
In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below
val MY_CONSTANT = "Constants"
And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.
companion object{
const val MY_CONSTANT = "Constants"
}
Changing
RestResponse response = client.Execute(request);
to
IRestResponse response = client.Execute(request);
worked for me.
Try ClassGraph. (Disclaimer, I am the author). ClassGraph supports scanning for subclasses of a given class, either at runtime or at build time, but also much more. ClassGraph can build an abstract representation of the entire class graph (all classes, annotations, methods, method parameters, and fields) in memory, for all classes on the classpath, or for classes in selected packages, and you can query this class graph however you want. ClassGraph supports more classpath specification mechanisms and classloaders than any other scanner, and also works seamlessly with the new JPMS module system, so if you base your code on ClassGraph, your code will be maximally portable. See the API here.
Use the backslash to escape a character. For example:
/\\d/
This will match \d instead of a numeric character
I had the same problem as you though I have followed a different guide: http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
The strange part is that, in this guide I have used, I should not have any problem with compatibility between versions (1.x against 2.x) because following the guide you use the jersey 1.8.x on pom.xml
and in the web.xml
you refer to a class (com.sun.jersey.spi.container.servlet.ServletContainer
) as said before of 1.x version. So as I can infer this should be working.
My guess is because I'm using JDK 1.7 this class does not exist anymore.
After, I tried to resolve with the answers before mine, did not helped, I have made changes on the pom.xml
and on the web.xml
the error changed to: java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Which supposedly should be exist!
As result of this error, I found a "new" solution: http://marek.potociar.net/2013/06/13/jax-rs-2-0-and-jersey-2-0-released/
With Maven (archetypes), generate a jersey project, likes this:
mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.0
And it worked for me! :)
Use sort_values
to sort the df by a specific column's values:
In [18]:
df.sort_values('2')
Out[18]:
0 1 2
4 85.6 January 1.0
3 95.5 February 2.0
7 104.8 March 3.0
0 354.7 April 4.0
8 283.5 May 5.0
6 238.7 June 6.0
5 152.0 July 7.0
1 55.4 August 8.0
11 212.7 September 9.0
10 249.6 October 10.0
9 278.8 November 11.0
2 176.5 December 12.0
If you want to sort by two columns, pass a list of column labels to sort_values
with the column labels ordered according to sort priority. If you use df.sort_values(['2', '0'])
, the result would be sorted by column 2
then column 0
. Granted, this does not really make sense for this example because each value in df['2']
is unique.
If you want they to be paragraph, then use it.
<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>
Both <label>
and <input>
are paragraph and flow content so you can insert as paragraph elements and as block elements.