This means your array is missing the key you're looking for. I handle this with a function which either returns the value if it exists or it returns a default value instead.
def keyCheck(key, arr, default):
if key in arr.keys():
return arr[key]
else:
return default
myarray = {'key1':1, 'key2':2}
print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')
Output:
1
2
#default
Well, you can hide it, by removing the entire system menu:
private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= ~WS_SYSMENU;
return cp;
}
}
Of course, doing so removes the minimize and maximize buttons.
If you keep the system menu but remove the close item then the close button remains but is disabled.
The final alternative is to paint the non-client area yourself. That's pretty hard to get right.
Given you've set up a git daemon on <url>
and an empty repository:
cd <localdir>
git init
git add .
git commit -m 'message'
git remote add origin <url>
git push -u origin master
This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true
.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Thanks everyone!
ANSI C99/C11 don't include an extra printf conversion specifier for bool
.
But the GNU C library provides an API for adding custom specifiers.
An example:
#include <stdio.h>
#include <printf.h>
#include <stdbool.h>
static int bool_arginfo(const struct printf_info *info, size_t n,
int *argtypes, int *size)
{
if (n) {
argtypes[0] = PA_INT;
*size = sizeof(bool);
}
return 1;
}
static int bool_printf(FILE *stream, const struct printf_info *info,
const void *const *args)
{
bool b = *(const bool*)(args[0]);
int r = fputs(b ? "true" : "false", stream);
return r == EOF ? -1 : (b ? 4 : 5);
}
static int setup_bool_specifier()
{
int r = register_printf_specifier('B', bool_printf, bool_arginfo);
return r;
}
int main(int argc, char **argv)
{
int r = setup_bool_specifier();
if (r) return 1;
bool b = argc > 1;
r = printf("The result is: %B\n", b);
printf("(written %d characters)\n", r);
return 0;
}
Since it is a glibc extensions the GCC warns about that custom specifier:
$ gcc -Wall -g main.c -o main main.c: In function ‘main’: main.c:34:3: warning: unknown conversion type character ‘B’ in format [-Wformat=] r = printf("The result is: %B\n", b); ^ main.c:34:3: warning: too many arguments for format [-Wformat-extra-args]
Output:
$ ./main The result is: false (written 21 characters) $ ./main 1 The result is: true (written 20 characters)
If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:
public void doStuff() throws MyException {
try {
//Stuff
} catch(StuffException e) {
throw new MyException();
}
}
And now your compiler will not yell at you :)
Double check if you have set and initial value for int and decimal values to be printed.
This sample is printing an empty line
declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)
And this sample is printing -> The number is : 1
declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)
In Ubuntu 20.04, PHP 7.4 use the following command:
sudo apt-get install php7.4-intl
replace 7.4 with your PHP version
directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
This post is a bit old so could be there was a bug andit was fixed, but I just did this:
git --work-tree=/X/Y --git-dir=/X/Y/.git pull origin branch
And it worked. Took me a minute to figure out that it wanted the dotfile and the parent directory (in a standard setup those are always parent/child but not in ALL setups, so they need to be specified explicitly.
getcwd()
(documentation)$_SERVER['DOCUMENT_ROOT']
$_SERVER['SCRIPT_FILENAME']
Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:
<!-- <content> blah </content> -->
You can take two approaches here:
Be careful.
I am also not so sure you can match all new lines at once. @Quartz suggested this one:
<content>([^\n]*\n+)+</content>
This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:
<content>.*</content>
BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.
I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.
I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...
UPDATE 1:
Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):
To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.
Similarly, to search for content tags, use: .*?
Also, You may be able to try this out, and access each newline character with the match objects groups():
<content>(.*?(\n))+.*?</content>
I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.
UPDATE 2:
So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:
#!/usr/bin/python
import re
def FindContentNewlines(xml_text):
# May want to compile these regexes elsewhere, but I do it here for brevity
comments = re.compile(r"<!--.*?-->", re.DOTALL)
content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)
# strip comments: this actually may not be reliable for "nested comments"
# How does xml handle <!-- <!-- --> -->. I am not sure. But that COULD
# be trouble.
xml_text = re.sub(comments, "", xml_text)
result = []
all_contents = re.findall(content, xml_text)
for c in all_contents:
result.extend(re.findall(newlines, c))
return result
if __name__ == "__main__":
example = """
<!-- This stuff
ought to be omitted
<content>
omitted
</content>
-->
This stuff is good
<content>
<p>
haha!
</p>
</content>
This is not found
"""
print FindContentNewlines(example)
This program prints the result:
['', '<p>', ' haha!', '</p>', '']
The first and last empty strings come from the newline chars immediately preceeding the first <p>
and the one coming right after the </p>
. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.
Hope this helps :-).
PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
We can use params
, new feature of the UI-Router:
API Reference / ui.router.state / $stateProvider
params
A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.
See the part: "...or defines additional non-url parameters..."
So the state def would be:
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
params: { hiddenOne: null, }
})
Few examples form the doc mentioned above:
// define a parameter's default value
params: {
param1: { value: "defaultValue" }
}
// shorthand default values
params: {
param1: "defaultValue",
param2: "param2Default"
}
// param will be array []
params: {
param1: { array: true }
}
// handling the default value in url:
params: {
param1: {
value: "defaultId",
squash: true
} }
// squash "defaultValue" to "~"
params: {
param1: {
value: "defaultValue",
squash: "~"
} }
EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info
Here is an example of a state definition:
$stateProvider
.state('home', {
url: "/home",
params : { veryLongParamHome: null, },
...
})
.state('parent', {
url: "/parent",
params : { veryLongParamParent: null, },
...
})
.state('parent.child', {
url: "/child",
params : { veryLongParamChild: null, },
...
})
This could be a call using ui-sref:
<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
})">home</a>
<a ui-sref="parent({
veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
})">parent</a>
<a ui-sref="parent.child({
veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',
veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
})">parent.child</a>
Check the example here
It would be something like this
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
Then you can call the function similar to this.
$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null )
{
echo "Input was [$userInput]"
}
else
{
echo "User cancelled the form!"
}
This is the most simple way to do this that I can think of.
This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php
And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2
I haven't tried either method, but this may save you some time if it's what you need to do...
Your project supports .Net Framework 4.0 and .Net Framework 4.5. If you have upgrade issues
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
instead of can use;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
You can get the url like this:
Request.Headers["Referer"]
Explanation
The Request.UrlReferer
will throw a System.UriFormatException
if the referer HTTP header is malformed (which can happen since it is not usually under your control).
As for using Request.ServerVariables
, per MSDN:
Request.ServerVariables Collection
The ServerVariables collection retrieves the values of predetermined environment variables and request header information.
Request.Headers Property
Gets a collection of HTTP headers.
I guess I don't understand why you would prefer the Request.ServerVariables
over Request.Headers
, since Request.ServerVariables
contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.
So the best solution is to use the Request.Headers
collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.
I just fix this problem in my project-
CSS code
.scroll-menu{
min-width: 220px;
max-height: 90vh;
overflow: auto;
}
HTML code
<ul class="dropdown-menu scroll-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Action</a></li>
..
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
</ul>
You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.
If you are working with MVVM Light you have to use the System.Windows.Interactivity Version 4.0
(the NuGet .dll wont work) that you can find under :
PathToProjectFolder\Software\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll
Just add this .dll manually as Reference and it should be fine.
You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py
the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!
You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?
Here is a UITableView extension with Swift 5:
import UIKit
extension UITableView
{
func updateRow(row: Int, section: Int = 0)
{
let indexPath = IndexPath(row: row, section: section)
self.beginUpdates()
self.reloadRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
self.endUpdates()
}
}
Call with
self.tableView.updateRow(row: 1)
(in answer to the second question) By only using a sign bit (and not 2's complement), you can end up with -0. Not very pretty.
I use
\pagenumbering{roman}
for everything in the frontmatter and then switch over to
\pagenumbering{arabic}
for the actual content. With pdftex, the page numbers come out right in the PDF file.
SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.
If anyone like me is searching to read only a specific line, example only line 18 here is the code:
filename = "C:\log.log"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
For i = 1 to 17
f.ReadLine
Next
strLine = f.ReadLine
Wscript.Echo strLine
f.Close
Without plugin cross browser with setInterval:
function rotatePic() {
jQuery({deg: 0}).animate(
{deg: 360},
{duration: 3000, easing : 'linear',
step: function(now, fx){
jQuery("#id").css({
'-moz-transform':'rotate('+now+'deg)',
'-webkit-transform':'rotate('+now+'deg)',
'-o-transform':'rotate('+now+'deg)',
'-ms-transform':'rotate('+now+'deg)',
'transform':'rotate('+now+'deg)'
});
}
});
}
var sec = 3;
rotatePic();
var timerInterval = setInterval(function() {
rotatePic();
sec+=3;
if (sec > 30) {
clearInterval(timerInterval);
}
}, 3000);
Use the keyword next
. If you do not want to continue to the next item, use break
.
When next
is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:
f.each do |line| # Iterate over the lines in file f
next if line[0,1] == "#" # If this line is a comment, go to the next
puts eval(line)
end
When used in a block, break
transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:
f.each do |line| # Iterate over the lines in file f
break if line == "quit\n" # If this break statement is executed...
puts eval(line)
end
puts "Good bye" # ...then control is transferred here
And finally, the usage of return
in a block:
return
always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):
def find(array, target)
array.each_with_index do |element,index|
return index if (element == target) # return from find
end
nil # If we didn't find the element, return nil
end
a version similar to C. Dragon's, but for if you only need a single replacement:
int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);
if (n >= 0)
{
myText = myText.Substring(0, n)
+ newValue
+ myText.Substring(n + oldValue.Length);
}
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"_x000D_
_x000D_
let output = str.replace(/\?.+/g,"$'")_x000D_
_x000D_
console.log(output)
_x000D_
HTML
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 option2">
<p>left column </p>
<p>The first column has to be the longest The first column has to be the longes</p>
</div>
<div class="span4 option2">
<p>middle column</p>
</div>
<div class="span4 option2">
<p>right column </p>
<p>right column </p>
<p>right column </p>
<p>right column </p>
<p>right column </p>
</div>
</div>
</div>
CSS
.option2 { background: red; border: black 1px solid; color: white; }
JS
$('.option2').css({
'height': $('.option2').height()
});
I'm having the same problem with Wampserver. It’s worked for me:
You must change this file: "C:\wamp\bin\mysql[mysql_version]\my.ini" For example: "C:\wamp\bin\mysql[mysql5.6.12]\my.ini"
And change default port 3306 to 80. (Lines 20 & 27, in both)
port = 3306 To port = 80
I hope this is helpful.
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>
If you need simply scroll page to top, you can do this (not the best solution, but fast)
document.getElementById('elementId').scrollTop = 0;
The answer is: It depends.
Although base64-images are larger, there a few conditions where base64 is the better choice.
Size of base64-images
Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.
Example:
An 48kb image needs around 64kb as base64 converted image.
Calculation: (48 / 6) * 8 = 64
Simple CLI calculator on Linux systems:
$ cat /dev/urandom|head -c 48000|base64|wc -c
64843
Or using an image:
$ cat my.png|base64|wc -c
Base64-images and websites
This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:
This VBA code will refresh all pivot tables/charts in the workbook.
Sub RefreshAllPivotTables()
Dim PT As PivotTable
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
For Each PT In WS.PivotTables
PT.RefreshTable
Next PT
Next WS
End Sub
Another non-programatic option is:
This will refresh the pivot table each time the workbook is opened.
The object viewer in Acrobat is good but Windjack Solution's PDF Canopener allows better inspection with an eyedropper for selecting objects on page. Also permits modifications to be made to PDF.
You can present the buttons like this:
<input type="submit" name="typeBtn" value="BUY">
<input type="submit" name="typeBtn" value="SELL">
And then in the code you can get the value using:
if request.method == 'POST':
#valUnits = request.POST.get('unitsInput','')
#valPrice = request.POST.get('priceInput','')
valType = request.POST.get('typeBtn','')
(valUnits and valPrice are some other values I extract from the form that I left in for illustration)
In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.
If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.
If you want to search for multilines by the character literal, remember to check the rightmost regex icon.
In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.
Update : STYLE GUIDE is now on Angular docs.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.
The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.
- John Papa
Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide
This is for those who want to overwrite the column cells quickly (without cutting and copying). This is the same as double-clicking the cell box but unlike double-clicking, it still works after the first try.
BONUS:
The shortcut for going to the bottom-most content (to double-check the copy) is Ctrl+⇓. To go back up you can use Ctrl+⇑ but if your top rows are frozen you'll also have to press Enter a few times.
verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"
enter code here
print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.
Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..
Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)
The warning appears only because the demo code has:
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}> // <==NOTE P TAG HERE
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
Changing it like this takes care of it:
function TabPanel(props) {
const {children, value, index, classes, ...other} = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Container>
<Box> // <== P TAG REMOVED
{children}
</Box>
</Container>
)}
</div>
);
}
you can also see many examples in R cookbook
olddata_wide <- read.table(header=TRUE, text='
subject sex control cond1 cond2
1 M 7.9 12.3 10.7
2 F 6.3 10.6 11.1
3 F 9.5 13.1 13.8
4 M 11.5 13.4 12.9
')
# Make sure the subject column is a factor
olddata_wide$subject <- factor(olddata_wide$subject)
olddata_long <- read.table(header=TRUE, text='
subject sex condition measurement
1 M control 7.9
1 M cond1 12.3
1 M cond2 10.7
2 F control 6.3
2 F cond1 10.6
2 F cond2 11.1
3 F control 9.5
3 F cond1 13.1
3 F cond2 13.8
4 M control 11.5
4 M cond1 13.4
4 M cond2 12.9
')
# Make sure the subject column is a factor
olddata_long$subject <- factor(olddata_long$subject)
Less than or equal:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than. You can find them all in the documentation.
You basically need to run the installation again to rebuild the master
database with the new collation. You cannot change the entire server's collation any other way.
See:
Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:
SELECT name, collation_name
FROM sys.databases
WHERE name = 'test2' -- put your database name here
This will yield a value something like:
Latin1_General_CI_AS
The _CI
means "case insensitive" - if you want case-sensitive, use _CS
in its place:
Latin1_General_CS_AS
So your T-SQL command would be:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
You can get a list of all available collations on the server using:
SELECT * FROM ::fn_helpcollations()
You can see the server's current collation using:
SELECT SERVERPROPERTY ('Collation')
Don't delete the folder or you will create a registry problem. However, if you do not want to use IIS, search the web for turning it off. You might want to check out "www.blackviper.com" because he lists all Operating System "services" (Not "Computer Services" - both are in Administrator Tools) with extra information for what you can and cannot disable to change to manual. If I recall correctly, he had some IIS info and how to turn it off.
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
Here is my full code using tag from remote search. Hope this is helpful.
$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/api/all_cities.php',
type: 'GET',
dataType: 'json',
data: {
name: query,
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
onInitialize: function(){
var selectize = this;
$.get("/api/selected_cities.php", function( data ) {
selectize.addOption(data); // This is will add to option
var selected_items = [];
$.each(data, function( i, obj) {
selected_items.push(obj.id);
});
selectize.setValue(selected_items); //this will set option values as default
});
}
});
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
I have found this answer https://stackoverflow.com/a/47107135/3067148 also very helpful:
gradle dependencies
will list the dependencies and download them as a side-effect.
For Error: 'opts' is deprecated
. Use theme()
instead. (Defunct; last used in version 0.9.1)'
I replaced opts(title = "Boxplot - Candidate's Tweet Scores")
with
labs(title = "Boxplot - Candidate's Tweet Scores")
. It worked!
I rely on JScript. I have a JScript file like this:
// This is sleep.js
WScript.Sleep( WScript.Arguments( 0 ) );
And inside a batch file I run it with CScript (usually it is %SystemRoot%\system32\cscript.exe
)
rem This is the calling inside a BAT file to wait for 5 seconds
cscript /nologo sleep.js 5000
Is this role attribute necessary?
Answer: Yes.
It provides you:
I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).
Code is here: http://codepen.io/SimeonC/pen/AJIyC
Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/
I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:
tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */
They both function in exactly the same way (in the context of HTML tables anyway) as:
tr:not(:first-child)
You can reset the root password by running the server with --skip-grant-tables
and logging in without a password by running the following as root (or with sudo):
# service mysql stop
# mysqld_safe --skip-grant-tables &
$ mysql -u root
mysql> use mysql;
mysql> update user set authentication_string=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
# service mysql stop
# service mysql start
$ mysql -u root -p
Now you should be able to login as root with your new password.
It is also possible to find the query that reset the password in /home/$USER/.mysql_history
or /root/.mysql_history
of the user who reset the password, but the above will always work.
Note: prior to MySQL 5.7 the column was called password
instead of authentication_string
. Replace the line above with
mysql> update user set password=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
Add this to the end of your code...
and call startTimer function with a parameter of where you want to count down to...
For example (2 hours to the future of the date right now) -> startTimer(for: Date().addingTimeInterval(60*60*2))
Click here to view a screenshot of iPhone Simulator of how it'll look
extension ViewController
{
func startTimer(for theDate: String)
{
let todaysDate = Date()
let tripDate = Helper.getTripDate(forDate: theDate)
let diffComponents = Calendar.current.dateComponents([.hour, .minute], from: Date(), to: tripDate)
if let hours = diffComponents.hour
{
hoursLeft = hours
}
if let minutes = diffComponents.minute
{
minutesLeft = minutes
}
if tripDate > todaysDate
{
timer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
}
else
{
timerLabel.text = "00:00:00"
}
}
@objc func onTimerFires()
{
secondsLeft -= 1
//timerLabel.text = "\(hoursLeft):\(minutesLeft):\(secondsLeft)"
timerLabel.text = String(format: "%02d:%02d:%02d", hoursLeft, minutesLeft, secondsLeft)
if secondsLeft <= 0 {
if minutesLeft != 0
{
secondsLeft = 59
minutesLeft -= 1
}
}
if minutesLeft <= 0 {
if hoursLeft != 0
{
minutesLeft = 59
hoursLeft -= 1
}
}
if(hoursLeft == 0 && minutesLeft == 0 && secondsLeft == 0)
{
timer.invalidate()
}
}
}
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.
CREATE TABLE contacts
(contact_id BIGINT AUTO_INCREMENT NOT NULL,
name VARCHAR(75) NOT NULL,
PRIMARY KEY(contact_id)) ENGINE = InnoDB;
CREATE TABLE phone_numbers
(phone_id BIGINT AUTO_INCREMENT NOT NULL,
phone_number CHAR(10) NOT NULL,
contact_id BIGINT NOT NULL,
PRIMARY KEY(phone_id),
UNIQUE(phone_number)) ENGINE = InnoDB;
ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;
By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.
INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);
Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.
DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */
To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.
<?php
namespace Entities;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @Entity
* @Table(name="contacts")
*/
class Contact
{
/**
* @Id
* @Column(type="integer", name="contact_id")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string", length="75", unique="true")
*/
protected $name;
/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
*/
protected $phonenumbers;
public function __construct($name=null)
{
$this->phonenumbers = new ArrayCollection();
if (!is_null($name)) {
$this->name = $name;
}
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function addPhonenumber(Phonenumber $p)
{
if (!$this->phonenumbers->contains($p)) {
$this->phonenumbers[] = $p;
$p->setContact($this);
}
}
public function removePhonenumber(Phonenumber $p)
{
$this->phonenumbers->remove($p);
}
}
<?php
namespace Entities;
/**
* @Entity
* @Table(name="phonenumbers")
*/
class Phonenumber
{
/**
* @Id
* @Column(type="integer", name="phone_id")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string", length="10", unique="true")
*/
protected $number;
/**
* @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
* @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
*/
protected $contact;
public function __construct($number=null)
{
if (!is_null($number)) {
$this->number = $number;
}
}
public function setPhonenumber($number)
{
$this->number = $number;
}
public function setContact(Contact $c)
{
$this->contact = $c;
}
}
?>
<?php
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$contact = new Contact("John Doe");
$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1);
$contact->addPhonenumber($phone2);
$em->persist($contact);
try {
$em->flush();
} catch(Exception $e) {
$m = $e->getMessage();
echo $m . "<br />\n";
}
If you now do
# doctrine orm:schema-tool:create --dump-sql
you will see that the same SQL will be generated as in the first, raw-SQL example
Actually it's a bug and nobody found a workaround so far. An issue has been created. The bug is still here in honeycomb.
Please star it if you think it's important : http://code.google.com/p/android/issues/detail?id=14749
You can add any php file in under your active themes folder like (/wp-content/themes/your_active_theme/) and then you can go to add new page from wp-admin and select this page template from page template options.
<?php
/*
Template Name: Your Template Name
*/
?>
And there is one other way like you can include your file in functions.php and create shortcode from that and then you can put that shortcode in your page like this.
// CODE in functions.php
function abc(){
include_once('your_file_name.php');
}
add_shortcode('abc' , 'abc');
And then you can use this shortcode in wp-admin side page like this [abc].
You can write a simple readable solution to this by using both map
and filter
:
const nanoIndexes = Cars
.map((car, i) => car === 'Nano' ? i : -1)
.filter(index => index !== -1);
EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:
const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);
actually you should only put in-line elements inside the p
, so in your case ol
is better outside
Depending on your use case, instead of using a case statement, you can use the union of multiple select statements, one for each condition.
My goal when I found this question was to select multiple columns conditionally. I didn't necessarily need the case statement, so this is what I did.
For example:
SELECT
a1,
a2,
a3,
...
WHERE <condition 1>
AND (<other conditions>)
UNION
SELECT
b1,
b2,
b3,
...
WHERE <condition 2>
AND (<other conditions>)
UNION
SELECT
...
-- and so on
Be sure that exactly one condition evaluates to true at a time.
I'm using Postgresql, and the query planner was smart enough to not run a select statement at all if the condition in the where clause evaluated to false (i.e. only one of the select statement actually runs), so this was also performant for me.
Based on @Dirk's and @Tony's answer I have made a slight update. The result was outputting [1]
before the pretty size values, so I took out the capture.output
which solved the problem:
.ls.objects <- function (pos = 1, pattern, order.by,
decreasing=FALSE, head=FALSE, n=5) {
napply <- function(names, fn) sapply(names, function(x)
fn(get(x, pos = pos)))
names <- ls(pos = pos, pattern = pattern)
obj.class <- napply(names, function(x) as.character(class(x))[1])
obj.mode <- napply(names, mode)
obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
obj.prettysize <- napply(names, function(x) {
format(utils::object.size(x), units = "auto") })
obj.size <- napply(names, utils::object.size)
obj.dim <- t(napply(names, function(x)
as.numeric(dim(x))[1:2]))
vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
obj.dim[vec, 1] <- napply(names, length)[vec]
out <- data.frame(obj.type, obj.size, obj.prettysize, obj.dim)
names(out) <- c("Type", "Size", "PrettySize", "Rows", "Columns")
if (!missing(order.by))
out <- out[order(out[[order.by]], decreasing=decreasing), ]
if (head)
out <- head(out, n)
return(out)
}
# shorthand
lsos <- function(..., n=10) {
.ls.objects(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}
lsos()
import React, { useState } from 'react';
function App() {
const [apes , setap] = useState('yo');
const handleClick = () =>{
setap(document.getElementById('name').value)
};
return (
<div>
<input id='name' />
<h2> {apes} </h2>
<button onClick={handleClick} />
</div>
);
}
export default App;
In Sql Server:
insert into Table_Name(PersonName,PersonEmail) values(NULL,'[email protected]')
PersonName is varchar(50), NULL is not a string, because we are not passing with in single codes, so it treat as NULL.
Code Behind:
string name = (txtName.Text=="")? NULL : "'"+ txtName.Text +"'";
string email = txtEmail.Text;
insert into Table_Name(PersonName,PersonEmail) values(name,'"+email+"')
If you're running a CentOS container, you can install ps using this command:
yum install -y procps
Running this command on Dockerfile:
RUN yum install -y procps
you can make an array like:
s = np.arange(0, len(a), 1)
then shuffle it:
np.random.shuffle(s)
now use this s as argument of your arrays. same shuffled arguments return same shuffled vectors.
x_data = x_data[s]
x_label = x_label[s]
If you're trying to print a specific register in GDB, you have to omit the % sign. For example,
info registers eip
If your executable is 64 bit, the registers start with r. Starting them with e is not valid.
info registers rip
Those can be abbreviated to:
i r rip
Although it seems that in most cases it's enough to have onAttach(Context)
, there are some phones (i.e: Xiaomi Redme Note 2) where it's not being called, thus it causes NullPointerExceptions. So to be on the safe side I suggest to leave the deprecated method as well:
// onAttach(Activity) is necessary in some Xiaomi phones
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
_onAttach(activity);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
_onAttach(context);
}
private void _onAttach(Context context) {
// do your real stuff here
}
Not necessary to use \restylefloat
and destroys other options, like caption placement. just use [H]
or [!h]
after \begin{table}
.
There are codes for other space characters, and the codes as such work well, but the characters themselves are legacy character. They have been included into character sets only due to their presence in existing character data, rather than for use in new documents. For some combinations of font and browser version, they may cause a generic glyph of unrepresentable character to be shown. For details, check my page about Unicode spaces.
So using CSS is safer and lets you specify any desired amount of spacing, not just the specific widths of fixed-width spaces. If you just want to have added spacing around your h2 elements, as it seems to me, then setting padding on those elements (changing the value of the padding: 0 settings that you already have) should work fine.
Be aware of an issue with sparse unique indexes in MongoDB. I've hit it and it is extremely cumbersome to workaround.
The problem is this - you have a field, which is unique if present and you wish to find all the objects where the field is absent. The way sparse unique indexes are implemented in Mongo is that objects where that field is missing are not in the index at all - they cannot be retrieved by a query on that field - {$exists: false}
just does not work.
The only workaround I have come up with is having a special null family of values, where an empty value is translated to a special prefix (like null:) concatenated to a uuid. This is a real headache, because one has to take care of transforming to/from the empty values when writing/quering/reading. A major nuisance.
I have never used server side javascript execution in MongoDB (it is not advised anyway) and their map/reduce has awful performance when there is just one Mongo node. Because of all these reasons I am now considering to check out CouchDB, maybe it fits more to my particular scenario.
BTW, if anyone knows the link to the respective Mongo issue describing the sparse unique index problem - please share.
Here is a custom function that mimic's Matlab's/Octave's tic
toc
functions.
Example of use:
time_var = time_me(); # get a variable with the current timestamp
... run operation ...
time_me(time_var); # print the time difference (e.g. '5 seconds 821.12314 ms')
Function :
def time_me(*arg):
if len(arg) != 0:
elapsedTime = time.time() - arg[0];
#print(elapsedTime);
hours = math.floor(elapsedTime / (60*60))
elapsedTime = elapsedTime - hours * (60*60);
minutes = math.floor(elapsedTime / 60)
elapsedTime = elapsedTime - minutes * (60);
seconds = math.floor(elapsedTime);
elapsedTime = elapsedTime - seconds;
ms = elapsedTime * 1000;
if(hours != 0):
print ("%d hours %d minutes %d seconds" % (hours, minutes, seconds))
elif(minutes != 0):
print ("%d minutes %d seconds" % (minutes, seconds))
else :
print ("%d seconds %f ms" % (seconds, ms))
else:
#print ('does not exist. here you go.');
return time.time()
This topic is old but if other people like me search a solution, this is a solution that I have found:
Public Function DBStats() As Boolean
On Error GoTo errorHandler
If Not IsNull(myBase.Version) Then
DBStats = True
End If
Exit Function
errorHandler:
DBStats = False
End Function
So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":
Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false
Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false
I was also breaking my head for a long time with this error message and later I identified that I was using [datasource] instead of [dataSource].
The answer to this one is actually wrong.
Auto filling in the value (auto_now/auto_now_add isn't the same as default). The default value will actually be what the user sees if its a brand new object. What I typically do is:
date = models.DateTimeField(default=datetime.now, editable=False,)
Make sure, if your trying to represent this in an Admin page, that you list it as 'read_only' and reference the field name
read_only = 'date'
Again, I do this since my default value isn't typically editable, and Admin pages ignore non-editables unless specified otherwise. There is certainly a difference however between setting a default value and implementing the auto_add which is key here. Test it out!
You need to right-click on res->new->Android resource directory. Make sure you select directory and not file.
Select raw in resource type and it automatically selects raw as the directory name.
Drag and drop your .mp3 music file inside the res folder. Make sure that it starts with a small letter.
How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.
As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.
(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).
def read_config(filename):
f = open(filename)
config_dict = {}
for lines in f:
items = lines.split(': ', 1)
config_dict[items[0]] = eval(items[1])
return config_dict
Extending Alex's answer slightly:
class User:
def __init__(self):
self.data = [1,2,3]
self.other_data = [4,5,6]
def doSomething(self, source):
dataSource = getattr(self,source)
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
will yield:
[1, 2, 3] [4, 5, 6]
However, personally I don't think that's great style - getattr
will let you access any attribute of the instance, including things like the doSomething
method itself, or even the __dict__
of the instance. I would suggest that instead you implement a dictionary of data sources, like so:
class User:
def __init__(self):
self.data_sources = {
"data": [1,2,3],
"other_data":[4,5,6],
}
def doSomething(self, source):
dataSource = self.data_sources[source]
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
again yielding:
[1, 2, 3] [4, 5, 6]
Try doing:
RecyclerView v = (RecyclerView) findViewById(...);
v.setNestedScrollingEnabled(false);
As an alternative, you can modify your layout using the support design library. I guess your current layout is something like:
<ScrollView >
<LinearLayout >
<View > <!-- upper content -->
<RecyclerView > <!-- with custom layoutmanager -->
</LinearLayout >
</ScrollView >
You can modify that to:
<CoordinatorLayout >
<AppBarLayout >
<CollapsingToolbarLayout >
<!-- with your content, and layout_scrollFlags="scroll" -->
</CollapsingToolbarLayout >
</AppBarLayout >
<RecyclerView > <!-- with standard layoutManager -->
</CoordinatorLayout >
However this is a longer road to take, and if you are OK with the custom linear layout manager, then just disable nested scrolling on the recycler view.
The v 23.2
release of the support libraries now includes a factory “wrap content” feature in all default LayoutManager
s. I didn’t test it, but you should probably prefer it to that library you were using.
<ScrollView >
<LinearLayout >
<View > <!-- upper content -->
<RecyclerView > <!-- with wrap_content -->
</LinearLayout >
</ScrollView >
The following was tested for IIS 8.5 and Windows 8.1.
As of IIS 7, Windows recommends restarting IIS via net stop/start
. Via the command prompt (as Administrator):
> net stop WAS
> net start W3SVC
net stop WAS
will stop W3SVC
as well. Then when starting, net start W3SVC
will start WAS
as a dependency.
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
There are two other "quick and easy" ways to accomplish it without a plugin:
Make it a shortcode (put it in functions.php
and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
If you want to do binary, give a --binary
option when you run git diff
.
Compare the length using lengthB and length function in oracle.
SELECT * FROM test WHERE length(sampletext) <> lengthb(sampletext)
From what I can see FOR XML
(as posted earlier) is the only way to do it if you want to also select other columns (which I'd guess most would) as the OP does.
Using COALESCE(@var...
does not allow inclusion of other columns.
Update:
Thanks to programmingsolutions.net there is a way to remove the "trailing" comma to.
By making it into a leading comma and using the STUFF
function of MSSQL you can replace the first character (leading comma) with an empty string as below:
stuff(
(select ',' + Column
from Table
inner where inner.Id = outer.Id
for xml path('')
), 1,1,'') as Values
I just had to face the same kind of issue with my Laravel 7 project, in Debian 10 shared hosting. I have to add RewriteBase /
to my .htaccess within /public/ directory. So the .htaccess looks a like
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
jQuery have special function isEmptyObject()
for this case:
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
Read more on http://api.jquery.com/jQuery.isEmptyObject/
You can always use an attribute selector. The selector itself would look something like:
a[data-item-id=stand-out]
Try setting core.autocrlf value like this :
git config --global core.autocrlf true
I had to add one more line to REVOKE...
After running:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
I was still receiving the error: username cannot be dropped because some objects depend on it DETAIL: privileges for schema public
I was missing this:
REVOKE USAGE ON SCHEMA public FROM username;
Then I was able to drop the role.
DROP USER username;
For my case, the exception was raised because I tried to mock a package-access
method. When I changed the method access level from package
to protected
the exception went away. E.g. inside below Java class,
public class Foo {
String getName(String id) {
return mMap.get(id);
}
}
the method String getName(String id)
has to be AT LEAST protected
level so that the mocking mechanism (sub-classing) can work.
Comparison expressions should each be in their own brackets:
{% if (a == 'foo') or (b == 'bar') %}
...
{% endif %}
Alternative if you are inspecting a single variable and a number of possible values:
{% if a in ['foo', 'bar', 'qux'] %}
...
{% endif %}
You want to grab the value of the first option in the select element.
$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
You should set signatureVersion: 'v4'
in config
to use new sign version:
AWS.config.update({
signatureVersion: 'v4'
});
Works for JS
sdk.
If I understand what you are asking, it is a regular expression like this:
^(8768|9875|2353)
This matches the three sets of digit strings at beginning of line only.
To those that are incline to use GUI:
Click Right mouse button on procecdure name then select Test
Then in new window you will see script generated just add the parameters and click on Start Debugger
or F9
Hope this saves you some time.
If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
nickh@SCLLNHENRY:~/Work/standingcloud/svn/main/trunk/dev/scripts$ svnversion
12354
Or
nickh@SCLLNHENRY:~/Work/standingcloud/svn/main/trunk/dev/scripts$ svn info --xml | xmlstarlet sel -t --value-of "//entry/@revision"
12354
Or
nickh@SCLLNHENRY:~/Work/standingcloud/svn/main/trunk/dev/scripts$ svn info --xml | xmlstarlet sel -t --value-of "//commit/@revision"
12335
You can try this:
Hope it works for you..
`private void validateUserEntry()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}`
Simply you can find index name and column names of a particular table using below command
SP_HELPINDEX 'tablename'
It work's for me
In the end I found out that no apps were being installed successfully, not just mine. I set the Install App default from SD card to Automatic. That fixed it.
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
It's all a perceptual thing. Git is generally rather good at recognising moves, because GIT is a content tracker
All that really depends is how your "stat" displays it. The only difference here is the -M flag.
git log --stat -M
commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date: Fri Jan 9 22:13:51 2009 +1300
Category Restructure
lib/Gentoo/Repository.pm | 10 +++++-----
lib/Gentoo/{ => Repository}/Base.pm | 2 +-
lib/Gentoo/{ => Repository}/Category.pm | 12 ++++++------
lib/Gentoo/{ => Repository}/Package.pm | 10 +++++-----
lib/Gentoo/{ => Repository}/Types.pm | 10 +++++-----
5 files changed, 22 insertions(+), 22 deletions(-)
git log --stat
commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date: Fri Jan 9 22:13:51 2009 +1300
Category Restructure
lib/Gentoo/Base.pm | 36 ------------------------
lib/Gentoo/Category.pm | 51 ----------------------------------
lib/Gentoo/Package.pm | 41 ---------------------------
lib/Gentoo/Repository.pm | 10 +++---
lib/Gentoo/Repository/Base.pm | 36 ++++++++++++++++++++++++
lib/Gentoo/Repository/Category.pm | 51 ++++++++++++++++++++++++++++++++++
lib/Gentoo/Repository/Package.pm | 41 +++++++++++++++++++++++++++
lib/Gentoo/Repository/Types.pm | 55 +++++++++++++++++++++++++++++++++++++
lib/Gentoo/Types.pm | 55 -------------------------------------
9 files changed, 188 insertions(+), 188 deletions(-)
git help log
-M
Detect renames.
-C
Detect copies as well as renames. See also --find-copies-harder.
I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.
Example is in here:
$(function () {
$('#CostAnalysis input[type=radio]').click(function () {
var value = $(this).val();
if (value == "Supply & Lay") {
$('#ul-suplay').empty();
$('#ul-suplay').append('<fieldset data-role="controlgroup"> \
Select Java editor settings for Intellij Select values for Tabsize, Indent & Continuation Intent (I choose 4,4 & 4)
Then Ctrl + Alt + L to format your file (or your selection).
According to your CSS file path, I will suppose it is at the same directory with your HTML page, you have to change the url
as follows:
body { background: url(img/debut_dark.png) repeat 0 0; }
I had a similar issue - very slow xml downloads followed by an empty package list. The SDK, it seems, was trying to use legacy Java installation. Setting the JAVA_HOME to the 1.6 jdk did the trick.
MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-
SHOW INDEXES FROM products \G
It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -
*************************** 1. row ***************************
Table: products
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: product_id
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
To just display primary key from the table use :-
SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'
Here is one version that works with filenames that may contain spaces, newlines, and glob characters as well:
find . -type f -printf "%T@ %p\0" | sort -zk1nr
find ... -printf
prints the file modification time (Epoch value) followed by a space and \0
terminated filenames.sort -zk1nr
reads NUL terminated data and sorts it reverse numericallyAs the question is tagged with Linux, I am assuming GNU Core Utilities are available.
You can pipe the above with:
xargs -0 printf "%s\n"
to print the modification time and filenames sorted by modification time (most recent first) terminated by newlines.
Try this
var div = document.getElementById("test");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
alert(spans[i].innerHTML);
}
I had the same issue and it is very easy to implement.
All you have to do is wrap your EditText field in a (com.google.android.material.textfield.TextInputLayout) and in that add ( app:passwordToggleEnabled="true" ).
This will show the eye in the EditText field and when you click on it the password will appear and disappear when clicked again.
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColorHint="#B9B8B8"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/register_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginRight="44dp"
android:backgroundTint="#BEBEBE"
android:hint="Password"
android:inputType="textPassword"
android:padding="16dp"
android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>
If you are serializing your data object, it will not be a proper json object. Take what you have, and just wrap the data object in a JSON.stringify()
.
$http({
url: '/user_to_itsr',
method: "POST",
data: JSON.stringify({application:app, from:d1, to:d2}),
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
$scope.users = data.users; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
});
Machines don't understand English or any other languages, they understand only byte code, which they have to be compiled (e.g., C/C++, Java) or interpreted (e.g., Ruby, Python), the .pyc is a cached version of the byte code. https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/ Here is a quick read on what is the difference between compiled language vs interpreted language, TLDR is interpreted language does not require you to compile all the code before run time and thus most of the time they are not strict on typing etc.
I also prefer decorator syntax to deriving from metaclass. My two cents:
from typing import Callable, Dict, Set
def singleton(cls_: Callable) -> type:
""" Implements a simple singleton decorator
"""
class Singleton(cls_): # type: ignore
__instances: Dict[type, object] = {}
__initialized: Set[type] = set()
def __new__(cls, *args, **kwargs):
if Singleton.__instances.get(cls) is None:
Singleton.__instances[cls] = super().__new__(cls, *args, **kwargs)
return Singleton.__instances[cls]
def __init__(self, *args, **kwargs):
if self.__class__ not in Singleton.__initialized:
Singleton.__initialized.add(self.__class__)
super().__init__(*args, **kwargs)
return Singleton
@singleton
class MyClass(...):
...
This has some benefits above other decorators provided:
isinstance(MyClass(), MyClass)
will still work (returning a function from the clausure instead of a class will make isinstance to fail)property
, classmethod
and staticmethod
will still work as expected__init__()
constructor is executed only onceCons:
print(MyClass().__class__.__name__)
will return Singleton
instead od MyClass
. If you still need this, I recommend using a metaclass as suggested above.If you need a different instance based on constructor parameters this solution needs to be improved (solution provided by siddhesh-suhas-sathe provides this).
Finally, as other suggested, consider using a module in python. Modules are objects. You can even pass them in variables and inject them in other classes.
For future googlers, FYI, the method in the answer by @meder , can be used with any element that has a name attribute, so lets say theres an <iframe>
with the name xyz
then you can use the rule as belows.
iframe[name=xyz] {
display: none;
}
The name
attribute can be used on the following elements:
<button>
<fieldset>
<form>
<iframe>
<input>
<keygen>
<map>
<meta>
<object>
<output>
<param>
<select>
<textarea>
You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:
import numpy as np
csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")
# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))
which looks like this:
array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])
You can access a named column like this r['E']
:
array([1715.37476, 1715.37476, 1715.37476])
Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.
I had the same need for conditional tests, and I figured out a good workaround. I defined a macro TEST_C that works like a TEST_F macro, but it has a third parameter, which is a boolean expression, evaluated runtime in main.cpp BEFORE the tests are started. Tests that evaluate false are not executed. The macro is ugly, but it look like:
#pragma once
extern std::map<std::string, std::function<bool()> >* m_conditionalTests;
#define TEST_C(test_fixture, test_name, test_condition)\
class test_fixture##_##test_name##_ConditionClass\
{\
public:\
test_fixture##_##test_name##_ConditionClass()\
{\
std::string name = std::string(#test_fixture) + "." + std::string(#test_name);\
if (m_conditionalTests==NULL) {\
m_conditionalTests = new std::map<std::string, std::function<bool()> >();\
}\
m_conditionalTests->insert(std::make_pair(name, []()\
{\
DeviceInfo device = Connection::Instance()->GetDeviceInfo();\
return test_condition;\
}));\
}\
} test_fixture##_##test_name##_ConditionInstance;\
TEST_F(test_fixture, test_name)
Additionally, in your main.cpp, you need this loop to exclude the tests that evaluate false:
// identify tests that cannot run on this device
std::string excludeTests;
for (const auto& exclusion : *m_conditionalTests)
{
bool run = exclusion.second();
if (!run)
{
excludeTests += ":" + exclusion.first;
}
}
// add the exclusion list to gtest
std::string str = ::testing::GTEST_FLAG(filter);
::testing::GTEST_FLAG(filter) = str + ":-" + excludeTests;
// run all tests
int result = RUN_ALL_TESTS();
Make sure it is
public static void main(String[] argv)
No other signature will do.
Python is dynamic language so the IDE can do only so much in terms of code intelligence and syntax checking but I personally recommend Komode IDE, it's pretty slick on OS/X and Windows. I've experienced high cpu use with Linux but not sure if it's caused by my VirtualBox environment.
You can also try Eclipse with PyDev plugin. It's heavier so performance might become a problem though.
You could convert to string, right?
n = (n + "").split(".");
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers.
Convert style.scss
to style.css
set the arguments
--no-cache --update $FileName$:$FileNameWithoutExtension$.css
and output paths to refresh
$FileNameWithoutExtension$.css
Convert style.scss
to compressed style.min.css
set the arguments
--no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
and output paths to refresh
$FileNameWithoutExtension$.min.css
Add this code into the css file:
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
This will help.
environment.plst
file loads first on MAC so put the path on it.
For 1st time use, use the following command
export PATH=$PATH: /path/to/set
shared_ptr isn't large enough, nor do its constructor\destructor do enough work for there to be enough overhead from the copy to care about pass by reference vs pass by copy performance.
First
Make a dir c:\command
Second Make a ll.bat
ll.bat
dir
Use selectionStart
/selectionEnd
properties of the input element (works for <textarea>
as well)
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
It depends on your situation.
I would say, if your bool has a good name, then:
if (control.IsEnabled) // Read "If control is enabled."
{
}
would be preferred.
If, however, the variable has a not-so-obvious name, checking against true
would be helpful in understanding the logic.
if (first == true) // Read "If first is true."
{
}
Solution:
<form name="frmSeguimiento" id="frmSeguimiento" method="post" action="proc_seguimiento.php">
<input type="hidden" name="accion" id="accion"/>
<input name="save" type="image" src="imagenes/save.png" alt="Save" onmouseover="this.src='imagenes/save_over.png';" onmouseout="this.src='imagenes/save.png';" value="Save" onclick="validaFrmSeguimiento(this.value);"/>
function validaFrmSeguimiento(accion)
{
document.frmSeguimiento.accion.value=accion;
}
Regards, jp
You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.py
file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.
My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.
Use
"$filepath"_newstap.sh
or
${filepath}_newstap.sh
or
$filepath\_newstap.sh
_
is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap
.
You can use set -u
to make the shell exit with an error when you reference an undefined variable.
You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.
Here is the command:
version=1.2.3
artefact="myartefact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus
curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artefact-$version.tgz
If you are using Ant and trying to build then you need to :
Specify tomcat location by <property name="tomcat-home" value="C:\xampp\tomcat" />
Add tomcat libs to your already defined path for jars by
<path id="libs">
<fileset includes="*.jar" dir="${WEB-INF}/lib" />
<fileset includes="*.jar" dir="${tomcat-home}/bin" />
<fileset includes="*.jar" dir="${tomcat-home}/lib" />
</path>
check this if it works it works fine for me
<script>
var windowObjectReference;
var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";
function openRequestedPopup() {
windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
}
</script>
//get the main handle and remove it
//whatever remains is the child pop up window handle
String mainHandle = driver.getWindowHandle();
Set<String> allHandles = driver.getWindowHandles();
Iterator<String> iter = allHandles.iterator();
allHandles.remove(mainHandle);
String childHandle=iter.next();
You've declared the class Thing
as a non-static inner class. That means it must be associated with an instance of the Hello
class.
In your code, you're trying to create an instance of Thing
from a static context. That is what the compiler is complaining about.
There are a few possible solutions. Which solution to use depends on what you want to achieve.
Move Thing
out of the Hello
class.
Change Thing
to be a static
nested class.
static class Thing
Create an instance of Hello
before creating an instance of Thing
.
public static void main(String[] args)
{
Hello h = new Hello();
Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
}
The last solution (a non-static nested class) would be mandatory if any instance of Thing
depended on an instance of Hello
to be meaningful. For example, if we had:
public class Hello {
public int enormous;
public Hello(int n) {
enormous = n;
}
public class Thing {
public int size;
public Thing(int m) {
if (m > enormous)
size = enormous;
else
size = m;
}
}
...
}
any raw attempt to create an object of class Thing
, as in:
Thing t = new Thing(31);
would be problematic, since there wouldn't be an obvious enormous
value to test 31 against it. An instance h
of the Hello
outer class is necessary to provide this h.enormous
value:
...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...
Because it doesn't mean a Thing
if it doesn't have a Hello
.
For more information on nested/inner classes: Nested Classes (The Java Tutorials)
Start with:
find . -name '*.log.*.zip' -a -mtime +1
You may not need a regex, try:
find . -name '*.log.*-*-*.zip' -a -mtime +1
You will want the +1 in order to match 1, 2, 3 ...
I have also faced the same issue in recent past for me I have do the following commands one by one in terminal.
sudo npm uninstall -g angular-cli
sudo npm cache clean
After this run
ng -v
If still get angular-cli version 1.0.0-beta.2x.x then run the following command
which ng
It will show the ng path. Go to the path and if it is linked with any file remove the same the link and actual ng file. In my case the link is in /usr/bin/ng and actual path of ng file is /lib/node_modules/@angular/cli/bin/ng.
sudo rm -rf /lib/node_modules/@angular/cli/bin/ng
sudo rm -rf /usr/bin/ng
Next you need to install @angular/cli using
sudo npm install -g @angular/cli
Close all the terminal and run ng -v and you are on. May be it will help someone. Thanks :)
With current HTML5 it should be possible to calculate the md5 hash of a binary file, But I think the step before that would be to convert the banary data BlobBuilder to a String, I am trying to do this step: but have not been successful.
Here is the code I tried: Converting a BlobBuilder to string, in HTML5 Javascript
What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.
CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult
should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
If you want to use the catch()
of the Observable
you need to use Observable.throw()
method before delegating the error response to a method
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
constructor(private http: AuthHttp) {}_x000D_
_x000D_
envirArquivos(order): Observable < any > {_x000D_
const headers = new Headers();_x000D_
return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
new ResponseOptions({_x000D_
headers: headers_x000D_
}))_x000D_
.map(response => response.json())_x000D_
.catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
}_x000D_
_x000D_
errorHandler(error: any): void {_x000D_
console.log(error)_x000D_
}_x000D_
}
_x000D_
Using Observable.throw()
worked for me
Make sure to be careful when editing your model file. For example, in your post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $table = 'posts';
}
You need to pay close attention to the class Post extend Model
line. The class Post
defined here will be your namespace for your controller.
Please check this function - it converts timedelta object into string 'HH:MM:SS'
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)
background-position-x: center;
background-position-y: center;
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.
Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.
One option might be to make your data look like this:
var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
Now you have an array of objects, and we can sort it.
json.sort(function(a, b){
return a.id - b.id;
});
The resulting array will look like:
[{
"name": "user3",
"id" : 1
}, {
"name": "user1",
"id" : 3
}, {
"name": "user2",
"id" : 6
}];
Here's a (Tested) Extension Method, with comments to help you out.
using IWshRuntimeLibrary;
using System;
namespace Extensions
{
public static class XShortCut
{
/// <summary>
/// Creates a shortcut in the startup folder from a exe as found in the current directory.
/// </summary>
/// <param name="exeName">The exe name e.g. test.exe as found in the current directory</param>
/// <param name="startIn">The shortcut's "Start In" folder</param>
/// <param name="description">The shortcut's description</param>
/// <returns>The folder path where created</returns>
public static string CreateShortCutInStartUpFolder(string exeName, string startIn, string description)
{
var startupFolderPath = Environment.SpecialFolder.Startup.GetFolderPath();
var linkPath = startupFolderPath + @"\" + exeName + "-Shortcut.lnk";
var targetPath = Environment.CurrentDirectory + @"\" + exeName;
XFile.Delete(linkPath);
Create(linkPath, targetPath, startIn, description);
return startupFolderPath;
}
/// <summary>
/// Create a shortcut
/// </summary>
/// <param name="fullPathToLink">the full path to the shortcut to be created</param>
/// <param name="fullPathToTargetExe">the full path to the exe to 'really execute'</param>
/// <param name="startIn">Start in this folder</param>
/// <param name="description">Description for the link</param>
public static void Create(string fullPathToLink, string fullPathToTargetExe, string startIn, string description)
{
var shell = new WshShell();
var link = (IWshShortcut)shell.CreateShortcut(fullPathToLink);
link.IconLocation = fullPathToTargetExe;
link.TargetPath = fullPathToTargetExe;
link.Description = description;
link.WorkingDirectory = startIn;
link.Save();
}
}
}
And an example of use:
XShortCut.CreateShortCutInStartUpFolder(THEEXENAME,
Environment.CurrentDirectory,
"Starts some executable in the current directory of application");
1st parm sets the exe name (found in the current directory) 2nd parm is the "Start In" folder and 3rd parm is the shortcut description.
The naming convention of the link leaves no ambiguity as to what it will do. To test the link just double click it.
Final Note: the application itself (target) must have an ICON image associated with it. The link is easily able to locate the ICON within the exe. If the target application has more than one icon, you may open the link's properties and change the icon to any other found in the exe.
If you want input to disable on some statement.
use [readonly]=true
or false
instead of disabled.
<input [readonly]="this.isEditable"
type="text"
formControlName="reporteeName"
class="form-control"
placeholder="Enter Name" required>
If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.
var globalObject = {
name:"a",
age:20
}
function() {
let localObject = {
name:'a',
age:21
}
this.globalObject = localObject;
}
I might as well throw this out here.
Make an extension to remove chars from a string:
public static string RemoveChars(this string input, params char[] chars)
{
var sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (!chars.Contains(input[i]))
sb.Append(input[i]);
}
return sb.ToString();
}
And it's usable like this:
string str = "My name @is ,Wan.;'; Wan";
string cleanedUpString = str.RemoveChars('@', ',', '.', ';', '\'');
Or just like this:
string str = "My name @is ,Wan.;'; Wan".RemoveChars('@', ',', '.', ';', '\'');
You can use the jQuery find method
$('select').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
});
The above solution works perfectly but I choose to add the following code for them willing to get the clicked option. It allows you get the selected option even when this select value has not changed. (Tested with Mozilla only)
$('select').find('option').click(function () {
var optionSelected = $(this);
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
});
Here's how I did it. It seems to work fairly well, and it's extremely compact. (It uses a lot of ternary operators, though)
function formatTime(seconds) {
var hh = Math.floor(seconds / 3600),
mm = Math.floor(seconds / 60) % 60,
ss = Math.floor(seconds) % 60;
return (hh ? (hh < 10 ? "0" : "") + hh + ":" : "") + ((mm < 10) && hh ? "0" : "") + mm + ":" + (ss < 10 ? "0" : "") + ss
}
...and for formatting strings...
String.prototype.toHHMMSS = function() {
formatTime(parseInt(this, 10))
};
I put this:
@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
return !(self == nil
|| [self isKindOfClass:[NSNull class]]
|| ([self respondsToSelector:@selector(length)]
&& [(NSData *)self length] == 0)
|| ([self respondsToSelector:@selector(count)]
&& [(NSArray *)self count] == 0));
};
@end
The problem is that if self is nil, this function is never called. It'll return false, which is desired.
You need to accept the licences before building.
According to Android SDK docs you can use the following command depending on the sdkmanager location: Docs on --licenses
option seems to be missing though.
yes | sdkmanager --licenses
GNU/Linux Distributions:
yes | ~/Android/Sdk/tools/bin/sdkmanager --licenses
macOS:
export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home
yes | ~/Library/Android/sdk/tools/bin/sdkmanager --licenses
Windows:
%ANDROID_HOME%/tools/bin/sdkmanager --licenses
Flutter:
> flutter doctor --android-licenses
A simple way but dangerous way to do this would be to use eval()
. eval()
executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:
import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
print eval(s)
else:
print "Try entering a math problem"
Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
I want to give my resolution, it work when i replace the line [session = tf.Session()]
with [sess = tf.InteractiveSession()]
. Hope this will be useful to others.
If you don't care about the changes that git says are outstanding, then you can do a force checkout.
git checkout -f {{insert your branch name here}}
Somehow even Webstorm made it like this import {of} from 'rxjs/observable/of';
and everything started to work
Make sure HttpClient has access to the full client certificate (including the private key).
You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.
Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).
This is still an issue in VS Community 2015 and 2017 when building either console or windows apps. If the project is created with precompiled headers, the precompiled headers are apparently loaded before any of the #includes, so even if the #define _USE_MATH_DEFINES is the first line, it won't compile. #including math.h instead of cmath does not make a difference.
The only solutions I can find are either to start from an empty project (for simple console or embedded system apps) or to add /Y- to the command line arguments, which turns off the loading of precompiled headers.
For information on disabling precompiled headers, see for example https://msdn.microsoft.com/en-us/library/1hy7a92h.aspx
It would be nice if MS would change/fix this. I teach introductory programming courses at a large university, and explaining this to newbies never sinks in until they've made the mistake and struggled with it for an afternoon or so.
Simple variant:
Regex.Replace(input, @"\r\n|\r|\n", "\r\n")
For better performance:
static Regex newline_pattern = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
[...]
newline_pattern.Replace(input, "\r\n");
This should work
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
SELECT * FROM a WHERE a.group_id IN
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';
Try
$('li.current_sub').prev('.par_cat').[do stuff];
A very simple method would be to use the extract
method to select all the digits. Simply supply it the regular expression '\d+'
which extracts any number of digits.
df['result'] = df.result.str.extract(r'(\d+)', expand=True).astype(int)
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);
Retrieve on another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data like this
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
I have updated my server to GitLab 6.6.4 and finally found the way to get version of GitLab remotely without SSH access to server.
You should be logged in to access the following page:
https://your.domain.name/help
It shows something similar to:
GitLab 6.6.4 42e34ae
GitLab is open source software to collaborate on code.
...
etc.
I'd recommend graphviz highly when you get to the point where you want to render your graphs.
And its companions: take a look at Laszlo Szathmary's GraphViz class, along with notugly.xls.
I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working
$(".submitbtn").on("click", function(e) {
var form = $("#Form");
// you can't pass Jquery form it has to be javascript form object
var formData = new FormData(form[0]);
//if you only need to upload files then
//Grab the File upload control and append each file manually to FormData
//var files = form.find("#fileupload")[0].files;
//$.each(files, function() {
// var file = $(this);
// formData.append(file[0].name, file[0]);
//});
if ($(form).valid()) {
$.ajax({
type: "POST",
url: $(form).prop("action"),
//dataType: 'json', //not sure but works for me without this
data: formData,
contentType: false, //this is requireded please see answers above
processData: false, //this is requireded please see answers above
//cache: false, //not sure but works for me without this
error : ErrorHandler,
success : successHandler
});
}
});
this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html i.e.
<input id="fileupload" type="file" name="UploadedFiles" multiple>
public class MyViewModel
{
public HttpPostedFileBase[] UploadedFiles { get; set; }
}
You're missing a close parenthesis, I.E. you aren't closing Range()
.
Try this Range(cells(1, 1), cells(lastRow, lastColumn)).Select
But you should really look at the other answer from Dick Kusleika for possible alternatives that may serve you better. Specifically, ActiveSheet.UsedRange.Select
which has the same end result as your code.
You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?
Try a software called Access to MySQL.
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
- Wizard interface.
- Transfer data directly from one server to another.
- Create a dump file.
- Select tables to transfer.
- Select fields to transfer.
- Transfer password protected databases.
- Supports both shared security and user-level security.
- Optional transfer of indexes.
- Optional transfer of records.
- Optional transfer of default values in field definitions.
- Identifies and transfers auto number field types.
- Command line interface.
- Easy install, uninstall and upgrade.
See the aforementioned link for a step-by-step tutorial with screenshots.
Andy's response worked for me by escaping $path:
git submodule foreach "(git checkout master; git pull; cd ..; git add \$path; git commit -m 'Submodule Sync')"
To read directory contents you can use readdir() and use a script, in my example download.php
, to download files
if ($handle = opendir('/path/to/your/dir/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}
closedir($handle);
}
In download.php
you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php
$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;
if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
Save as fix_whitespace.py
:
#!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""
import os
import sys
def main():
""" Parse arguments, then fix whitespace in the given file """
if len(sys.argv) == 2:
fname = sys.argv[1]
if not os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
sys.exit(1)
fix_whitespace(fname)
def fix_whitespace(fname):
""" Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lines):
new_line = line.rstrip()
if len(line) != len(new_line):
lines[k] = new_line
fixed += 1
with open(fname, "wb") as fo:
fo.write("\n".join(lines))
if fixed or contents != original_contents:
print("************* %s" % os.path.basename(fname))
if fixed:
slines = "lines" if fixed > 1 else "line"
print("Fixed trailing whitespace on %d %s" \
% (fixed, slines))
if contents != original_contents:
print("Fixed line endings to Unix (\\n)")
if __name__ == "__main__":
main()
If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe
Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value
But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version
Sub CommandClick()
Dim rCell As Range
Dim rNext As Range
For Each rCell In Sheet2.Range("C1:C30000").Cells
If rCell.Value >= 100 And rCell.Value < 1000 Then
Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
End If
Next rCell
End Sub
I do it like this and it's work for me, I hope this will help :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>
This generates a random float between two floats.
float RandomFloat(float min, float max){
return ((max - min) * ((float)rand() / RAND_MAX)) + min;
}
The article Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError
error explains the behavior in great details.
The problem with you setup is that ngAfterViewInit
lifecycle hook is executed after change detection processed DOM updates. And you're effectively changing the property that is used in the template in this hook which means that DOM needs to be re-rendered:
ngAfterViewInit() {
this.message = 'all done loading :)'; // needs to be rendered the DOM
}
and this will require another change detection cycle and Angular by design only runs one digest cycle.
You basically have two alternatives how to fix it:
update the property asynchronously either using setTimeout
, Promise.then
or asynchronous observable referenced in the template
perform the property update in a hook before the DOM update - ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked.
Try like this:
if message.value[0] == "/" or message.value[0] == "\\":
do_stuff
Try this please
DELETE FROM messages,usersmessages
USING messages
INNER JOIN usermessages on (messages.messageid = usersmessages.messageid)
WHERE messages.messsageid='1'
In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.
Note that in an XML Declaration the encoding
and standalone
are both optional. Only the version
is mandatory. Also, these are not attributes, so if they are present they must be in that order: version
, followed by any encoding
, followed by any standalone
.
<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.
The standalone
indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.
Update:
A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.
Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?>
which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding
and simply say <?xml version="1.0"?>
. You could also edit it to say encoding="UTF-16"
but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.
Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.
I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle
'd bytestrings generated by pickle.dumps(...)
.
The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain
object.
$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma
from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)
brain['a'] = [1]*10000
brain['a']
# >>> [1,1,1,1,...]
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
While they are both rooted in C, they are two completely different languages.
A major difference is that Objective-C is focused on runtime-decisions for dispatching and heavily depends on its runtime library to handle inheritance and polymorphism, while in C++ the focus usually lies on static, compile time, decisions.
Regarding libraries, you can use plain C libraries in both languages - but their native libraries are completely different.
Of interest though is that you can mix both languages (with some limitations). The result is called Objective-C++.
Use dict.setdefault()
:
>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}