You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.
Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: .
::
sizeof
typeid
.*
and the only ternary operator in C++, ?:
Among the operators that can be overloaded in C++ are these:
+
-
*
/
%
and +=
-=
*=
/=
%=
(all binary infix); +
-
(unary prefix); ++
--
(unary prefix and postfix)&
|
^
<<
>>
and &=
|=
^=
<<=
>>=
(all binary infix); ~
(unary prefix)==
!=
<
>
<=
>=
||
&&
(all binary infix); !
(unary prefix)new
new[]
delete
delete[]
=
[]
->
->*
,
(all binary infix); *
&
(all unary prefix) ()
(function call, n-ary infix)However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.
In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @
3, applied to an object x, is invoked either as operator@(x)
or as x.operator@()
. A binary infix operator @
, applied to the objects x
and y
, is called either as operator@(x,y)
or as x.operator@(y)
.4
Operators that are implemented as non-member functions are sometimes friend of their operand’s type.
1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.
2 This is covered in a later part of this FAQ.
3 The @
is not a valid operator in C++ which is why I use it as a placeholder.
4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.
Continue to The Three Basic Rules of Operator Overloading in C++.
I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem. the problem on the API, make sure you have a good variable name I used $start_date and it caused the problem, so I try $startdate and it works!
as well make sure you send all parameter that declare on API, for example, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];
you have to pass this two variable from the retrofit.
as well if you use date on SQL statement, try to put it inside '' like '2017-07-24'
I hope it helps you.
You can escape the dot and other special characters using \
eg. grep -r "0\.49"
You could try jsawk as suggested in this answer.
Really you could whip up a quick python script to do this though.
After doing the git rm --cached
command, try adding myfile
to the .gitignore
file (create one if it does not exist). This should tell git to ignore myfile
.
The .gitignore
file is versioned, so you'll need to commit it and push it to the remote repository.
For Kotlin users:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?) : View?
{
// Inflate the layout for this fragment
var myView = inflater.inflate(R.layout.fragment_home, container, false)
var btn_test = myView.btn_test as Button
btn_test.setOnClickListener {
textView.text = "hunny home fragment"
}
return myView
}
Well maybe you forgot to add "$route" when declaring the dependencies of your Controller:
app.controller('NameCtrl', ['$scope','$route', function($scope,$route) {
// $route.reload(); Then this should work fine.
}]);
In Python integers will automatically switch from a fixed-size int
representation into a variable width long
representation once you pass the value sys.maxint
, which is either 231 - 1 or 263 - 1 depending on your platform. Notice the L
that gets appended here:
>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L
From the Python manual:
Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an
'L'
or'l'
suffix yield long integers ('L'
is preferred because1l
looks too much like eleven!).
Python tries very hard to pretend its integers are mathematical integers and are unbounded. It can, for instance, calculate a googol with ease:
>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
Opera, Chrome, Safari supports SSE, Chrome, Safari supports SSE inside of SharedWorker Firefox supports XMLHttpRequest readyState interactive, so we can make EventSource polyfil for Firefox
Two things worth pointing out:
You should configure the compiler plugin to compile to at least java 1.5 to handle the annotations when building with Maven. (Can also affect IDE settings, though Eclipse doesn't tend to care.)
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
After that, reconfiguring your project from Maven should fix it. I don't recall exactly how to do that in Eclipse, but you should find it if you right click the project node and poke around the menus.
I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.
Give "write" permission to the directory you need to put the file. In your case it is the current directory.
Use "chmod" in linux.
Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.
Simplified & Improved version:
SELECT
D.name,
CAST(SUM(F.size) AS bigint) * 8*1024 AS SizeInBytes,
CAST(SUM(F.size*8.0)/1024/1024 AS decimal(18,3)) AS SizeInGB
FROM
sys.master_files F
INNER JOIN sys.databases D ON D.database_id = F.database_id
GROUP BY D.name
ORDER BY SizeInBytes desc
m/ /g
just give space in / /
, and it will work. Or use \S
— it will replace all the special characters like tab, newlines, spaces, and so on.
Empty strings are falsey, so you can just write:
if ($a) {
echo 'text';
}
Although if you're asking if a particular substring exists in that string, you can use strpos()
to do that:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
You can use a trick, by creating a <a>
-element, then setting the string to the href of that <a>
-element and then you have a Location object you can get the hostname from.
You could either add a method to the String prototype:
String.prototype.toLocation = function() {
var a = document.createElement('a');
a.href = this;
return a;
};
and use it like this:
"http://www.abc.com/search".toLocation().hostname
or make it a function:
function toLocation(url) {
var a = document.createElement('a');
a.href = url;
return a;
};
and use it like this:
toLocation("http://www.abc.com/search").hostname
both of these will output: "www.abc.com"
If you also need the protocol, you can do something like this:
var url = "http://www.abc.com/search".toLocation();
url.protocol + "//" + url.hostname
which will output: "http://www.abc.com"
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
Long answer to short, if you install boost in custom path, all header files must in ${path}/boost/.
if you want to konw why cmake can't find the requested Boost libraries after you have set BOOST_ROOT/BOOST_INCLUDEDIR
, you can check cmake install location path_to_cmake/share/cmake-xxx/Modules/FindBoost
.
cmake which will find Boost_INCLUDE_DIR
in boost/config.hpp
in BOOST_ROOT
. That means your boost header file must in ${path}/boost/
, any other format (such as ${path}/boost-x.y.z
) will not be suitable for find_package
in CMakeLists.txt.
func readToDisplayUsingFile1(f *os.File){
defer f.Close()
reader := bufio.NewReader(f)
contents, _ := ioutil.ReadAll(reader)
lines := strings.Split(string(contents), '\n')
}
or
func readToDisplayUsingFile1(f *os.File){
defer f.Close()
slice := make([]string,0)
reader := bufio.NewReader(f)
for{
str, err := reader.ReadString('\n')
if err == io.EOF{
break
}
slice = append(slice, str)
}
Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.
Right-click project in Package explorer Build path -> Add external archives...
Select your ojdbc6.jar archive
Press OK
Or
Go through this link and read and do carefully.
The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.
As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.
You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data
).
It would look like this:
# read dataset
df = mtcars
# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)
# save predictions of the model in the new data frame
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))
# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
This is not a very nice fix but it works:
CSS:
.new-tab-opener
{
display: none;
}
HTML:
<a data-href="http://www.google.com/" href="javascript:">Click here</a>
<form class="new-tab-opener" method="get" target="_blank"></form>
Javascript:
$('a').on('click', function (e) {
var f = $('.new-tab-opener');
f.attr('action', $(this).attr('data-href'));
f.submit();
});
Live example: http://jsfiddle.net/7eRLb/
Simply unregister the default StringHttpMessageConverter
instance:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* Unregister the default {@link StringHttpMessageConverter} as we want Strings
* to be handled by the JSON converter.
*
* @param converters List of already configured converters
* @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.stream()
.filter(c -> c instanceof StringHttpMessageConverter)
.findFirst().ifPresent(converters::remove);
}
}
Tested with both controller action handler methods and controller exception handlers:
@RequestMapping("/foo")
public String produceFoo() {
return "foo";
}
@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
return e.getMessage();
}
Final notes:
extendMessageConverters
is available since Spring 4.1.3, if are running on a previous version you can implement the same technique using configureMessageConverters
, it just takes a little bit more work.Example code using NLog that will catch exceptions thrown from all threads in the AppDomain, from the UI dispatcher thread and from the async functions:
public partial class App : Application
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SetupExceptionHandling();
}
private void SetupExceptionHandling()
{
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");
DispatcherUnhandledException += (s, e) =>
{
LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");
e.Handled = true;
};
TaskScheduler.UnobservedTaskException += (s, e) =>
{
LogUnhandledException(e.Exception, "TaskScheduler.UnobservedTaskException");
e.SetObserved();
};
}
private void LogUnhandledException(Exception exception, string source)
{
string message = $"Unhandled exception ({source})";
try
{
System.Reflection.AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
}
catch (Exception ex)
{
_logger.Error(ex, "Exception in LogUnhandledException");
}
finally
{
_logger.Error(exception, message);
}
}
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
The intent of the standalone=yes
declaration is to guarantee that the information inside the document can be faithfully retrieved based only on the internal DTD, i.e. the document can "stand alone" with no external references. Validating a standalone document ensures that non-validating processors will have all of the information available to correctly parse the document.
The standalone declaration serves no purpose if a document has no external DTD, and the internal DTD has no parameter entity references, as these documents are already implicitly standalone.
The following are the actual effects of using standalone=yes
.
Forces processors to throw an error when parsing documents with an external DTD or parameter entity references, if the document contains references to entities not declared in the internal DTD (with the exception of replacement text of parameter entities as non-validating processors are not required to parse this); amp
, lt
, gt
, apos
, and quot
are the only exceptions
When parsing a document not declared as standalone, a non-validating processor is free to stop parsing the internal DTD as soon as it encounters a parameter entity reference. Declaring a document as standalone forces non-validating processors to parse markup declarations in the internal DTD even after they ignore one or more parameter entity references.
Forces validating processors to throw an error if any of the following are found in the document, and their respective declarations are in the external DTD or in parameter entity replacement text:
amp
, lt
, gt
, apos
, and quot
)A non-validating processor might consider retrieving the external DTD and expanding all parameter entity references for documents that are not standalone, even though it is under no obligation to do so, i.e. setting standalone=yes
could theoretically improve performance for non-validating processors (spoiler alert: it probably won't make a difference).
The other answers here are either incomplete or incorrect, the main misconception is that
The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.
standalone="yes" means that the XML processor must use the DTD for validation only.
Quite the opposite, declaring a document as standalone will actually force a non-validating processor to parse internal declarations it must normally ignore (i.e. those after an ignored parameter entity reference). Non-validating processors must still use the info in the internal DTD to provide default attribute values and normalize tokenized attributes, as this is independent of validation.
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.
[id] [int] IDENTITY(1,1) NOT NULL,
of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.
Or, if you are looking for simple collection of errors for your apps.. here is my implementation of this:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
var errors = new List<string>();
foreach (var state in modelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
var response = new { errors = errors };
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.BadRequest, response, JsonMediaTypeFormatter.DefaultMediaType);
}
}
Error Message Response will look like:
{ "errors": [ "Please enter a valid phone number (7+ more digits)", "Please enter a valid e-mail address" ] }
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
How to properly ignore Exceptions?
There are several ways of doing this.
However, the choice of example has a simple solution that does not cover the general case.
Instead of
try:
shutil.rmtree(path)
except:
pass
Do this:
shutil.rmtree(path, ignore_errors=True)
This is an argument specific to shutil.rmtree
. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.
>>> import shutil
>>> help(shutil.rmtree)
Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.
Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.
You can import the suppress
context manager:
from contextlib import suppress
But only suppress the most specific exception:
with suppress(FileNotFoundError):
shutil.rmtree(path)
You will silently ignore a FileNotFoundError
:
>>> with suppress(FileNotFoundError):
... shutil.rmtree('bajkjbkdlsjfljsf')
...
>>>
From the docs:
As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.
Note that suppress
and FileNotFoundError
are only available in Python 3.
If you want your code to work in Python 2 as well, see the next section:
When you just want to do a try/except without handling the exception, how do you do it in Python?
Is the following the right way to do it?
try : shutil.rmtree ( path ) except : pass
For Python 2 compatible code, pass
is the correct way to have a statement that's a no-op. But when you do a bare except:
, that's the same as doing except BaseException:
which includes GeneratorExit
, KeyboardInterrupt
, and SystemExit
, and in general, you don't want to catch those things.
In fact, you should be as specific in naming the exception as you can.
Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
... and so on
You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.
We can get that specific error number from the errno
library, and reraise if we don't have that:
import errno
try:
shutil.rmtree(path)
except OSError as error:
if error.errno == errno.ENOENT: # no such file or directory
pass
else: # we had an OSError we didn't expect, so reraise it
raise
Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass
with code in the exception handling:
try:
shutil.rmtree(path)
except OSError as error:
if error.errno != errno.ENOENT: # no such file or directory
raise
I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.
This should work:
// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());
// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
String key = entry.getKey();
List<String>value = entry.getValue();
// ...
}
or you can use
// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
List<String>value = test1.get(key);
// ...
}
You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.
If you just need this for debugging to see how the XML looks like, then instead of print(xml.etree.ElementTree.tostring(e))
you can use dump
like this:
xml.etree.ElementTree.dump(e)
And this works both with Element
and ElementTree
objects as e
, so there should be no need for getroot
.
The documentation of dump
says:
xml.etree.ElementTree.dump(elem)
Writes an element tree or element structure to
sys.stdout
. This function should be used for debugging only.The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.
elem
is an element tree or an individual element.Changed in version 3.8: The
dump()
function now preserves the attribute order specified by the user.
Try this:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
There are more methods available, e.g. see here: http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black.
The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown).
<UserControl.Resources>
<!-- This style is used for buttons, to remove the WPF default 'animated' mouse over effect -->
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border"
BorderThickness="1"
Padding="4,2"
BorderBrush="DarkGray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<!-- usage in xaml -->
<Button Style="{StaticResource MyButtonStyle}">Hello!</Button>
Ctrl+Space : Show Imports
This displays imports as you're typing a non-standard class name provided the proper references have been added to the project.
This works on partial or complete class names as you are typing them or after the fact (Just place the cursor back on the class name with squigglies).
HTML Pencil is an online HTML editor created for modern browsers.
<script type="text/javascript">
function MyFunction() {
var FNumber = Number(document.getElementById('txtFirstNumber').value);
var SNumber = Number(document.getElementById("txtSecondNumber").value);
var Sum = FNumber + SNumber;
alert(Sum);
}
</script>
<table class="auto-style1">
<tr>
<td>FirstNaumber</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>SecondNumber</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClientClick="MyFunction()" />
</td>
</tr>
</table>
</div>
</form>
If your proxy server or container adds the following header when serving the .js file, it will force some browsers such as Chrome to perform strict checking of MIME types:
X-Content-Type-Options: nosniff
Remove this header to prevent Chrome performing the MIME check.
There is a .val();
method that you can use.
So in your situation you would want to use $("#txtEmail").val();
. Also, make sure you add the id property into your html code!
In Django, MVC structure is as Chris Pratt said, different from classical MVC model used in other frameworks, I think the main reason for doing this is avoiding a too strict application structure, like happens in others MVC frameworks like CakePHP.
In Django, MVC was implemented in the following way:
View layer is splitted in two. The views should be used only to manage HTTP requests, they are called and respond to them. Views communicate with the rest of your application (forms, modelforms, custom classes, of in simple cases directly with models). To create the interface we use Templates. Templates are string-like to Django, it maps a context into them, and this context was communicated to the view by the application (when view asks).
Model layer gives encapsulation, abstraction, validation, intelligence and makes your data object-oriented (they say someday DBMS will also). This doesn't means that you should make huge models.py files (in fact a very good advice is to split your models in different files, put them into a folder called 'models', make an '__init__.py' file into this folder where you import all your models and finally use the attribute 'app_label' of models.Model class). Model should abstract you from operating with data, it will make your application simpler. You should also, if required, create external classes, like "tools" for your models.You can also use heritage in models, setting the 'abstract' attribute of your model's Meta class to 'True'.
Where is the rest? Well, small web applications generally are a sort of an interface to data, in some small program cases using views to query or insert data would be enough. More common cases will use Forms or ModelForms, which are actually "controllers". This is not other than a practical solution to a common problem, and a very fast one. It's what a website use to do.
If Forms are not enogh for you, then you should create your own classes to do the magic, a very good example of this is admin application: you can read ModelAmin code, this actually works as a controller. There is not a standard structure, I suggest you to examine existing Django apps, it depends on each case. This is what Django developers intended, you can add xml parser class, an API connector class, add Celery for performing tasks, twisted for a reactor-based application, use only the ORM, make a web service, modify the admin application and more... It's your responsability to make good quality code, respect MVC philosophy or not, make it module based and creating your own abstraction layers. It's very flexible.
My advice: read as much code as you can, there are lots of django applications around, but don't take them so seriously. Each case is different, patterns and theory helps, but not always, this is an imprecise cience, django just provide you good tools that you can use to aliviate some pains (like admin interface, web form validation, i18n, observer pattern implementation, all the previously mentioned and others), but good designs come from experienced designers.
PS.: use 'User' class from auth application (from standard django), you can make for example user profiles, or at least read its code, it will be useful for your case.
C/program files/
and user/sukhendra/AppData
then only Anaconda is remaining in my PC so opened Anaconda and then it's all working fine for me
$today_at_midnight = strtotime(date("Ymd"));
should give you what you're after.
explanation
What I did was use PHP's date function to get today's date without any references to time, and then pass it to the 'string to time' function which converts a date and time to a epoch timestamp. If it doesn't get a time, it assumes the first second of that day.
References: Date Function: http://php.net/manual/en/function.date.php
String To Time: http://us2.php.net/manual/en/function.strtotime.php
This would get a single entry from the map, which about as close as one can get, given 'first' doesn't really apply.
import java.util.*;
public class Friday {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("code", 10);
map.put("to", 11);
map.put("joy", 12);
if (! map.isEmpty()) {
Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
System.out.println(entry);
}
}
}
GNU Colab lets you run a standard persistent desktop environment on top of a Colaboratory instance.
Indeed it contains a mechanism to not let machines die of idling.
Here's a video demonstration.
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}
You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select
You can expend the following function in order to pull out more parameters from the DB before the insert:
--
-- insert_employee (Function)
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2)
RETURN VARCHAR2 AS
p_state_id varchar2(30) := '';
BEGIN
select state_id
into p_state_id
from states where lower(emp_state) = state_name;
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES
(p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);
return 'SUCCESS';
EXCEPTION
WHEN others THEN
RETURN 'FAIL';
END;
/
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
Tried everything in this thread and nothing worked for me in IntelliJ 2020.2. This answer did the trick, but I had to set the correct path to the JDK and choose it in Gradle settings after that (as showed in figures bellow):
After that, the option "Reload All Gradle Projects" downloaded all dependencies as expected.
Cheers.
kwargs is just a dictionary that is added to the parameters.
A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.
The what for is not so simple.
For example (very hypothetical) you have an interface that just calls other routines to do the job:
def myDo(what, where, why):
if what == 'swim':
doSwim(where, why)
elif what == 'walk':
doWalk(where, why)
...
Now you get a new method "drive":
elif what == 'drive':
doDrive(where, why, vehicle)
But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.
Here you can throw kwargs into play -- you just add kwargs to the signature:
def myDo(what, where, why, **kwargs):
if what == 'drive':
doDrive(where, why, **kwargs)
elif what == 'swim':
doSwim(where, why, **kwargs)
This way you don't need to change the signature of your interface function every time some of your called routines might change.
This is just one nice example you could find kwargs helpful.
Yes, you can do a 3 table join for an update statement. Here is an example :
UPDATE customer_table c
JOIN
employee_table e
ON c.city_id = e.city_id
JOIN
anyother_ table a
ON a.someID = e.someID
SET c.active = "Yes"
WHERE c.city = "New york";
here you can find an implementation :
def __uniqueid__():
"""
generate unique id with length 17 to 21.
ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward).
if you generate 1 million ids per second during 100 years, you will generate
2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids.
with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20).
In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed)
do not cover all numbers that could be represented with 35 digits (radix 16).
if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour
so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period.
the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need
a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you
move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate
more than 1 million ids per second.
one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id.
you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world.
hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is
possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps
35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms
in order to be convinced that problems could occur as soon as you use random library :)
1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get :
>>> timeit.timeit(uniqueid,number=40000)
1.0114529132843018
an average of 40000 id/second
"""
mynow=datetime.now
sft=datetime.strftime
# store old datetime each time in order to check if we generate during same microsecond (glucky wallet !)
# or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level]
old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :)
# manage seed
seed_range_bits=14 # max range for seed
seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1
# get random seed
seed=random.getrandbits(seed_range_bits)
current_seed=str(seed)
# producing new ids
while True:
# get current time
current_time=mynow()
if current_time <= old_time:
# previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward)
seed = max(1,(seed + 1) % seed_max_value)
current_seed=str(seed)
# generate new id (concatenate seed and timestamp as numbers)
#newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1]
newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed]))
# save current time
old_time=current_time
# return a new id
yield newid
""" you get a new id for each call of uniqueid() """
uniqueid=__uniqueid__().next
import unittest
class UniqueIdTest(unittest.TestCase):
def testGen(self):
for _ in range(3):
m=[uniqueid() for _ in range(10)]
self.assertEqual(len(m),len(set(m)),"duplicates found !")
hope it helps !
If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.
Using Java Config it would be:
@Configuration
public class DBConfig {
@Bean
public DataSource dataSource() {
//create a data source
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public TransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
Then a repository that uses that JdbcTemplate could be:
@Repository
public class JdbcSomeRepository implements SomeRepository {
private final JdbcTemplate jdbcTemplate ;
@Autowired
public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
@Transactional
public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
}
}
The update method from JdbcTemplate that I have used can be found here.
If you set the following property to false then it will disable both bundling and minification.
In Global.asax.cs file, add the line as mentioned below
protected void Application_Start()
{
System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
May be it will helpful:
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>
Got it! I found an idea here
http://www.mail-archive.com/[email protected]/msg18410.html
In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:
$('.printBtn').bind('click',function() {
var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
$('#popup-content').clone().appendTo( thePopup.document.body );
thePopup.print();
});
I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.
Works in Firefox. I need to test it in some other major browsers too.
I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.
Thanks for the input! You gave me some ideas of how to get around this.
I found dfsq's answer its comments extremely useful. I made some minor modifications applicable to me (and I'm posting it here, in case it is of some use to others).
class
as hooks, instead of table elements tr
class
while showing/hiding parent$rows
text elements into an array only once (and avoiding $rows.length
times computation)var $rows = $('.wrapper');
var rowsTextArray = [];
var i = 0;
$.each($rows, function () {
rowsTextArray[i] = ($(this).find('.number').text() + $(this).find('.fruit').text())
.replace(/\s+/g, '')
.toLowerCase();
i++;
});
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/\s+/g, '').toLowerCase();
$rows.show().filter(function(index) {
return (rowsTextArray[index].indexOf(val) === -1);
}).hide();
});
_x000D_
span {
margin-right: 0.2em;
}
_x000D_
<input type="text" id="search" placeholder="type to search" />
<div class="wrapper"><span class="number">one</span><span class="fruit">apple</span></div>
<div class="wrapper"><span class="number">two</span><span class="fruit">banana</span></div>
<div class="wrapper"><span class="number">three</span><span class="fruit">cherry</span></div>
<div class="wrapper"><span class="number">four</span><span class="fruit">date</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
How about using express module?
var app = require('express')();
app.get('/',function(request,response){
response.sendFile(__dirname+'/XXX.html');
});
app.listen('8000');
then, you can use browser to get /localhost:8000
if you are using any mobile suit like mobogenie or something that might also will make this issue. try killing that too from the task manager.
Note : i faced the same issue, tried the above solution. That didn't work, finally found out this solution.May useful for someone else!..
Our global AsyncTask class variable
LongOperation LongOperationOdeme = new LongOperation();
And KEYCODE_BACK action which interrupt AsyncTask
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LongOperationOdeme.cancel(true);
}
return super.onKeyDown(keyCode, event);
}
It works for me.
As a windows user, run an Admin powershell and launch :
python -m pip install --upgrade pip
You can use this function to get the absolute value:
+(NSNumber *)absoluteValue:(NSNumber *)input {
return [NSNumber numberWithDouble:fabs([input doubleValue])];
}
Otherwise you can create your own function then call it. It is important to use Double
Function sov(sekunder As Double) As Double
starting_time = Timer
Do
DoEvents
Loop Until (Timer - starting_time) >= sekunder
End Function
I was using a playbook like this to test my roles locally:
---
- hosts: localhost
roles:
- role: .
but this stopped working with Ansible v2.2.
I debugged the aforementioned solution of
---
- hosts: all
tasks:
- name: Find out playbooks path
shell: pwd
register: playbook_path_output
- debug: var=playbook_path_output.stdout
and it produced my home directory and not the "current working directory"
I settled with
---
- hosts: all
roles:
- role: '{{playbook_dir}}'
per the solution above.
Pick one or more from:
So, you can check that your application is listening successfully by running lsof -i
as root on the machine and look for a python
entry with the corresponding port you've specified.
Non-root users generally cannot bind to ports < 1024.
You'll need to look at iptables -nvL
to see if there's a rule that would prevent access to the ip:port that you are trying to bind your application to.
If there is an upstream firewall and you don't know much about it, you'll need to talk to your network administrators.
For Passing a single variable to view.
Inside Your controller create a method like:
function sleep()
{
return view('welcome')->with('title','My App');
}
In Your route
Route::get('/sleep', 'TestController@sleep');
In Your View Welcome.blade.php
. You can echo your variable like {{ $title }}
For An Array(multiple values) change,sleep method to :
function sleep()
{
$data = array(
'title'=>'My App',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('welcome')->with($data);
}
You can access you variable like {{ $author }}
.
my implementation is very simple, count the number of lines in the input (and minimum 2 rows to show that it's a textarea):
textarea.rows = Math.max(2, textarea.value.split("\n").length) // # oninput
full working example with stimulus: https://jsbin.com/kajosolini/1/edit?html,js,output
(and this works with the browser's manual resize handle for instance)
The Alert Method, authenticateUsing()
lets you skip the Http Basic Authentication box.
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));
As of Selenium 3.4 it is still in beta
Right now implementation is only done for
InternetExplorerDriver
if anyone cares there is a much better way to capture focus now, $(foo).focus(...)
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
You can use the UNPIVOT function to convert the columns into rows:
select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;
Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.
You could also use CROSS APPLY
with UNION ALL to convert the columns:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
select 'Indicator1', Indicator1 union all
select 'Indicator2', Indicator2 union all
select 'Indicator3', Indicator3 union all
select 'Indicator4', Indicator4
) c (indicatorname, indicatorvalue);
Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
values
('Indicator1', Indicator1),
('Indicator2', Indicator2),
('Indicator3', Indicator3),
('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);
Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'yourtable' and
C.column_name like 'Indicator%'
for xml path('')), 1, 1, '')
set @query
= 'select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in ('+ @colsunpivot +')
) u'
exec sp_executesql @query;
You can also access the principal using the User
property on ApiController
.
So the following two statements are basically the same:
string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();
Use CONCAT_WS instead:
CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.
SELECT CONCAT_WS('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) AS device_name FROM devices
try this:
powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
For PHP7 on CentOS or EC2 Linux AMI:
sudo yum install php70-gd
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
In cases where you don't want the metaclass-based solution above, and you don't like the simple function decorator-based approach (e.g. because in that case static methods on the singleton class won't work), this compromise works:
class singleton(object):
"""Singleton decorator."""
def __init__(self, cls):
self.__dict__['cls'] = cls
instances = {}
def __call__(self):
if self.cls not in self.instances:
self.instances[self.cls] = self.cls()
return self.instances[self.cls]
def __getattr__(self, attr):
return getattr(self.__dict__['cls'], attr)
def __setattr__(self, attr, value):
return setattr(self.__dict__['cls'], attr, value)
You should do something like that:
<LinearLayout
android:id="@+id/widget34"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_below="@+id/tv_scanning_for"
android:layout_centerHorizontal="true">
<ListView
android:id="@+id/lv_events"
android:textSize="18sp"
android:cacheColorHint="#00000000"
android:layout_height="1"
android:layout_width="fill_parent"
android:layout_weight="0dp"
android:layout_below="@+id/tv_scanning_for"
android:layout_centerHorizontal="true"
/>
</LinearLayout>
Also use dp instead px or read about it here.
One significant difference between INNER JOIN and NATURAL JOIN is the number of columns returned.
Consider:
TableA TableB
+------------+----------+ +--------------------+
|Column1 | Column2 | |Column1 | Column3 |
+-----------------------+ +--------------------+
| 1 | 2 | | 1 | 3 |
+------------+----------+ +---------+----------+
The INNER JOIN
of TableA and TableB on Column1 will return
SELECT * FROM TableA AS a INNER JOIN TableB AS b USING (Column1);
SELECT * FROM TableA AS a INNER JOIN TableB AS b ON a.Column1 = b.Column1;
+------------+-----------+---------------------+
| a.Column1 | a.Column2 | b.Column1| b.Column3|
+------------------------+---------------------+
| 1 | 2 | 1 | 3 |
+------------+-----------+----------+----------+
The NATURAL JOIN
of TableA and TableB on Column1 will return:
SELECT * FROM TableA NATURAL JOIN TableB
+------------+----------+----------+
|Column1 | Column2 | Column3 |
+-----------------------+----------+
| 1 | 2 | 3 |
+------------+----------+----------+
The repeated column is avoided.
(AFAICT from the standard grammar, you can't specify the joining columns in a natural join; the join is strictly name-based. See also Wikipedia.)
(There's a cheat in the inner join output; the a.
and b.
parts would not be in the column names; you'd just have column1
, column2
, column1
, column3
as the headings.)
When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this)
. So, to get, for example, the next sibling element, you would do this inside the click handler:
var nextSibling = $(this).next();
Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index()
to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.
var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);
If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"
Versions of sed
that support the -i
option for editing a file in place write to a temporary file and then rename the file.
Alternatively, you can just use ed
. For example, to change all occurrences of foo
to bar
in the file file.txt
, you can do:
echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
Syntax is similar to sed
, but certainly not exactly the same.
Even if you don't have a -i
supporting sed
, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file
, you could do inline file sed 's/foo/bar/g'
. Such a script is trivial to write. For example:
#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN" # preserve hard links
should be adequate for most uses.
it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)
That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(),
and/or readResolve()
or /writeReplace()
methods and/or a serializableFields
declaration that could cope with the change.
One can also do this :
<xsl:text disable-output-escaping="yes"><![CDATA[ ]]></xsl:text>
Detailed Solution with Screenshots
MyCustomCell.xib
.UITableViewCell
as the root of your xib file and any other visual components you want.MyCustomCell
as a subclass of UITableViewCell
.ctrl+drag
to create outlets for your visual components.UIViewController
to use your custom cell.class MyViewController: UIViewController {
@IBOutlet weak var myTable: UITableView!
override func viewDidLoad {
super.viewDidLoad()
let nib = UINib(nibName: "MyCustomCell", bundle: nil)
myTable.register(nib, forCellReuseIdentifier: "MyCustomCell")
myTable.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell") as? MyCustomCell {
cell.myLabel.text = "Hello world."
return cell
}
...
}
}
Open Notepad, create a file called XlsToCsv.vbs and paste this in:
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
Then from a command line, go to the folder you saved the .vbs file in and run:
XlsToCsv.vbs [sourcexlsFile].xls [destinationcsvfile].csv
This requires Excel to be installed on the machine you are on though.
Like you said remote_repo_url
is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.
There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server
You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server
A simple approach is to make use of
;
For example:
ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV" deauthorize_users.yml --check
A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status
, etc.
If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:
# initialize your bare repo
$ git init --bare test-repo.git
# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone
# make an initial commit in the clone
$ touch README.md
$ git add .
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md
# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
* [new branch] master -> master
There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.
Long story short:
if I call
p=malloc(1000);
free(p);
then the Private Bytes reflect only the allocation, not the deallocation.
if I call
p=malloc(>512k);
free(p);
then the Private Bytes correctly reflect the allocation and the deallocation.
You already got some good answers, but I guess you could see it like this: ENCRYPTION: Encryption has to be decryptable if you have the right key.
Example: Like when you send an e-mail. You might not want everyone in the world to know what you are writing to the person receiving the e-mail, but the person who receives the e-mail would probably want to be able to read it.
HASHES: hashes work similar like encryption, but it should not be able to reverse it at all.
Example: Like when you put a key in a locked door(the kinds that locks when you close them). You do not care how the lock works in detail, just as long as it unlocks itself when you use the key. If there is trouble you probably cannot fix it, instead get a new lock.(like forgetting passwords on every login, at least I do it all the time and it is a common area to use hashing).
... and I guess you could call that rainbow-algorithm a locksmith in this case.
Hope things clear up =)
Just for clarification: setRequestProperty("User-Agent", "Mozilla ...")
now works just fine and doesn't append java/xx
at the end! At least with Java 1.6.30 and newer.
I listened on my machine with netcat(a port listener):
$ nc -l -p 8080
It simply listens on the port, so you see anything which gets requested, like raw http-headers.
And got the following http-headers without setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
And WITH setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
As you can see the user agent was properly set.
Full example:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class TestUrlOpener {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/foobar");
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
System.out.println(hc.getContentType());
}
}
It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...
You can use VLOOKUP, but this requires a wrapper function to return True
or False
. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.
Fill down this formula in column K next to the existing values in column I (from I1
to I2691
):
=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0
You can also use MATCH:
=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))
gevang's answer is great. There's another way as well to do this directly by using pcolor
. Code:
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure;
subplot(1,3,1);
pcolor(X,Y,Z);
subplot(1,3,2);
pcolor(X,Y,Z); shading flat;
subplot(1,3,3);
pcolor(X,Y,Z); shading interp;
Output:
Also, pcolor
is flat too, as show here (pcolor
is the 2d base; the 3d figure above it is generated using mesh
):
now Application-Level Rate Limiting 200 calls per hour !
If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.
I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.
DELIMITER $$
CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;
WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
SET lastParent = curParent;
SELECT ParentId from `test` where id=curId limit 1 into curParent;
IF curParent = pParentId THEN
SET isChild = 1;
END IF;
SET curId = curParent;
END WHILE;
RETURN isChild;
END$$
Here, the table test
has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.
Usage :
SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;
Result :
3 7 k
5 3 d
9 3 f
1 5 a
SQL for test creation :
CREATE TABLE IF NOT EXISTS `test` (
`Id` int(11) NOT NULL,
`ParentId` int(11) DEFAULT NULL,
`Name` varchar(300) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');
EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.
var isWin64 = process.env.hasOwnProperty('ProgramFiles(x86)');
If the array is a global, static, or automatic variable (int array[10];
), then sizeof(array)/sizeof(array[0])
works.
If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);
) or passed as a function argument (void f(int array[])
), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0])
compiles just fine even for the second case, but it will silently produce the wrong result.
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
From the Java Documentation:
[...] More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:
<T extends Annotation> T getAnnotation(Class<T> annotationType);
This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:
Author a = Othello.class.getAnnotation(Author.class);
Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation. [...]
Well, I never had to use this kind of stuff. Anyone?
to access the last element in array using c# we can use GetUpperBound(0)
(0) in case if this one dimention array
my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array
The correct solution is to take a peek at contrib/completions/git-completion.bash does that for bash prompt in __git_ps1
. Removing all extras like selecting how to describe detached HEAD situation, i.e. when we are on unnamed branch, it is:
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
git symbolic-ref is used to extract fully qualified branch name from symbolic reference; we use it for HEAD, which is currently checked out branch.
Alternate solution could be:
branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}
where in last line we deal with the detached HEAD situation, using simply "HEAD" to denote such situation.
Added 11-06-2013
Junio C. Hamano (git maintainer) blog post, Checking the current branch programatically, from June 10, 2013 explains whys (and hows) in more detail.
The above answers regarding @JsonProperty
and CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
are 100% accurate, although some people (like me) might be trying to do this inside a Spring MVC application with code-based configuration. Here's sample code (that I have inside Beans.java
) to achieve the desired effect:
@Bean
public ObjectMapper jacksonObjectMapper() {
return new ObjectMapper().setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
On Linux the command is whereis. Alternatively you can issue find / -name git
and wait for an eternity. Alternatively try echo $PATH | sed "s/:/ /g" | xargs -L 1 ls | grep git
Python includes a function called itemgetter to return the item at a specific index in a list:
from operator import itemgetter
Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:
itemgetter(0)([10, 20, 30]) # Returns 10
This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:
my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']
Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:
lst2.append(list(map(itemgetter(0), lst)))
This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.
More info: https://docs.python.org/3/library/operator.html#operator.itemgetter
Here is a way to handle duplicate tuple "keys":
# An example
l = [('A', 1), ('B', 2), ('C', 3), ('A', 5), ('D', 0), ('D', 9)]
# A solution
d = dict()
[d [t [0]].append(t [1]) if t [0] in list(d.keys())
else d.update({t [0]: [t [1]]}) for t in l]
d
OUTPUT: {'A': [1, 5], 'B': [2], 'C': [3], 'D': [0, 9]}
You have it covered aside from using the wrong property. The scrollbar can be triggered with any property overflow
, overflow-x
, or overflow-y
and each can be set to any of visible
, hidden
, scroll
, auto
, or inherit
. You are currently looking at these two:
auto
- This value will look at the width and height of the box. If they are defined, it won't let the box expand past those boundaries. Instead (if the content exceeds those boundaries), it will create a scrollbar for either boundary (or both) that exceeds its length.
scroll
- This values forces a scrollbar, no matter what, even if the content does not exceed the boundary set. If the content doesn't need to be scrolled, the bar will appear as "disabled" or non-interactive.
If you always want the vertical scrollbar to appear:
You should use overflow-y: scroll
. This forces a scrollbar to appear for the vertical axis whether or not it is needed. If you can't actually scroll the context, it will appear as a"disabled" scrollbar.
If you only want a scrollbar to appear if you can scroll the box:
Just use overflow: auto
. Since your content by default just breaks to the next line when it cannot fit on the current line, a horizontal scrollbar won't be created (unless it's on an element that has word-wrapping disabled). For the vertical bar,it will allow the content to expand up to the height you have specified. If it exceeds that height, it will show a vertical scrollbar to view the rest of the content, but will not show a scrollbar if it does not exceed the height.
When you must return specified type:
Task.FromResult<MyClass>(null);
The JSONP comes to mind:
JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.
If you don't have the latest Homebrew: I "fixed" this in the past by forcing Homebrew to run as root, which could only be done by changing the ownership of the Homebrew executables to root. At some point, they removed this feature.
And I know they'll give lots of warnings saying it shouldn't run as root, but c'mon, it doesn't work properly otherwise.
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
I had to make SQL scripts often and add them to source control and send them to DBA. I used this ExcelIntoSQL App from windows store https://www.microsoft.com/store/apps/9NH0W51XXQRM It creates complete script with "CREATE TABLE" and INSERTS.
The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'.
By default, the router checks URL elements from the left to see if the URL matches a given path, and stops when there is a match. For example, '/team/11/user' matches 'team/:id'.
The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.
Try with the following line:
CleanString = Application.WorksheetFunction.Clean(MyString)
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
Simple solution for cast pointer to object
class myClass
{
public:
void sayHello () {
cout << "Hello";
}
};
int main ()
{
myClass* myPointer;
myClass myObject = myClass(* myPointer); // Cast pointer to object
myObject.sayHello();
return 0;
}
I had same problem.
The cause was that I declared same global variable in 2 files. So it was showing same error saying 2 duplicate symbols.
The solution was to remove those variables.
I use:
logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
This is what I did for the instagram API. converted timestamp with date method by multiplying by 1000. and then added all entity individually like (year, months, etc)
created the custom month list name and mapped with getMonth()
method which returns the index of the month.
convertStampDate(unixtimestamp){
// Unixtimestamp
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// filtered fate
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and thats it.
Well, I'm not sure if my solution is best practice. Using the NotificationBuilder
my code looks like that:
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
Manifest:
<activity
android:name=".MainActivity"
android:launchMode="singleInstance"
</activity>
and here the Service:
<service
android:name=".services.ProtectionService"
android:launchMode="singleTask">
</service>
I don't know if there really is a singleTask
at Service
but this works properly at my application...
Adding a branch
option in .gitmodule
is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.
From git submodule --help
, HEAD detached is the default behavior of git submodule update --remote
.
First, there's no need to specify a branch to be tracked. origin/master
is the default branch to be tracked.
--remote
Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (
branch.<name>.remote
), defaulting toorigin
. The remote branch used defaults tomaster
.
So why is HEAD detached after update
? This is caused by the default module update behavior: checkout
.
--checkout
Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override
submodule.$name.update
when set to a value other thancheckout
.
To explain this weird update behavior, we need to understand how do submodules work?
Quote from Starting with Submodules in book Pro Git
Although sbmodule
DbConnector
is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.
The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.
If you want the submodule merged with remote branch automatically, use --merge
or --rebase
.
--merge
This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.
--rebase
Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.
All you need to do is,
git submodule update --remote --merge
# or
git submodule update --remote --rebase
Recommended alias:
git config alias.supdate 'submodule update --remote --merge'
# do submodule update with
git supdate
There's also an option to make --merge
or --rebase
as the default behavior of git submodule update
, by setting submodule.$name.update
to merge
or rebase
.
Here's an example about how to config the default update behavior of submodule update in .gitmodule
.
[submodule "bash/plugins/dircolors-solarized"]
path = bash/plugins/dircolors-solarized
url = https://github.com/seebi/dircolors-solarized.git
update = merge # <-- this is what you need to add
Or configure it in command line,
# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge
git submodule --help
If you're running these commands in a Docker container on Windows, it may mean that your docker machine's network connection is stale and needs to be rebuilt. To fix it, run these commands:
docker-machine stop
docker-machine start
@FOR /f "tokens=*" %i IN ('docker-machine env') DO @%i
No, it doesn't, see: R Language Definition: Operators
You need create /home/yozloy/html/test
folder. Or you can use alias
like below show:
location /test {
alias /home/yozloy/html/;
autoindex on;
}
In general, the most appropriated way to avoid this problem, (also because of better Mockito integration in JUnit) is to use the Setter/Field Injection as described at https://www.baeldung.com/circular-dependencies-in-spring and at https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
@Component("bean1")
@Scope("view")
public class Bean1 {
private Bean2 bean2;
@Autowired
public void setBean2(Bean2 bean2) {
this.bean2 = bean2;
}
}
@Component("bean2")
@Scope("view")
public class Bean2 {
private Bean1 bean1;
@Autowired
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
}
I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up. As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.
$('#userNav').change(function() {
window.location = $(':selected',this).attr('href')
});
<select id="userNav">
<option></option>
<option href="http://google.com">Goolge</option>
<option href="http://duckduckgo.com">Go Go duck</option>
</select>
This works for the href in an option that is selected
I had this problem when trying to run Rails in a subdirectory, and not in /
. For example, I had Angular/Node/Gulp app running in /client
and a Rails app running in /server
, but both of them were in the same git repo, so I could track changes across the front end and back end. I got this error when trying to deploy them to Heroku. For anyone else having this issue, here is a custom buildpack that will allow running Rails in a subdirectory.
Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length]
+ 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:
I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).
As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.
Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!
I've deleted java files at windows/system32 and I also have removed c:\ProgramData\Oracle\Java\javapath from the PATH variable, because there was 3 symlinks to java 1.8 files.
I had JDK 1.7 in the %JAVA_HOME% variable and java1.7/bin in the PATH.
PS1: My problem was between Java 1.7 and Java 1.8.
PS2: I can't add this as a comment to Victor's answer because I haven't enough points.
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
It's entirely likely that a large portion of the developer base comes from a Java background where using ==
to compare strings is wrong and doesn't work.
In C# there's no (practical) difference (for strings) as long as they are typed as string.
If they are typed as object
or T
then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.
You can use ResolveUrl
<link type="text/css" rel="stylesheet" href="<%=Page.ResolveUrl("~/Content/table-sorter.css")%>" />
When you run git commit
with no arguments, it will open your default editor to allow you to type a commit message. Saving the file and quitting the editor will make the commit.
It looks like your default editor is Vi or Vim. The reason "weird stuff" happens when you type is that Vi doesn't start in insert mode - you have to hit i on your keyboard first! If you don't want that, you can change it to something simpler, for example:
git config --global core.editor nano
Then you'll load the Nano editor (assuming it's installed!) when you commit, which is much more intuitive for users who've not used a modal editor such as Vi.
That text you see on your screen is just to remind you what you're about to commit. The lines are preceded by #
which means they're comments, i.e. Git ignores those lines when you save your commit message. You don't need to type a message per file - just enter some text at the top of the editor's buffer.
To bypass the editor, you can provide a commit message as an argument, e.g.
git commit -m "Added foo to the bar"
When you really want to write an i-test for a spring data repository you can do it like this:
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(basePackageClasses = WebBookingRepository.class)
@EntityScan(basePackageClasses = WebBooking.class)
public class WebBookingRepositoryIntegrationTest {
@Autowired
private WebBookingRepository repository;
@Test
public void testSaveAndFindAll() {
WebBooking webBooking = new WebBooking();
webBooking.setUuid("some uuid");
webBooking.setItems(Arrays.asList(new WebBookingItem()));
repository.save(webBooking);
Iterable<WebBooking> findAll = repository.findAll();
assertThat(findAll).hasSize(1);
webBooking.setId(1L);
assertThat(findAll).containsOnly(webBooking);
}
}
To follow this example you have to use these dependencies:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
jsfiddle: http://jsfiddle.net/mgtoz4d3/
I added a container which contains both buttons. Try this:
CSS:
#button1{
width: 300px;
height: 40px;
}
#button2{
width: 300px;
height: 40px;
}
#container{
text-align: center;
}
HTML:
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
<br><br>
<div id="container">
<button type="button home-button" id="button1" >Home</button>
<button type="button contact-button" id="button2">Contact Us</button>
</div>
If you are adventurous you can also get the source code and latest release of MsBuild from GitHub now at https://github.com/Microsoft/msbuild/releases/
Echo the session object as json. I like json because I have a browser extension that nicely formats json.
session_start();
echo json_encode($_SESSION);
I've been playing around with this, as I love my enums. =)
Using Object.defineProperty
I think I came up with a somewhat viable solution.
Here's a jsfiddle: http://jsfiddle.net/ZV4A6/
Using this method.. you should (in theory) be able to call and define enum values for any object, without affecting other attributes of that object.
Object.defineProperty(Object.prototype,'Enum', {
value: function() {
for(i in arguments) {
Object.defineProperty(this,arguments[i], {
value:parseInt(i),
writable:false,
enumerable:true,
configurable:true
});
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
Because of the attribute writable:false
this should make it type safe.
So you should be able to create a custom object, then call Enum()
on it. The values assigned start at 0 and increment per item.
var EnumColors={};
EnumColors.Enum('RED','BLUE','GREEN','YELLOW');
EnumColors.RED; // == 0
EnumColors.BLUE; // == 1
EnumColors.GREEN; // == 2
EnumColors.YELLOW; // == 3
This error can also be caused by simply missing a comma ,
between the column names in the SELECT statement.
eg:
SELECT MyCol1, MyCol2 MyCol3 FROM SomeTable;
Each resource has references to other resources, either in hierarchy or links, so it's easy to browse around. This is an advantage to the human developing the client, saving he/she from constantly consulting the docs, and offering suggestions. It also means the server can change resource names unilaterally (as long as the client software doesn't hardcode the URLs).
You can CURL your way into any part of the API or use the web browser to navigate resources. Makes debugging and testing integration much easier.
Allows you to specify actions without having to hunt the correct wording. Imagine if OOP getters and setters weren't standardized, and some people used retrieve
and define
instead. You would have to memorize the correct verb for each individual access point. Knowing there's only a handful of verbs available counters that problem.
If you GET
a resource that doesn't exist, you can be sure to get a 404
error in a RESTful API. Contrast it with a non-RESTful API, which may return {error: "Not found"}
wrapped in God knows how many layers. If you need the extra space to write a message to the developer on the other side, you can always use the body of the response.
Imagine two APIs with the same functionality, one following REST and the other not. Now imagine the following clients for those APIs:
RESTful:
GET /products/1052/reviews
POST /products/1052/reviews "5 stars"
DELETE /products/1052/reviews/10
GET /products/1052/reviews/10
HTTP:
GET /reviews?product_id=1052
POST /post_review?product_id=1052 "5 stars"
POST /remove_review?product_id=1052&review_id=10
GET /reviews?product_id=1052&review=10
Now think of the following questions:
If the first call of each client worked, how sure can you be the rest will work too?
There was a major update to the API that may or may not have changed those access points. How much of the docs will you have to re-read?
Can you predict the return of the last query?
You have to edit the review posted (before deleting it). Can you do so without checking the docs?
My two cents in this chain:
Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar
instead of ~/lib/some_lib.jar
) otherwise you can still face NoClassDefFoundError
error.
I am using a spreadsheet with headers in row 1, data are in rows 2 and below.
IDs are in column A. To count how many different values there are I put this formula from row 2 to the end of the spreadsheet of the first available column [F in my case] : "=IF(A2=A1,F1+1,1)"
.
Then I use the following formula in a free cell: "=COUNTIF(F:F,1)"
. In this way I am sure every ID is counted.
Please note that IDs must be sorted, otherwise they will be counted more than once...but unlike array formulas it is very fast even with a 150000 rows spreadsheet.
React gives a security issue when using a
tag with target="_blank"
.
I managed to get it working like that:
<a href={uploadedFileLink} target="_blank" rel="noopener noreferrer" download>
<Button>
<i className="fas fa-download"/>
Download File
</Button>
</a>
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in (over)write mode
[it overwrites the file if it already exists]
r+ open an existing file in read+write mode
a+ create file if it doesn't exist and open it in append mode
'''
example:
file_name = 'my_file.txt'
f = open(file_name, 'a+') # open file in append mode
f.write('python rules')
f.close()
I hope this helps. [FYI am using python version 3.6.2]
This error happened to me when I forgot to change entity Properties before creating NSManagedObject subclass. Solved by:
Entity+CoreDataClass.swift
and Entity+CoreDataProperties.swift
.Current Product Module
and "codegen" to Manual/None
.None of the above things worked for me as I had multiple recipients both in 'to' and 'cc'. So I tried like below:
recipients = ['[email protected]', '[email protected]']
cc_recipients = ['[email protected]', '[email protected]']
MESSAGE['To'] = ", ".join(recipients)
MESSAGE['Cc'] = ", ".join(cc_recipients)
and extend the 'recipients' with 'cc_recipients' and send mail in trivial way
recipients.extend(cc_recipients)
server.sendmail(FROM,recipients,MESSAGE.as_string())
I think the only cookie you need is JSESSIONID=xxx..
Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.
The List class's constructor can convert an IQueryable for you:
public static List<TResult> ToList<TResult>(this IQueryable source)
{
return new List<TResult>(source);
}
or you can just convert it without the extension method, of course:
var list = new List<T>(queryable);
In order to see images, plots and anything displayed on windows on your remote machine you need to connect to it like this:
ssh -X user@hostname
That way you enable the access to the X server. The X server is a program in the X Window System that runs on local machines (i.e., the computers used directly by users) and handles all access to the graphics cards, display screens and input devices (typically a keyboard and mouse) on those computers.
More info here.
To exclude dotfiles in base directory:
scp -r [!.]* server:/path/to/something
[!.]*
is a shell glob that expands to all files in working directory not starting with a dot.
Check the PID i.e. id of process running on port 3000 with below command :
lsof -i tcp:3000
It would output something like following:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 5805 xyz 12u IPv6 63135 0t0 TCP *:3000 (LISTEN)
Now kill the process using :
kill -9 5805
I found a better solution on the Chrome product forums by a user called Gary. The original thread is here.
Navigate to C:\Windows\System32\GroupPolicy
Open each subdirectory there and change the *.pol
files to *.sav
, E.g. registry.pol
becomes registry.sav
.
Hit Windows-Key + R, type the following in the box and hit enter
reg delete HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome
In the command promt window that opens type: Yes and press Enter.
Restart Google Chrome and check whether you can change the search engine.
in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
I had the same problem, and found a detailed explanation in http://www.webmasterworld.com/apache/3163397.htm
My solution (the subdomains contents should be in a folder called sd_subdomain
:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} subdomain\.domain\.com
RewriteCond $1 !^sd_
RewriteRule (.*) /sd_subdomain/$1 [L]
You can use Unpack list:
a = 5
li = [1,2,3]
li = [a, *li]
=> [5, 1, 2, 3]
This is what I knocked together to solve my immediate problem.
private void ExecuteBatchNonQuery(string sql, SqlConnection conn) {
string sqlBatch = string.Empty;
SqlCommand cmd = new SqlCommand(string.Empty, conn);
conn.Open();
sql += "\nGO"; // make sure last batch is executed.
try {
foreach (string line in sql.Split(new string[2] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries)) {
if (line.ToUpperInvariant().Trim() == "GO") {
cmd.CommandText = sqlBatch;
cmd.ExecuteNonQuery();
sqlBatch = string.Empty;
} else {
sqlBatch += line + "\n";
}
}
} finally {
conn.Close();
}
}
It requires GO commands to be on their own line, and will not detect block-comments, so this sort of thing will get split, and cause an error:
ExecuteBatchNonQuery(@"
/*
GO
*/", conn);
No, it probably is actually working. It's just not readily visible. Instead of just using the header
call, try doing that, then including 404.php
, and then calling die
.
You can test the fact that the HTTP/1.0 404 Not Found
works by creating a PHP file named, say, test.php
with this content:
<?php
header("HTTP/1.0 404 Not Found");
echo "PHP continues.\n";
die();
echo "Not after a die, however.\n";
Then viewing the result with curl -D /dev/stdout
reveals:
HTTP/1.0 404 Not Found
Date: Mon, 04 Apr 2011 03:39:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.2
Content-Length: 14
Connection: close
Content-Type: text/html
PHP continues.
Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.
A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId
attribute set to True
, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show
without creating a new instance of the class.
Step away from this, and treat your form as an object instead - expose Property Get
members and abstract away the form's controls - the calling code doesn't care about controls anyway:
Option Explicit
Private cancelling As Boolean
Public Property Get UserId() As String
UserId = txtUserId.Text
End Property
Public Property Get Password() As String
Password = txtPassword.Text
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelling
End Property
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
cancelling = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
cancelling = True
Cancel = True
Me.Hide
End If
End Sub
Now the calling code can do this (assuming the UserForm was named LoginPrompt
):
With New LoginPrompt
.Show vbModal
If .IsCancelled Then Exit Sub
DoSomething .UserId, .Password
End With
Where DoSomething
would be some procedure that requires the two string parameters:
Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
'work with the parameter values, regardless of where they came from
End Sub
This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php
<?php
## DEFINE ROOTPATH
$check_data_exist = "";
$i_surf = 0;
// looking for mainpath.php at the aktiv folder or higher folder
while (!file_exists($check_data_exist."mainpath.php")) {
$check_data_exist .= "../";
$i_surf++;
// max 7 folder deep
if ($i_surf == 7) {
return false;
}
}
define("MAINPATH", ($check_data_exist ? $check_data_exist : ""));
?>
For me is that the best and easiest way to find them. ^^
About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.
Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:
IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.
Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.
The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".
In R, we can use the functions mGCD(x) and mLCM(x) from the package numbers, to compute the greatest common divisor and least common multiple for all numbers in the integer vector x together:
library(numbers)
mGCD(c(4, 8, 12, 16, 20))
[1] 4
mLCM(c(8,9,21))
[1] 504
# Sequences
mLCM(1:20)
[1] 232792560
You could use search or match for this.
str.search( 'Yes' )
will return the position of the match, or -1 if it isn't found.
C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.
In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.
Of course, when you try to link, and it can't find foo, then you will get an error.
In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.
OK, there are just 2 different ways to do the same thing! One called object literal
and the other one is a function constructor
!
But read on, there are couple of things I'd like to share:
Using {}
makes your code more readable, while creating instances of Object
or other built-in functions not recommended...
Also, Object function gets parameters as it's a function, like Object(params)
... but {}
is pure way to start an object in JavaScript...
Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...
While Object in Javascript can be almost anything, {}
only points to javascript objects, for the test how it works, do below in your javascript code or console:
var n = new Object(1); //Number {[[PrimitiveValue]]: 1}
Surprisingly, it's creating a Number!
var a = new Object([1,2,3]); //[1, 2, 3]
And this is creating a Array!
var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}
and this weird result for String
!
So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {}
is better in my experience!
Below command can be used for finding both package and current Activity name. Found this very useful command to quickly fetch these two information about an app especially when developing tests with Appium.
adb shell dumpsys window windows | grep -E 'mCurrentFocus'
Response of this command contains both package name and current Activity. For example: in following "com.android.contacts" is the package and "com.android.contacts.activities.TwelveKeyDialer" is current Activity launched on the phone which is connected via adb.
mCurrentFocus=Window{2089af8 u0 com.android.contacts/com.android.contacts.activities.TwelveKeyDialer}
Reference: http://www.automationtestinghub.com/apppackage-and-appactivity-name/
In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.
The default password for Mariadb is blank.
$ mysql -u root -p
Enter Password: <--- press enter
To import SQL file what works for me
For Wamp-Server
- Find mysql in wamp. In my computer it's location is "C:\wamp64\bin\mysql\mysql5.7.21\bin"
Open cmd and once you get inside bin you have to write " mysql -uroot -p database_name < filename.sql"
remember to put sql file under bin.
in nutshell you have to do this:-
C:\wamp64\bin\mysql\mysql5.7.21\bin>mysql -uroot -p database_name < filename.sql
After this, it will ask for the password, mine password was nothing(BLANK).
hope it helps someone.
You can multiply a list
by an integer n
to repeat the list
n
times:
buckets = [0] * 100
onchange
will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.
So it is better to use onblur
event or on submitting the form.
function checkTextField(field) {_x000D_
document.getElementById("error").innerText =_x000D_
(field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
Its possible, but not directly.
In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.
In the search menu there is a point "delete bookmarked lines" voila.
I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?
Another method through re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Above regex would match one or more non-space characters.
You don't mention what environment you're running in, which makes a big difference because there isn't a pure Python web browser that's capable of rendering HTML.
But if you're using a Mac, I've used webkit2png with great success. If not, as others have pointed out there are plenty of options.
if (chapeau) {
You forgot the ending brace to this if
statement, so the subsequent else if
is considered a syntax error. You need to add the brace when the if
statement body is complete:
if (chapeau) {
cout << "le Professeur Violet";
}
else if (moustaches) {
cout << "le Colonel Moutarde";
}
// ...
You are very close.
You applied the round to the series of values given by df.value1
.
The return type is thus a Series.
You need to assign that series back to the dataframe (or another dataframe with the same Index).
Also, there is a pandas.Series.round
method which is basically a short hand for pandas.Series.apply(np.round)
.
In[2]:
df.value1 = df.value1.round()
print df
Out[2]:
item value1 value2
0 a 1 1.3
1 a 2 2.5
2 a 0 0.0
3 b 3 -1.0
4 b 5 -1.0
for importing the image in flask you want a sub folder named static into the folder keep your img
and go into your html file and write
The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site
<head>
<base href="~/" />
</head>
It specifies the axis along which the means are computed. By default axis=0
. This is consistent with the numpy.mean
usage when axis
is specified explicitly (in numpy.mean
, axis==None by default, which computes the mean value over the flattened array) , in which axis=0
along the rows (namely, index in pandas), and axis=1
along the columns. For added clarity, one may choose to specify axis='index'
(instead of axis=0
) or axis='columns'
(instead of axis=1
).
+------------+---------+--------+
| | A | B |
+------------+---------+---------
| 0 | 0.626386| 1.52325|----axis=1----->
+------------+---------+--------+
| |
| axis=0 |
? ?
#table
refers to a local (visible to only the user who created it) temporary table.
##table
refers to a global (visible to all users) temporary table.
@variableName
refers to a variable which can hold values depending on its type.
To turn it off:
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
To turn it back on:
ActiveRecord::Base.logger = old_logger
Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.
Option 1: Probably the simplest way is to include your helper module in your controller:
class MyController < ApplicationController
include MyHelper
def xxxx
@comments = []
Comment.find_each do |comment|
@comments << {:id => comment.id, :html => html_format(comment.content)}
end
end
end
Option 2: Or you can declare the helper method as a class function, and use it like so:
MyHelper.html_format(comment.content)
If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:
module MyHelper
def self.html_format(str)
process(str)
end
def html_format(str)
MyHelper.html_format(str)
end
end
Hope this helps!
This happened to me when an web request endpoint was switched to another server that accepted TLS1.2 requests only. Tried so many attempts mostly found on Stackoverflow like
The exception received did no make justice to the actual problem I was facing and found no help from the service operator.
To solve this I have to add a new Cipher Suite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 I have used IIS Crypto 2.0 Tool from here as shown below.
Here's how to do it using default ACLs, at least under Linux.
First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl
option. In that case, add the option to your /etc/fstab
. For example, if the directory is located on your root filesystem:
/dev/mapper/qz-root / ext3 errors=remount-ro,acl 0 1
Then remount it:
mount -oremount /
Now, use the following command to set the default ACL:
setfacl -dm u::rwx,g::rwx,o::r /shared/directory
All new files in /shared/directory
should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp
, tar
, and rsync
will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.
Hope this helps!
Click Start | Run and type regedit
in the Open: line. Click OK.
Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
Scroll down the left pane, locate the service name, right click it and select Delete.
Reboot the system.
try this if you need to convert black image into white:
.classname{
filter: brightness(0) invert(1);
}
Although it creates a little clutter, it is worth putting final
. Ides e.g eclipse can automatically put the final
if you configure it to do so.
Several definitions of the same name
<C-w>g<C-]>
open the definition in a split, but also do :tjump
which either goes to the definition or, if there are several definitions, presents you with a list of definitions to choose from.
Create Language Table ‘languages’:
Fields:
language_id(primary and auto increamented)
language_name
created_at
created_by
updated_at
updated_by
Create a table in database ‘content’:
Fields:
content_id(primary and auto incremented)
main_content
header_content
footer_content
leftsidebar_content
rightsidebar_content
language_id(foreign key: referenced to languages table)
created_at
created_by
updated_at
updated_by
When user selects any language from dropdown or any area then save selected language id in session like,
$_SESSION['language']=1;
Now fetch data from database table ‘content’ based on language id stored in session.
Detail may found here http://skillrow.com/multilingual-website-in-php-2/
The key is a Textview with singleline=false
(which yes is deprecated, but is a must have to work) combined with lines
, maxlines
or minlines
<TextView
android:id="@+id/txtBowlers"
style="@style/Default_TextBox.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:singleLine="false"
android:maxLines="6"
android:text="Bob\nSally\nJohn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/txtTeamName"
app:layout_constraintTop_toBottomOf="@+id/txtTeamName"/>
The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.
I use this script to enable on a server, if the option is disabled:
if not exists(
SELECT value
FROM sys.configurations
WHERE name = 'clr enabled'
and value = 1
)
begin
exec sp_configure @configname=clr_enabled, @configvalue=1
reconfigure
end
If you use OmniFaces you can also use it's EL functions like of:formatDate()
to format Date
objects. You would use it like this:
<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />
This way you can not only use it for output but also to pass it on to other JSF components.
From your code
<input type=button value="Select" onClick="sendValue(this.form.details);"
Im not sure that your this.form.details
valid or not.
IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;
I can't found an input's id contain details
I'm just found only id=sku1
(recommend you to add "
like id="sku1"
).
And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.
<html>
<head>
<script>
function callFromDialog(id,data){ //for callback from the dialog
document.getElementById(id).value = data;
// do some thing other if you want
}
function choose(id){
var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
}
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>
Look in function choose
I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#
)
<html>
<head>
<script>
function goSelect(data){
var idFromCallPage = getUrlVars()["id"];
window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
window.close();
}
function getUrlVars(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>
I have add function getUrlVars for get URL param that the parent has pass to child.
Okay, when select data in the popup, for this case it's will call function goSelect
In that function will get URL param to sent back.
And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog
By fully is window.opener.callFromDialog(idFromCallPage,data);
Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data;
It's ok too.
You might output your DataFrame
as a csv file and then use mysqlimport
to import your csv into your mysql
.
Seems pandas's build-in sql util provide a write_frame
function but only works in sqlite.
I found something useful, you might try this