Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
can not be called.
This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
is a "non-object" because the value is a boolean.
Figure out why your function returned a boolean instead of an object. For example, check the $pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.
If even the ->prepare
is failing then your $pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.
Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
I might be a little late, but after spending hours and researching on this issue.
I found out that in the latest version IntelliJ 2020 @AutoWired is optional and constructor based depedency injection is preferable.
I sloved the problem by simply removing the @AutoWired Annotation from Service and Controller class and using constructor based dependency injection.
This link might help.
Happy Coding!
@blytung Has a nice function to replace that function
<?php
$url = "http://www.example.org/";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$contents = '';
} else {
curl_close($ch);
}
if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}
echo $contents;
?>
I am using MariaDB and have the similar problem.
From MariaDB site, it is recommended to fix it by
Run with a lower error reporting level:
$err_level = error_reporting(0);
$conn = mysql_connect('params');
error_reporting($err_level);
My problem fixed by using the mysqlnd driver in Ubuntu:
sudo apt-get install php5-mysqlnd
Cheers!
[update: extra information] Installing this driver also resolve PDO problem that returns integer value as a string. To keep the type as integer, after installing mysqlInd, do this
$db = new PDO('mysql:host='.$host.';dbname='.$db_name, $user, $pass,
array( PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
Try presenting on TabBarController
if it is a TabBarController
based app .
[self.tabBarController presentViewController:viewController animated:YES completion:nil];
Reason could be self
is child of TabBarController
and you are trying to present from a ChildViewController
.
For the benefit of others, I though I'd include what I did.
Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.
BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.
My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.
So for the "Debug" configuraton, I edited:
Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from
$(IntDir)vc$(PlatformToolsetVersion).pdb
to be the following value:
$(OutDir)vc$(PlatformToolsetVersion)D$(ProjectName).pdb
Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.
I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.
Adding _CRT_SECURE_NO_WARNINGS
to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn't work for me, don't know why.
The following hint works: In stdafx.h file, please add
#define _CRT_SECURE_NO_DEPRECATE
before include other header files.
You can use property_exists
http://www.php.net/manual/en/function.property-exists.php
I had the same error here MacOSX 10.6.8 - it seems ruby checks to see if any directory (including the parents) in the path are world writable. In my case there wasn't a /usr/local/bin present as nothing had created it.
so I had to do
sudo chmod 775 /usr/local
to get rid of the warning.
A question here is does any non root:wheel process in MacOS need to create anything in /usr/local ?
You are returning char, and not char*, which is the pointer to the first character of an array.
If you want to return a new character array instead of doing in-place modification, you can ask for an already allocated pointer (char*) as parameter or an uninitialized pointer. In this last case you must allocate the proper number of characters for new string and remember that in C parameters as passed by value ALWAYS, so you must use char** as parameter in the case of array allocated internally by function. Of course, the caller must free that pointer later.
Whenever you are working with csv imports, try to use df.dropna() to avoid all such warnings or errors.
one
has not been assigned so points to an unpredictable location. You should either place it on the stack:
Vector one;
one.a = 12;
one.b = 13;
one.c = -11
or dynamically allocate memory for it:
Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);
Note the use of free
in this case. In general, you'll need exactly one call to free
for each call made to malloc
.
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
Your problem is that at the moment your incoming_Cid
column defined as CHAR(1)
when it should be CHAR(34)
.
To fix this just issue this command to change your columns' length from 1 to 34
ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);
Here is SQLFiddle demo
If you just want to suppress warnings from a function, you can add an @
sign in front:
<?php @function_that_i_dont_want_to_see_errors_from(parameters); ?>
I think that better solution is configuration of .htaccess In that way you dont have to alter code of application. Here are directives for Apache2
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
JSL 1.7
The Oracle documentation mentions:
unchecked
: Unchecked warnings are identified by the string "unchecked". deprecation
: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); orIt then explains that implementations can add and document their own:
Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.
@
operatorFor undesired and redundant notices, one could use the dedicated @
operator to »hide« undefined variable/index messages.
$var = @($_GET["optional_param"]);
isset?:
or ??
super-supression however. Notices still can get logged. And one may resurrect @
-hidden notices with: set_error_handler("var_dump");
if (isset($_POST["shubmit"]))
in your initial code.@
or isset
only after verifying functionality.Fix the cause first. Not the notices.
@
is mainly acceptable for $_GET
/$_POST
input parameters, specifically if they're optional.And since this covers the majority of such questions, let's expand on the most common causes:
$_GET
/ $_POST
/ $_REQUEST
undefined inputFirst thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Secondly, if the notice doesn't have an obvious cause, use var_dump
or print_r
to verify all input arrays for their curent content:
var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);
Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For $_GET
parameters you can also peek at the QUERY_STRING
in
print_r($_SERVER);
PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well.
You can also look at supplied raw $_COOKIES
and other HTTP request headers that way.
More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The name=value
pairs after the ?
question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"]
and $_GET["sort"]
.
Finally check your <form>
and <input>
declarations, if you expect a parameter but receive none.
<input name=FOO>
id=
or title=
attribute does not suffice.method=POST
form ought to populate $_POST
.method=GET
(or leaving it out) would yield $_GET
variables.action=script.php?get=param
via $_GET and the remaining method=POST
fields in $_POST alongside.$_REQUEST['vars']
again, which mashes GET and POST params.If you are employing mod_rewrite, then you should check both the access.log
as well as enable the RewriteLog
to figure out absent parameters.
$_FILES
$_FILES["formname"]
.enctype=multipart/form-data
method=POST
in your <form>
declaration.$_COOKIE
$_COOKIE
array is never populated right after setcookie()
, but only on any followup HTTP request.You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
You shouldn't raise
the warning, you should be using warnings
module. By raising it you're generating error, rather than warning.
The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...)
with just else
.
IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.
Yochai, if you ever read this, please see the note at the end.
For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library
one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked
while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking
Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.
Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.
[...] trawl through all your libraries and ensure they have the correct link settings
In the latter, as it in mentioned in the original post, two common problems can arise :
You have a third party library which is linked differently to your application.
You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.
For those cases, ensure you understand the problem and decide among the solutions.
Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry
The error seem to appear when u have more than one reference of the same file. I had 2 files of the same name and got this error. When I delete one of them the error disappear..
Remove warnings.filterwarnings and add:
numpy.seterr(all='raise')
Here is a flexible approach, it can be used in all cases, in particular:
dataframe
has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).First, un-factorize a string using the as.character
function, and, then, re-factorize with the as.factor
(or simply factor
) function:
fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
# Un-factorize (as.numeric can be use for numeric values)
# (as.vector can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)
# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)
Because until the constructor has completed executing, the object is not fully instantiated. Any members referenced by the virtual function may not be initialised. In C++, when you are in a constructor, this
only refers to the static type of the constructor you are in, and not the actual dynamic type of the object that is being created. This means that the virtual function call might not even go where you expect it to.
Just incase it helps anyone, I was getting this error because I forgot to unserialize a serialized array. That's definitely something I would check if it applies to your case.
At the time of writing this (May 2018), FindBugs seems to have been replaced by SpotBugs. Using the SuppressFBWarnings
annotation requires your code to be compiled with Java 8 or later and introduces a compile time dependency on spotbugs-annotations.jar
.
Using a filter file to filter SpotBugs rules has no such issues. The documentation is here.
If I have to use an API that doesn't support Generics.. I try and isolate those calls in wrapper routines with as few lines as possible. I then use the SuppressWarnings annotation and also add the type-safety casts at the same time.
This is just a personal preference to keep things as neat as possible.
In my case this was being issued by wp cli
, and the problem was that I didn't have php7.3-curl
installed. Fixed with: apt-get install -y --quiet php7.3-curl
From documentation of the warnings
module:
#!/usr/bin/env python -W ignore::DeprecationWarning
If you're on Windows: pass -W ignore::DeprecationWarning
as an argument to Python. Better though to resolve the issue, by casting to int.
(Note that in Python 3.2, deprecation warnings are ignored by default.)
You can prepend an @:
$content = @file_get_contents($site);
This will supress any warning - use sparingly!. See Error Control Operators
Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.
In my case it doesn't work, even with __DIR__
or getcwd()
it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:
if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/
I have MAMP with php 5.4.10 and my folder hierarchy is basilar:
q.php
w.php
e.php
r.php
cache/a.php
cache/b.php
setting/a.php
setting/b.php
....
Set these on php.ini
:
;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on
From your PHP page, use a suitable filter for error reporting.
error_reporting(E_ALL);
Filers can be made according to requirements.
E_ALL
E_ALL | E_STRICT
#pragma
push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?
try
{
// ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
// ...
}
I have ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;
. Because value
is a complex structure (I want to clean JSON), there can happen any combinations on numbers, booleans, strings, arrays. So, I used the solution of @Dan Dyer:
@SuppressWarnings("unchecked")
ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;
I had the same issue and I resolved by changing the following in web.config.
It happened to me because I am running the application using Newtonsoft.Json 4.0
From:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
To:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="4.5.0.0" />
</dependentAssembly>
-w
is the GCC-wide option to disable warning messages.
You want options(warn=-1)
. However, note that warn=0
is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:
oldw <- getOption("warn")
options(warn = -1)
[your "silenced" code]
options(warn = oldw)
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
Thanks to the fantastic answer from Glenn, I used ImageMagik's "mogrify *.png" functionality. However, I had images buried in sub-folders, so I used this simple Python script to apply this to all images in all sub-folders and thought it might help others:
import os
import subprocess
def system_call(args, cwd="."):
print("Running '{}' in '{}'".format(str(args), cwd))
subprocess.call(args, cwd=cwd)
pass
def fix_image_files(root=os.curdir):
for path, dirs, files in os.walk(os.path.abspath(root)):
# sys.stdout.write('.')
for dir in dirs:
system_call("mogrify *.png", "{}".format(os.path.join(path, dir)))
fix_image_files(os.curdir)
This warning tries to improve accessibility of your application.
To disable missing content description warning in the whole project, you can add this to your application module build.gradle
android {
...
lintOptions {
disable 'ContentDescription'
}
}
It looks like SyndFeed
is not using generics.
You could either have an unsafe cast and a warning suppression:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();
or call Collections.checkedList - although you'll still need to suppress the warning:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);
You can use __unused
to tell the compiler that variable might not be used.
- (void)myMethod:(__unused NSObject *)theObject
{
// there will be no warning about `theObject`, because you wrote `__unused`
__unused int theInt = 0;
// there will be no warning, but you are still able to use `theInt` in the future
}
I have had this issue before, you need more than the standard 755
or 644
permission to store the $_SESSION
information. You need to be able to write to that file as that is how it remembers.
You could also use this:
ini_alter('date.timezone','Asia/Calcutta');
You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.
I had done these things before I figured out this:
date_default_timezone_set("Asia/Calcutta");
- did not workini_alter()
- IT WORKEDdate_default_timezone_set("Asia/Calcutta");
- IT WORKEDFor me the init_alter()
method got it all working.
I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion
The existing answers have quite broken code. The DNS method does not work at all. Here is code that I used to configure my NIC:
public static class NetworkConfigurator
{
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="ipAddress">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <param name="nicDescription"></param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
{
// Set new IP address and subnet if needed
if (ipAddresses != null || !String.IsNullOrEmpty(subnetMask))
{
if (ipAddresses != null)
{
newIP["IPAddress"] = ipAddresses;
}
if (!String.IsNullOrEmpty(subnetMask))
{
newIP["SubnetMask"] = Array.ConvertAll(ipAddresses, _ => subnetMask);
}
managementObject.InvokeMethod("EnableStatic", newIP, null);
}
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
{
newGateway["DefaultIPGateway"] = new[] { gateway };
newGateway["GatewayCostMetric"] = new[] { 1 };
managementObject.InvokeMethod("SetGateways", newGateway, null);
}
}
}
}
}
}
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nic">NIC address</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetNameservers(string nicDescription, string[] dnsServers)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
{
newDNS["DNSServerSearchOrder"] = dnsServers;
managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
}
}
Just close your project and re-open it again. Than SDK message appears click ok.
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
I did something similar with this construct
$('li').each(function(){
if(this.id){
this.id = this.id+"something";
}
});
They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"
Try match
:
df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]
name value
2 b TRUE
3 c FALSE
1 a TRUE
4 d FALSE
It will work as long as your target
contains exactly the same elements as df$name
, and neither contain duplicate values.
From ?match
:
match returns a vector of the positions of (first) matches of its first argument
in its second.
Therefore match
finds the row numbers that matches target
's elements, and then we return df
in that order.
Firstly the setting of IDENTITY_INSERT on or off for that matter will not work for what you require (it is used for inserting new values, such as plugging gaps).
Doing the operation through the GUI just creates a temporary table, copies all the data across to a new table without an identity field, and renames the table.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
git branch copyOfMyBranch MyBranch
This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).
Fetch the KeyListener value of EditText
by editText.getKeyListener()
and store in the KeyListener type variable, which will contain
the Editable property value:
KeyListener variable;
variable = editText.getKeyListener();
Set the Editable property of EditText
to false as:
edittext.setKeyListener(null);
Now set Editable property of EditText
to true as:
editText.setKeyListener(variable);
Note: In XML the default Editable property of EditText
should be true.
try following:
UPDATE `list` SET `test` = `number`
it creates copy of all values from "number" and paste it to "test"
You can truncate the date part:
select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')
The trouble with this approach is that any index on field1
wouldn't be used due to the function call.
Alternatively (and more index friendly)
select * from table1
where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD')
and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')
I had to specify the AWS profile to use --profile default
explicitly to get rid of this error while running AWS CLI commands. I could not understand though that why it did not pick up this profile automatically as there was only [dafault]
profile present in my aws config and credentials file.
I hope this helps.
Cheers, Kunal
Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.
One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.
This is the reason for RAII: http://en.wikipedia.org/wiki/RAII
Making a helper class with purpose of making sure that an object always deleted once in all execution paths.
Example of a class like this is: std::auto_ptr
But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.
In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.
That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.
With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.
I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.
So we can start from your example:
std::vector<gate*> G;
G.push_back(new ANDgate);
G.push_back(new ORgate);
for(unsigned i=0;i<G.size();++i)
{
G[i]->Run();
}
The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr
// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G;
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));
G.push_back(gate_ptr (new ORgate));
for(unsigned i=0;i<G.size();++i)
{
G[i]->Run();
}
When G goes out of scope the memory is automatically reclaimed.
As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
I want to expand on my readability comment above.
Again, I completely agree with readability overriding other (performance-insignificant) concerns.
What I would like to point out is the brain interprets "positive" faster than it does "negative". E.g., "stop" vs. "do not go" (a rather lousy example due to the difference in number of words).
So given a choice:
if a == b
(do this)
else
(do that)
is preferable to the functionally-equivalent:
if a != b
(do that)
else
(do this)
Less readability/understandability leads to more bugs. Perhaps not in initial coding, but the (not as smart as you!) maintenance changes...
From the command line, you can type svn mv path1 path2
. This will create an add and a delete operation, but there's not really a way around that - as far as I know - in Subversion.
It's important to point out that install
and install:install
are different things, install
is a phase, in which maven do more than just install current project modules artifacs to local repository, it check remote repository first. On the other hand, install:install
is a goal, it just build your current project and install all it's artifacts to local repository (e.g. into the .m2
directory).
Depending on your needs, you can probably rely on node's path
module.
You may not be able to hit the filesystem (e.g. the file hasn't been created yet) and tbh you probably want to avoid hitting the filesystem unless you really need the extra validation. If you can make the assumption that what you are checking for follows .<extname>
format, just look at the name.
Obviously if you are looking for a file without an extname you will need to hit the filesystem to be sure. But keep it simple until you need more complicated.
const path = require('path');
function isFile(pathItem) {
return !!path.extname(pathItem);
}
Mike Stall posted the code for one he wrote in c# here :
http://blogs.msdn.com/jmstall/archive/2006/10/20/rtf_5F00_html.aspx
As many others have pointed out here, increasing the timeout settings for NGINX can solve your issue.
However, increasing your timeout settings might not be as straightforward as many of these answers suggest. I myself faced this issue and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This did not help me a single bit; there was no apparent change in NGINX' timeout settings. Now, many hours later, I finally managed to fix this problem.
The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
// Wait up to 5 seconds with no minimum for a UI element to be found
WebDriverWait wait = new WebDriverWait(_pagedriver, TimeSpan.FromSeconds(5));
IWebElement title = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.ClassName("MainContentHeader"));
});
Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.
Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.
#include <iostream>
#include <fstream>
#include <string>
void f()
{
std::string line;
while(std::getline(std::cin, line)) //input from the file in.txt
{
std::cout << line << "\n"; //output to the file out.txt
}
}
int main()
{
std::ifstream in("in.txt");
std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
std::string word;
std::cin >> word; //input from the file in.txt
std::cout << word << " "; //output to the file out.txt
f(); //call function
std::cin.rdbuf(cinbuf); //reset to standard input again
std::cout.rdbuf(coutbuf); //reset to standard output again
std::cin >> word; //input from the standard input
std::cout << word; //output to the standard input
}
You could save and redirect in just one line as:
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect
Here std::cin.rdbuf(in.rdbuf())
sets std::cin's
buffer to in.rdbuf()
and then returns the old buffer associated with std::cin
. The very same can be done with std::cout
— or any stream for that matter.
Hope that helps.
See the docs: https://getbootstrap.com/docs/4.0/utilities/display/
In order to hide the content on mobile and display on the bigger devices you have to use the following classes:
d-none d-sm-block
The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.
I suggest to read about that before migration:
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
To go n
folders up... run up(n)
import os
def up(n, nth_dir=os.getcwd()):
while n != 0:
nth_dir = os.path.dirname(nth_dir)
n -= 1
return nth_dir
To still be able to scroll this worked for me
if (e.changedTouches.length > 1) e.preventDefault();
You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do
<head>
<?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
<title>Title</title>
</hea>
Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.
Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.
public interface ICalculator
{
void Add(int a, int b);
}
public class Calculator : ICalculator
{
public void Add(int a, int b)
{
return a + b;
}
}
You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).
IoCLlibrary.Register<ICalculator>.Return<Calculator>();
So now when you want an instance of an ICalculator you just...
Calculator calc = IoCLibrary.Resolve<ICalculator>();
IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.
Now let's say you have a class that relies on an ICalculator to be present you could have..
public class BankingSystem
{
public BankingSystem(ICalculator calc)
{
_calc = calc;
}
private ICalculator _calc;
}
And you can setup the library to inject a object into the constructor when it's created.
So DI or Dependency Injection means to inject any object another might require.
To wrap in single quotes (for example) ciw'<C-r>"'<esc>
works, but repeat won't work. Try:
ciw'<C-r><C-o>"'<esc>
This puts the contents of the default register "literally". Now you can press .
on any word to wrap it in quotes. To learn more see :h[elp] i_ctrl-r
and more about text objects at :h text-objects
Source: http://vimcasts.org/episodes/pasting-from-insert-mode/
Another option is to use the TimeUtils
utility method:
TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)
keyPressed - when the key goes down
keyReleased - when the key comes up
keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.
I personally would use keyReleased for this. It will fire only when they lift their finger up.
Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.
Maybe late, but this is how i solved it: http://jsfiddle.net/KqsK2/18/
$(document).ready(function() {
fixSelect(document.getElementsByTagName("select"));
});
function fixSelect(selectList)
{
for (var i = 0; i != selectList.length; i++)
{
setActions(selectList[i]);
}
}
function setActions(select)
{
$(select).click(function() {
if (select.getElementsByTagName("option").length == 1)
{
active(select);
}
});
$(select).focus(function() {
active(select);
});
$(select).blur(function() {
inaktiv(select);
});
$(select).keypress(function(e) {
if (e.which == 13) {
inaktiv(select);
}
});
var optionList = select.getElementsByTagName("option");
for (var i = 0; i != optionList.length; i++)
{
setActionOnOption(optionList[i], select);
}
}
function setActionOnOption(option, select)
{
$(option).click(function() {
inaktiv(select);
});
}
function active(select)
{
var temp = $('<select/>');
$('<option />', {value: 1,text:$(select).find(':selected').text()}).appendTo(temp);
$(temp).insertBefore($(select));
$(select).attr('size', select.getElementsByTagName('option').length);
$(select).css('position', 'absolute');
$(select).css('margin-top', '-6px');
$(select).css({boxShadow: '2px 3px 4px #888888'});
}
function inaktiv(select)
{
if($(select).parent().children('select').length!=1)
{
select.parentNode.removeChild($(select).parent().children('select').get(0));
}
$(select).attr('size', 1);
$(select).css('position', 'static');
$(select).css({boxShadow: ''});
$(select).css('margin-top', '0px');
}
Here's an example link you can use to see the format:
Note the key query parameters:
text
dates
details
location
Here's another example (taken from http://wordpress.org/support/topic/direct-link-to-add-specific-google-calendar-event):
<a href="http://www.google.com/calendar/render?
action=TEMPLATE
&text=[event-title]
&dates=[start-custom format='Ymd\\THi00\\Z']/[end-custom format='Ymd\\THi00\\Z']
&details=[description]
&location=[location]
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
Here's a form which will help you construct such a link if you want (mentioned in earlier answers):
https://support.google.com/calendar/answer/3033039 Edit: This link no longer gives you a form you can use
I currently use this function in my project after a series of googling to download excel file from sql statement
// $sql = sql query e.g "select * from mytablename"
// $filename = name of the file to download
function queryToExcel($sql, $fileName = 'name.xlsx') {
// initialise excel column name
// currently limited to queries with less than 27 columns
$columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
// Execute the database query
$result = mysql_query($sql) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// fetch result set column information
$finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter
$columnlenght = 0;
foreach ($finfo as $val) {
// set column header values
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
}
// make the column headers bold
$objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);
$rowCount++;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
for ($i = 0; $i < $columnLenght; $i++) {
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
}
$rowCount++;
}
// set header information to force download
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('php://output');
}
It means you allow every (*
) user-agent/crawler to access the root (/
) of your site. You're okay.
Given that the remote repository has been cached via git fetch
it should be possible to compare against these commits. Try the following:
$ git fetch origin
$ git diff origin/master
You can also check single value in multiple arrays like,
if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
print "found it\n";
}
I think init_js should use declare instead of local!
function scan3() {
declare -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
The solution for me was to add :
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
</system.webServer>
To my web.config
As rule-of-thumb there are two kinds of members:
Maybe a little late to the party but why don't you use sessions to store your data?
bookingfacilities.php
session_start();
$_SESSION['form_date'] = $date;
successfulbooking.php
session_start();
$date = $_SESSION['form_date'];
Nobody will see this.
your code would be
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [a[1],a[5],a[7]]
print(ind_pos)
you get [88, 85, 16]
Take a look at this page on implementing graphs in python.
You could also take a look at pygraphlib on sourceforge.
Very easily done with Post build task plugin.
I was using groovy+springboot and got this error.
Adding getter/setter is enough if we are using below dependency.
implementation 'org.springframework.boot:spring-boot-starter-web'
As Jackson core classes come with it.
After using following load balancer setting my problem solved for wss but for ws problem still exists for specific one ISP.
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
DateTime does not know its timezone offset. There is no built-in method to return the offset or the timezone name (e.g. EAT, CEST, EST etc).
Like suggested by others, you can convert your date to UTC:
DateTime localtime = new DateTime.Now;
var utctime = localtime.ToUniversalTime();
and then only calculate the difference:
TimeSpan difference = localtime - utctime;
Also you may convert one time to another by using the DateTimeOffset:
DateTimeOffset targetTime = DateTimeOffset.Now.ToOffset(new TimeSpan(5, 30, 0));
But this is sort of lossy compression - the offset alone cannot tell you which time zone it is as two different countries may be in different time zones and have the same time only for part of the year (eg. South Africa and Europe). Also, be aware that summer daylight saving time may be introduced at different dates (EST vs CET - a 3-week difference).
You can get the name of your local system time zone using TimeZoneInfo class:
TimeZoneInfo localZone = TimeZoneInfo.Local;
localZone.IsDaylightSavingTime(localtime) ? localZone.DaylightName : localZone.StandardName
I agree with Gerrie Schenck, please read the article he suggested.
You don't need to download any new software. You can use Octave Online to open .m files.
Get the current URL including the query string.
echo url()->full();
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:
<p>
Hello {
<span>World</span>
}!
</p>
or
<p>
Hello {}
<span>World</span>
{} again!
</p>
Each of these produces clean html without additional
or other extraneous markup. It creates fewer text nodes than using {' '}
, and allows using of html entities where {' hello & goodbye '}
does not.
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();
I solved the problem by cat'ing all the pems together:
cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD
(keytool didn't know what to do with a PKCS7 formatted key)
I got all the pems from letsencrypt
You can initialize the values as empty strings and fill them in later as they are found.
dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2
The event
attribute of <f:ajax>
can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on*
attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText>
component which renders <input type="text">
lists the following on*
attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):
blur
change
click
dblclick
focus
keydown
keypress
keyup
mousedown
mousemove
mouseout
mouseover
mouseup
select
Additionally, JSF has two more special event names for EditableValueHolder
and ActionSource
components, the real HTML DOM event being rendered depends on the component type:
valueChange
(will render as change
on text/select inputs and as click
on radio/checkbox inputs)action
(will render as click
on command links/buttons)The above two are the default events for the components in question.
Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange
or action
events, such as PrimeFaces <p:ajax>
which supports among others tabChange
, itemSelect
, itemUnselect
, dateSelect
, page
, sort
, filter
, close
, etc depending on the parent <p:xxx>
component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.
A recursive algorithm that parses through an XmlDocument
Here is an example - Recursively reading an xml document and using regex to get contents
Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html
$json empty
public function deleteUser($extid)
{
$path = "/rest/user/".$extid."/;token=".$this->__token;
$result = $this->curl_req($path,"**$json**","DELETE");
return $result;
}
As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.
I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (
The correct version, with the space before the bracket, would be
If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
start "\\filer\repo\lab\software\myapp\setup.exe"
pause
)
To add to Lennart Regebro's answer There is even the third way that can be used:
encoded3 = str.encode(original, 'utf-8')
print(encoded3)
Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.
A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.
Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.
In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".
The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.
You need to use <!DOCTYPE html>
for :hover to work with anything other than the <a>
tag. Try adding that to the top of your HTML.
Your ngClick
is correct; you just need the right service. $location
is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:
$location.path( '/new-page.html' );
The $location
service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.
You could also do something more flexible with a directive if you so chose:
.directive( 'goClick', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'goClick', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path( path );
});
});
};
});
And then you could use it on anything:
<button go-click="/go/to/this">Click!</button>
There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.
Try this:
vi.setBackgroundColor(Color.parseColor("#FFFF0000"));
The one place I've run across it is in containers which allocate a contiguous buffer and then fill it with objects as required. As mentioned, std::vector might do this, and I know some versions of MFC CArray and/or CList did this (because that's where I first ran across it). The buffer over-allocation method is a very useful optimization, and placement new is pretty much the only way to construct objects in that scenario. It is also used sometimes to construct objects in memory blocks allocated outside of your direct code.
I have used it in a similar capacity, although it doesn't come up often. It's a useful tool for the C++ toolbox, though.
A short example of @ChrisThompson's answer
Example:
mysql> SELECT * FROM table_1;
+----+--------+
| id | col1 |
+----+--------+
| 1 | foo |
| 2 | bar |
| 3 | foobar |
+----+--------+
3 rows in set (0.00 sec)
mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 1);
+--------------------------------------------+
| EXISTS(SELECT 1 FROM table_1 WHERE id = 1) |
+--------------------------------------------+
| 1 |
+--------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 9);
+--------------------------------------------+
| EXISTS(SELECT 1 FROM table_1 WHERE id = 9) |
+--------------------------------------------+
| 0 |
+--------------------------------------------+
1 row in set (0.00 sec)
Using an alias:
mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 1) AS mycheck;
+---------+
| mycheck |
+---------+
| 1 |
+---------+
1 row in set (0.00 sec)
Judging by the documentation for date/time functions, you should be able to do something like:
SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY
In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.
charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes
for line in open(filePath):
for char in line:
charsFromFile.append(char)
#apply code on each character here
or if you want a one liner
#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]
.
.
Edit: as agf mentions you can use itertools.chain.from_iterable
His method is better, unless you want the ability to specify which lines to grab
list(itertools.chain.from_iterable(open(filename, 'rU)))
This does however require one to be familiar with itertools, and as a result looses some readablity
If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.
Just for the record, using requests library.
import requests
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
f.close()
Though it should check for requests.get() error.
You can't wrap a <td>
element with an <a>
tag, but you can accomplish similar functionality by using the onclick
event to call a function. An example is found here, something like this function:
<script type="text/javascript">
function DoNav(url)
{
document.location.href = url;
}
</script>
And add it to your table like this:
<tr onclick="DoNav('http://stackoverflow.com/')"><td></td></tr>
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
In general, you're looking for the "Except" extension.
var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);
In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int>
of IDs)
Run This Query:
*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
>
> -- --------------------------------------------------------
>
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
>
> -- --------------------------------------------------------
>
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> -- 'pma'@localhost;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__bookmark`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__bookmark` ( `id` int(10) unsigned
> NOT NULL auto_increment, `dbase` varchar(255) NOT NULL default '',
> `user` varchar(255) NOT NULL default '', `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '', `query` text NOT NULL,
> PRIMARY KEY (`id`) ) COMMENT='Bookmarks' DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__column_info`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__column_info` ( `id` int(5) unsigned
> NOT NULL auto_increment, `db_name` varchar(64) NOT NULL default '',
> `table_name` varchar(64) NOT NULL default '', `column_name`
> varchar(64) NOT NULL default '', `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '', `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '', `transformation` varchar(255)
> NOT NULL default '', `transformation_options` varchar(255) NOT NULL
> default '', `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',
> PRIMARY KEY (`id`), UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) ) COMMENT='Column information
> for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__history`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__history` ( `id` bigint(20) unsigned
> NOT NULL auto_increment, `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '', `table` varchar(64) NOT NULL
> default '', `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP, `sqlquery` text NOT NULL, PRIMARY KEY (`id`),
> KEY `username` (`username`,`db`,`table`,`timevalue`) ) COMMENT='SQL
> history for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__pdf_pages`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` ( `db_name` varchar(64)
> NOT NULL default '', `page_nr` int(10) unsigned NOT NULL
> auto_increment, `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '', PRIMARY KEY (`page_nr`), KEY `db_name`
> (`db_name`) ) COMMENT='PDF relation pages for phpMyAdmin' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__recent`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__recent` ( `username` varchar(64)
> NOT NULL, `tables` text NOT NULL, PRIMARY KEY (`username`) )
> COMMENT='Recently accessed tables' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__favorite`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__favorite` ( `username` varchar(64)
> NOT NULL, `tables` text NOT NULL, PRIMARY KEY (`username`) )
> COMMENT='Favorite tables' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_uiprefs`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` ( `username`
> varchar(64) NOT NULL, `db_name` varchar(64) NOT NULL, `table_name`
> varchar(64) NOT NULL, `prefs` text NOT NULL, `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP, PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__relation`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__relation` ( `master_db` varchar(64)
> NOT NULL default '', `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '', `foreign_db`
> varchar(64) NOT NULL default '', `foreign_table` varchar(64) NOT
> NULL default '', `foreign_field` varchar(64) NOT NULL default '',
> PRIMARY KEY (`master_db`,`master_table`,`master_field`), KEY
> `foreign_field` (`foreign_db`,`foreign_table`) ) COMMENT='Relation
> table' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_coords`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_coords` ( `db_name`
> varchar(64) NOT NULL default '', `table_name` varchar(64) NOT NULL
> default '', `pdf_page_number` int(11) NOT NULL default '0', `x`
> float unsigned NOT NULL default '0', `y` float unsigned NOT NULL
> default '0', PRIMARY KEY (`db_name`,`table_name`,`pdf_page_number`)
> ) COMMENT='Table coordinates for phpMyAdmin PDF output' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_info`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_info` ( `db_name` varchar(64)
> NOT NULL default '', `table_name` varchar(64) NOT NULL default '',
> `display_field` varchar(64) NOT NULL default '', PRIMARY KEY
> (`db_name`,`table_name`) ) COMMENT='Table information for
> phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__tracking`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__tracking` ( `db_name` varchar(64)
> NOT NULL, `table_name` varchar(64) NOT NULL, `version` int(10)
> unsigned NOT NULL, `date_created` datetime NOT NULL,
> `date_updated` datetime NOT NULL, `schema_snapshot` text NOT NULL,
> `schema_sql` text, `data_sql` longtext, `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL, `tracking_active`
> int(1) unsigned NOT NULL default '1', PRIMARY KEY
> (`db_name`,`table_name`,`version`) ) COMMENT='Database changes
> tracking for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__userconfig`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__userconfig` ( `username`
> varchar(64) NOT NULL, `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `config_data` text
> NOT NULL, PRIMARY KEY (`username`) ) COMMENT='User preferences
> storage for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__users`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__users` ( `username` varchar(64) NOT
> NULL, `usergroup` varchar(64) NOT NULL, PRIMARY KEY
> (`username`,`usergroup`) ) COMMENT='Users and their assignments to
> user groups' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__usergroups`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__usergroups` ( `usergroup`
> varchar(64) NOT NULL, `tab` varchar(64) NOT NULL, `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N', PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) ) COMMENT='User groups with configured
> menu items' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__navigationhiding`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` ( `username`
> varchar(64) NOT NULL, `item_name` varchar(64) NOT NULL,
> `item_type` varchar(64) NOT NULL, `db_name` varchar(64) NOT NULL,
> `table_name` varchar(64) NOT NULL, PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )
> COMMENT='Hidden items of navigation tree' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__savedsearches`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` ( `id` int(5)
> unsigned NOT NULL auto_increment, `username` varchar(64) NOT NULL
> default '', `db_name` varchar(64) NOT NULL default '',
> `search_name` varchar(64) NOT NULL default '', `search_data` text
> NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> ) COMMENT='Saved searches' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__central_columns`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__central_columns` ( `db_name`
> varchar(64) NOT NULL, `col_name` varchar(64) NOT NULL, `col_type`
> varchar(64) NOT NULL, `col_length` text, `col_collation`
> varchar(64) NOT NULL, `col_isNull` boolean NOT NULL, `col_extra`
> varchar(255) default '', `col_default` text, PRIMARY KEY
> (`db_name`,`col_name`) ) COMMENT='Central list of columns' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__designer_settings`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` ( `username`
> varchar(64) NOT NULL, `settings_data` text NOT NULL, PRIMARY KEY
> (`username`) ) COMMENT='Settings related to Designer' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__export_templates`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__export_templates` ( `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT, `username` varchar(64) NOT NULL,
> `export_type` varchar(10) NOT NULL, `template_name` varchar(64) NOT
> NULL, `template_data` text NOT NULL, PRIMARY KEY (`id`), UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> ) COMMENT='Saved export templates' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*
Open This File :
C:\xampp\phpMyAdmin\config.inc.php
Clear and Past this Code :
> --------------------------------------------------------- <?php /** * Debian local configuration file * * This file overrides the settings
> made by phpMyAdmin interactive setup * utility. * * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz * * NOTE:
> do not add security sensitive data to this file (like passwords) *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still * want to do this, make sure to properly secure the access to
> this file * (also on the filesystem level). */ /** * Server(s)
> configuration */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1]. Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
> /* Authentication type */
> $cfg['Servers'][$i]['auth_type'] = 'cookie';
> /* Server parameters */
> if (empty($dbserver)) $dbserver = 'localhost';
> $cfg['Servers'][$i]['host'] = $dbserver;
> if (!empty($dbport)) {
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> $cfg['Servers'][$i]['port'] = $dbport;
> }
> //$cfg['Servers'][$i]['compress'] = false;
> /* Select mysqli if your server has it */
> $cfg['Servers'][$i]['extension'] = 'mysqli';
> /* Optional: User for advanced features */
> $cfg['Servers'][$i]['controluser'] = $dbuser;
> $cfg['Servers'][$i]['controlpass'] = $dbpass;
> /* Optional: Advanced phpMyAdmin features */
> $cfg['Servers'][$i]['pmadb'] = $dbname;
> $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
> $cfg['Servers'][$i]['relation'] = 'pma_relation';
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
> $cfg['Servers'][$i]['history'] = 'pma_history';
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
> /* Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */
> // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
> /* Advance to next server for rest of config */
> $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* * End of servers
> configuration */ /* * Directories for saving/loading files from
> server */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';
------------------------------------------
i Solve My Problem Through this Method
generalising to multiple columns, why not:
columns = ['whatever', 'columns', 'you', 'choose']
df['period'] = df[columns].astype(str).sum(axis=1)
In Chrome Canary now you can limit the network throughput. This can be done in the "Network" options of the "Emulation" tab of the Console in the Dev Tools.
You might need to activate the Chrome flag "Enable Developer Tools experiments" (chrome://flags/#enable-devtools-experiments) (chrome://flags) to see this new feature. You can simulate some low bandwidth (GSM, GPRS, EDGE, 3G) for mobile connections.
For dynamic 2D charts, I have been using JChart2D. It's fast, simple, and being updated regularly. The author has been quick to respond to my one bug report and few feature requests. We, at our company, prefer it over JFreeChart because it was designed for dynamic use, unlike JFreeChart.
Elegant ES6 function to format a date into hh:mm:ss
:
const leadingZero = (num) => `0${num}`.slice(-2);
const formatTime = (date) =>
[date.getHours(), date.getMinutes(), date.getSeconds()]
.map(leadingZero)
.join(':');
If someone (like me) needs Tomalak's method with array support (ie. multiple select), here it is:
function getUrlParams(url) {
var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
match, params = {},
decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};
if (typeof url == "undefined") url = document.location.href;
while (match = re.exec(url)) {
if( params[decode(match[1])] ) {
if( typeof params[decode(match[1])] != 'object' ) {
params[decode(match[1])] = new Array( params[decode(match[1])], decode(match[2]) );
} else {
params[decode(match[1])].push(decode(match[2]));
}
}
else
params[decode(match[1])] = decode(match[2]);
}
return params;
}
var urlParams = getUrlParams(location.search);
input ?my=1&my=2&my=things
result 1,2,things
(earlier returned only: things)
By looking at your code, I assume you do not have a concern about the 'Time' of the DateTime object. If so, you can pass the date, month and the year as integer parameters. Please see the following code. This is a working example from my current project.
The advantage is; this method helps me to avoid DateTime format issues and culture incompatibilities.
/// <summary>
/// Get Arrivals Report Seven Day Forecast
/// </summary>
/// <param name="day"></param>
/// <param name="month"></param>
/// <param name="year"></param>
/// <returns></returns>
[HttpGet("arrivalreportsevendayforecast/{day:int}/{month:int}/{year:int}")]
public async Task<ActionResult<List<ArrivalsReportSevenDayForecastModel>>> GetArrivalsReportSevenDayForecast(int day, int month, int year)
{
DateTime selectedDate = new DateTime(year, month, day);
IList<ArrivalsReportSevenDayForecastModel> arrivingStudents = await _applicationService.Value.GetArrivalsReportSevenDayForecast(selectedDate);
return Ok(arrivingStudents);
}
If you are keen to see the front-end as well, feel free to read the code below. Unfortunately, that is written in Angular. This is how I normally pass a DateTime as a query parameter in Angular GET requests.
public getArrivalsReportSevenDayForecast(selectedDate1 : Date): Observable<ArrivalsReportSevenDayForecastModel[]> {
const params = new HttpParams();
const day = selectedDate1.getDate();
const month = selectedDate1.getMonth() + 1
const year = selectedDate1.getFullYear();
const data = this.svcHttp.get<ArrivalsReportSevenDayForecastModel[]>(this.routePrefix +
`/arrivalreportsevendayforecast/${day}/${month}/${year}`, { params: params }).pipe(
map<ArrivalsReportSevenDayForecastModel[], ArrivalsReportSevenDayForecastModel[]>(arrivingList => {
// do mapping here if needed
return arrivingList;
}),
catchError((err) => this.svcError.handleError(err)));
return data;
}
@RequestParam
annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:
request:
GET: http://someserver.org/path?name=John&surname=Smith
endpoint code:
public User getUser(@RequestParam(value = "name") String name,
@RequestParam(value = "surname") String surname){
...
}
So basically, while @RequestBody
maps entire user request (even for POST) to a String variable, @RequestParam
does so with one (or more - but it is more complicated) request param to your method argument.
If you face this problem while publishing your website or application on some server, the simple solution I used is to convert folder which contains files to web application.
Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
java.lang.StringBuilder. Use int constructor to create an initial size.
And do not forget the "new" service type (from the k8s docu):
ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.
Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.
The reason why things aren't stopping for you is because the process (doInBackground()) runs until it is finished. Therefore you should check if the thread is cancelled or not before doing stuff:
if(!isCancelled()){
// Do your stuff
}
So basically, if the thread is not cancelled, do it, otherwise skip it :) Could be useful to check for this some times during your operation, especially before time taking stuff.
Also it could be useful to "clean up" alittle in
onCancelled();
Documentation for AsyncTask:
http://developer.android.com/reference/android/os/AsyncTask.html
Hope this helps!
If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();"
and in the function you would return true or false.
If you just want to run the function, and then let the anchor tag do its job, simply remove the return false
statement.
As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.
Delete parent:
$(document).on("click", ".remove", function() {
$(this).parent().remove();
});
Delete all parents:
$(document).on("click", ".remove", function() {
$(this).parents().remove();
});
If you don't care about the changes that git says are outstanding, then you can do a force checkout.
git checkout -f {{insert your branch name here}}
I have created a small lib that does this a year ago:
https://github.com/shawnmclean/Idle.js
Description:
Tiny javascript library to report activity of user in the browser (away, idle, not looking at webpage, in a different tab, etc). that is independent of any other javascript libraries such as jquery.
Visual Studio users can get it from NuGet by: PM> Install-Package Idle.js
I'd recommend adopting Syslog severity levels: DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY
.
See http://en.wikipedia.org/wiki/Syslog#Severity_levels
They should provide enough fine-grained severity levels for most use-cases and are recognized by existing log-parsers. While you have of course the freedom to only implement a subset, e.g. DEBUG, ERROR, EMERGENCY
depending on your app's requirements.
Let's standardize on something that's been around for ages instead of coming up with our own standard for every different app we make. Once you start aggregating logs and are trying to detect patterns across different ones it really helps.
I found that in my code when I used a ration or percentage for line-height line-height;1.5;
My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px;
so that I could predict exactly how many pixels each page would take with a given number of lines.
Another thing you can do is to change the Deployment target to the highest value. This will prevent the Scheme Menu from displaying older versions.
To do this go to: Target->Summary then change the Deployment Target.
Correct permissions for the file is 644 Correct permissions for the folder is 755
To change the permissions , use terminal and following commands.
find foldername -type d -exec chmod 755 {} \;
find foldername -type f -exec chmod 644 {} \;
755 for folders and 644 for files.
Let us say we are migrating Jenkins LTS from PC1 to PC2 (irrispective of LTS version is same of upgraded). It is easy to use ThinBackUp Plugin for migration or Upgrade of Jenkins version.
Step1: Prepare PC1 for migration
Note: This Thinbackup will also take Plugin Backup which is optional.
Step2: Install Jenkins (Install using .war file or Paste archived version) in PC2.
sc create <Jenkins_PC2Servicename> binPath="<Path_to_Jenkinsexe>/jenkins.exe"
NOTE: If you are using Database setting of SCM in your Jenkins jobs then you need to take extra care as all SCM plugins do not support to carry Database settings with the help of ThinbackUp plugin. e.g. If you are using PTC Integrity SCM Plugin, and some Jenkins jobs are using DB using Integrity, then it will create a directory JENKINS_Home/IntegritySCM, ThinbackUp will not include this DB while taking backup.
Solution: Directly Copy this JENKINS_Home/IntegritySCM folder from PC1 to PC2.
If this is output from a Dockerfile then you don't want / need to commit it.
However you will want to tag the base image and any other contributing images / applications.
E.g.
FROM node:12.18.1
I used the following code.
<Label>
<Label.Content>
<AccessText TextWrapping="Wrap" Text="xxxxx"/>
</Label.Content>
</Label>
i was getting an error saying Permission Denied after running any 'ng' command (ng --version). I googled for a while and tried clearing npm cache npm cache verify
, uninstalling my global angular cli (npm uninstall -g @angular/cli
) and reinstalling Angular/cli (npm install -g @angular/cli
) etc.. but it would give an error say its already installed. but the node_modules folder here wouldn't have any angular folder.. reinstalled node even then restarted my computer.
ANSWER: Finally I found that the ng.cmd and ng.ps1 files in C:\Users\JaGoodwin\AppData\Roaming\npm\
here were still there (in npm folder).. even though I did npm uninstall -g @angular/cli
. those files were causing ng (angular/cli) to think it was still installed. i deleted those files then npm install -g @angular/[email protected]
(version i need) I then removed my projects node_modules and then ran npm install
and now can run my angular project using ng serve
.
C:\Users\JaGoodwin\AppData\Roaming\npm\
Find this by folder searching %APPDATA% in your windows search bar.
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
You can easily use .replace()
as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change.
Let me explain by;
>>stuff = "bin and small"
>>stuff.replace('and', ',')
>>print(stuff)
"big and small" #no change
To observe the change you want to apply, you can assign same or another variable;
>>stuff = "big and small"
>>stuff = stuff.replace("and", ",")
>>print(stuff)
'big, small'
you can use use JQuery for deep copying :
var arr =[['abc'],['xyz']];
var newArr = $.extend(true, [], arr);
newArr.shift().shift();
console.log(arr); //arr still has [['abc'],['xyz']]
This didn't start happening for me until I rooted my Samsung Galaxy S III phone (following the xda-developer forum guide).
It happens pretty randomly, but it's definitely occurring while running Eclipse.
Killing the adb.exe process and restarting it solves the problem.
I used the following command to install python mysql-connector in Mac. it works
pip install mysql-connector-python-rf
The word check_
in the name means that if the command (the shell in this case that returns the exit status of the last command (yum
in this case)) returns non-zero status then it raises CalledProcessError
exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_
methods. You could use subprocess.call
in your case because you are ignoring the captured output, e.g.:
import subprocess
rc = subprocess.call(['grep', 'pattern', 'file'],
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
...
elif rc == 1: # not found
...
elif rc > 1: # error
...
You don't need shell=True
to run the commands from your question.
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
You can use this func:
func randomString(length int) string {
b := make([]byte, length)
rand.Read(b)
return fmt.Sprintf("%x", b)[:length]
}
Check it out in the playground
Inline styling would work in any case
<p-column field="Quantity" header="Qté" [style]="{'width':'48px'}">
The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.
Sounds like you got your answer. Passing by value is expensive, but gives you a copy to work with if you need it.
What about Microsoft's Visual Studio Express? http://www.microsoft.com/express/default.aspx SQL Server Express is also at that link...
According to the following post, you can't do this with log4j: Use MaxBackupIndex in DailyRollingFileAppender -log4j
As far as I know, this functionality was supposed to make it into log4j 2.0 but that effort got sidetracked. According to the logback website, logback is the intended successor to log4j so you might consider using that.
There's an API called SLF4J which provides a common API to logging. It will load up the actual logging implementation at runtime so depending on the configuration that you have provided, it might use java.util.log or log4j or logback or any other library capable of providing logging facilities. There'll be a bit of up-front work to go from using log4j directly to using SLF4J but they provide some tools to automate this process. Once you've converted your code to use SLF4J, switching logging backends should simply be a case of changing the config file.
When you click the Button
if(isset($_POST['save'])){
$sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
**if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}**
}
This will execute the Query in the variable $sql
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
They are not bad, but actually helpful. I had a huge problem some time ago where I had to embed my twitter feed and it just wouldn't let md do it on the same page, so I set it on a different page, and put it in as an iframe.
They are also good because all browsers (and phone browsers) support them. They can not be considered a bad practice, as long as you use them correctly.
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.
Example without using the apply
method:
function a(...args){_x000D_
b(...args);_x000D_
b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
Note This snippet returns a syntax error if your browser still uses ES5.
Editor's note: Since the snippet uses console.log()
, you must open your browser's JS console to see the result - there will be no in-page result.
It will display this result:
In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters
The follow fix work for me
Windos server 2003 64 Reporting Services Windows Vista and Windows XP
Fix KB967511 and KB953752
http://support.microsoft.com/kb/967511/es
work for me
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:
td.male { color: blue; }
td.female { color: pink; }
can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:
<td class="{{person.gender}}">
Just make sure that the content is only one word! Or you could even map to different CSS class names with:
<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">
For completeness, here's the data attribute approach:
<td data-gender="{{person.gender}}">
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
Ref : Youtube Video Download (Android/Java)
private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();
initTypeMap(); call first
class Meta {
public String num;
public String type;
public String ext;
Meta(String num, String ext, String type) {
this.num = num;
this.ext = ext;
this.type = type;
}
}
class Video {
public String ext = "";
public String type = "";
public String url = "";
Video(String ext, String type, String url) {
this.ext = ext;
this.type = type;
this.url = url;
}
}
public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
throws IOException {
if (ytUrl == null) {
return null;
}
// Remove any query params in query string after the watch?v=<vid> in
// e.g.
// http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
int andIdx = ytUrl.indexOf('&');
if (andIdx >= 0) {
ytUrl = ytUrl.substring(0, andIdx);
}
// Get the HTML response
/* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
/* HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
userAgent);
HttpGet request = new HttpGet(ytUrl);
HttpResponse response = client.execute(request);*/
String html = "";
HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line.replace("\\u0026", "&"));
}
in.close();
html = str.toString();
// Parse the HTML response and extract the streaming URIs
if (html.contains("verify-age-thumb")) {
Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
return null;
}
if (html.contains("das_captcha")) {
Log.e("Downloader", "Captcha found, please try with different IP address.");
return null;
}
Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
// Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
Matcher m = p.matcher(html);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}
if (matches.size() != 1) {
Log.e("Downloader", "Found zero or too many stream maps.");
return null;
}
String urls[] = matches.get(0).split(",");
HashMap<String, String> foundArray = new HashMap<String, String>();
for (String ppUrl : urls) {
String url = URLDecoder.decode(ppUrl, "UTF-8");
Log.e("URL","URL : "+url);
Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
Matcher m1 = p1.matcher(url);
String itag = null;
if (m1.find()) {
itag = m1.group(1);
}
Pattern p2 = Pattern.compile("signature=(.*?)[&]");
Matcher m2 = p2.matcher(url);
String sig = null;
if (m2.find()) {
sig = m2.group(1);
} else {
Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
Matcher m23 = p23.matcher(url);
if (m23.find()) {
sig = m23.group(1);
}
}
Pattern p3 = Pattern.compile("url=(.*?)[&]");
Matcher m3 = p3.matcher(ppUrl);
String um = null;
if (m3.find()) {
um = m3.group(1);
}
if (itag != null && sig != null && um != null) {
Log.e("foundArray","Adding Value");
foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
+ "signature=" + sig);
}
}
Log.e("foundArray","Size : "+foundArray.size());
if (foundArray.size() == 0) {
Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
return null;
}
ArrayList<Video> videos = new ArrayList<Video>();
for (String format : typeMap.keySet()) {
Meta meta = typeMap.get(format);
if (foundArray.containsKey(format)) {
Video newVideo = new Video(meta.ext, meta.type,
foundArray.get(format));
videos.add(newVideo);
Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
+ ", type:" + newVideo.type + ", url:" + newVideo.url);
}
}
return videos;
}
private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(webViewActivity.this, "",
"Connecting to YouTube...", true);
}
@Override
protected ArrayList<Video> doInBackground(String... params) {
ArrayList<Video> fVideos = new ArrayList<>();
String url = params[0];
try {
ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
/* Log.e("Downloader","Size of Video : "+videos.size());*/
if (videos != null && !videos.isEmpty()) {
for (Video video : videos)
{
Log.e("Downloader", "ext : " + video.ext);
if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
ext = video.ext.toLowerCase();
fVideos.add(new Video(video.ext,video.type,video.url));
}
}
return fVideos;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
}
Log.e("Downloader", "Couldn't get stream URI for " + url);
return null;
}
@Override
protected void onPostExecute(ArrayList<Video> streamingUrl) {
super.onPostExecute(streamingUrl);
progressDialog.dismiss();
if (streamingUrl != null) {
if (!streamingUrl.isEmpty()) {
//Log.e("Steaming Url", "Value : " + streamingUrl);
for (int i = 0; i < streamingUrl.size(); i++) {
Video fX = streamingUrl.get(i);
Log.e("Founded Video", "URL : " + fX.url);
Log.e("Founded Video", "TYPE : " + fX.type);
Log.e("Founded Video", "EXT : " + fX.ext);
}
//new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
}
}
}
}
public void initTypeMap()
{
typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}
Edit 2:
Some time This Code Not worked proper
Same-origin policy
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1].
url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts // DASH: contains video or audio stream
Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this
url // direct HTTP link to a video
itag // code specifying the quality
s // signature, security measure to counter downloading
Each URL will be encoded so you will need to decode them. Now the tricky part.
YouTube has at least 3 security levels for their videos
unsecured // as expected, you can download these with just the unencoded URL
s // see below
RTMPE // uses "rtmpe://" protocol, no known method for these
The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.
The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as
AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this
function mo(a) {
a = a.split("");
a = lo.rw(a, 1);
a = lo.rw(a, 32);
a = lo.IC(a, 1);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 44);
return a.join("")
}
This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as
http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js
this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header
Access-Control-Allow-Origin: http://www.youtube.com
and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests
Access-Control-Allow-Origin: *
So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Lookup move /?
on Windows and man mv
on Unix systems
The number of itemId
s in your list will be the same as the number of elements in your list:
int itemCount = list.size();
However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.
Set<String> itemIds = new HashSet<String>();
//...
itemId = p.getItemId();
itemIds.add(itemId);
//... later ...
int uniqueItemIdCount = itemIds.size();
As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.
What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.
Using printf is like using a machine gun to fire one bullet.
date.toLocaleDateString('en-US')
works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
SHOW TABLES
mysql> USE test;
Database changed
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| t1 |
| t2 |
| t3 |
+----------------+
3 rows in set (0.00 sec)
SHOW TABLES IN db_name
mysql> SHOW TABLES IN another_db;
+----------------------+
| Tables_in_another_db |
+----------------------+
| t3 |
| t4 |
| t5 |
+----------------------+
3 rows in set (0.00 sec)
mysql> SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'another_db';
+------------+
| TABLE_NAME |
+------------+
| t3 |
| t4 |
| t5 |
+------------+
3 rows in set (0.02 sec)
you have fetched just 1 row. fix like this:
while ( $tables = $result->fetch_array())
{
echo $tmp[0]."<br>";
}
and I think, information_schema would be better than SHOW TABLES
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'your database name'
while ( $tables = $result->fetch_assoc())
{
echo $tables['TABLE_NAME']."<br>";
}
In command prompt:
SET PATH = "%PATH%;%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
The first answer is correct, but if you have a large amount of data (in my project I had 8.000 rows * 8 columns) is tragically slow.... Having a string that becomes that large in c# is why that solution is forbiden
Instead using a large string I used a string array that I join at the end in order to return the string of the html table. Moreover, I used a linq expression ((from o in row.ItemArray select o.ToString()).ToArray()) in order to join each DataRow of the table, instead of looping again, in order to save as much time as possible.
This is my sample code:
private string MakeHtmlTable(DataTable data)
{
string[] table = new string[data.Rows.Count] ;
long counter = 1;
foreach (DataRow row in data.Rows)
{
table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";
counter+=1;
}
return "</br><table>" + String.Join("", table) + "</table>";
}
The easiest way to do this is:
String hexadecimalString = String.format("%x", integerValue);
You can use gsub to replace multiple mutations of empty, like "" or a space, to be NA:
data= data.frame(cats=c('', ' ', 'meow'), dogs=c("woof", " ", NA))
apply(data, 2, function(x) gsub("^$|^ $", NA, x))
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
As a workaround which achieves the same purpose, you may use the sprintf-js library and types.
I got it from another SO answer.
Set
Dictionary<int, string> states = new Dictionary<int, string>()
as a property outside the function and inside the function insert the entries, it should work.
The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.
If You are on another branch, You need first "check to this commit" for commit you want to delete, and only then "reset current branch to this commit" choosing previous wright commit, will work.
if (!$("input[name='html_elements']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
Use the -s
or --strategy
option combined with the -X
option. In your specific question, you want to keep all of the remote files and replace the local files of the same name.
Replace conflicts with the remote version
git merge -s recursive -Xtheirs upstream/master
will use the remote repo version of all conflicting files.
Replace conflicts with the local version
git merge -s recursive -Xours upstream/master
will use the local repo version of all conflicting files.
Below Python packages are to be downloaded and installed to their default locations.
1.1. Python-2.7.x.
1.2. Numpy.
1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).
Install all packages into their default locations. Python will be installed to C:/Python27/.
After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.
Download latest OpenCV release from sourceforge site and double-click to extract it.
Goto opencv/build/python/2.7 folder.
Copy cv2.pyd to C:/Python27/lib/site-packeges.
Open Python IDLE and type following codes in Python terminal.
import cv2 print cv2.version If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.
I used the info above to help create a more permanent solution. The following will create the alias sh that you can use to open Git Bash:
echo @start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login > %systemroot%\sh.bat
java.exe is the command where it waits for application to complete untill it takes the next command. javaw.exe is the command which will not wait for the application to complete. you can go ahead with another commands.
EDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.
from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:
import pandas as pd
ds = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.
import pandas as pd
df = pd.DataFrame(data, index=index)
In both of the above index is list
for example: I have a csv file with following data:
,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi
To read above data as series and data frame:
import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index = file_data.index)
output:
>>> d
BR Brazil
RU Russia
IN India
df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )
output:
>>> df
area
BR 12015
RU 457
IN 457787
Another reason this error might occur is: there is no index.html
in .../YourApp/www/
!
I just followed the ionic guide, and one of the steps is:
$ rm www/index.html
On iOS this is no problem as during the build the compiler takes some default HTML instead. However, when building for android, NO example index.html
is used. Took me sometime to find out ("WHY does it work on iOS, but not on android...?)
Easy solution: create a index.html, save it under .../YourApp/www
, rebuild ...et voila!
Get all "words" in a string
/([^\s]+)/g
Basically
^/s
means break on spaces (or match groups of non-spaces)
Don't forget theg
for Greedy
you can simply add id to the button, it is not in the document, but it works.
$().dialog(buttons:[{id:'your button id'....}]);
then in your function just use the
$('#your button id')
to disable it.
I face with the same issue. I deleted the local repository and relaunched the ID. It worked fine .
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
For your first question try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
(available since API 8)
To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.
Try using .+
instead of [(\w)(\W)(\s)]+
.
Note that this actually includes more than you need - ASCII only defines the first 128 characters.
PDO does support this (as of 2020). Just do a query() call on a PDO object as usual, separating queries by ; and then nextRowset() to step to the next SELECT result, if you have multiple. Resultsets will be in the same order as the queries. Obviously think about the security implications - so don't accept user supplied queries, use parameters, etc. I use it with queries generated by code for example.
$statement = $connection->query($query);
do {
$data[] = $statement->fetchAll(PDO::FETCH_ASSOC);
} while ($statement->nextRowset());
select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
I think the new preferred way might be to use IDataErrorInfo
Read more here
Since C++11, you can also use a lambda expression instead of defining a comparator struct:
auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);
my_map["1"] = "a";
my_map["three"] = "b";
my_map["two"] = "c";
my_map["fouuur"] = "d";
for(auto const &kv : my_map)
cout << kv.first << endl;
Output:
1
two
three
fouuur
I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.
Function base solution for get index from a JSON object with value by VanillaJS.
Exemple: https://codepen.io/gmkhussain/pen/mgmEEW
var data= [{_x000D_
"name": "placeHolder",_x000D_
"section": "right"_x000D_
}, {_x000D_
"name": "Overview",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "ByFunction",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "Time",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "allFit",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "allbMatches",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "allOffers",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "allInterests",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "allResponses",_x000D_
"section": "left"_x000D_
}, {_x000D_
"name": "divChanged",_x000D_
"section": "right"_x000D_
}];_x000D_
_x000D_
_x000D_
// create function_x000D_
function findIndex(jsonData, findThis){_x000D_
var indexNum = jsonData.findIndex(obj => obj.name==findThis); _x000D_
_x000D_
//Output of result_x000D_
document.querySelector("#output").innerHTML=indexNum;_x000D_
console.log(" Array Index number: " + indexNum + " , value of " + findThis );_x000D_
}_x000D_
_x000D_
_x000D_
/* call function */_x000D_
findIndex(data, "allOffers");
_x000D_
Output of index number : <h1 id="output"></h1>
_x000D_
You should learn about the Media queries for CSS. The site you referring to is using the same. The site is basically using the different CSS everytime the browser window size is changining. Here's the link for samples
The format
method was introduced in Python 2.6. It is more capable and not much more difficult to use:
>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.
>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'
>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'
>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'
There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.
Assuming you mean the latter, the formally correct way is
signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;
which at least gcc properly recognizes as a no-op.
C# is a language, .NET is an application framework. The .NET libraries can run on the CLR and thus any language which can run on the CLR can also use the .NET libraries.
If you are familiar with Java, this is similar... Java is a language built on top of the JVM... though any of the pre-assembled Java libraries can be used by another language built on top of the JVM.
"watch" does not allow fractions of a second in Busybox, while "sleep" does. If that matters to you, try this:
while true; do ls -l; sleep .5; done
All answers provided thus far result in potentially dangerous behavior as it is quite possible you select a dummy value that is actually part of the dataset. This is increasingly likely as you create groups with many attributes. Simply put, the approach doesn't always generalize well.
A less hacky solve is to use pd.drop_duplicates() to create a unique index of value combinations each with their own ID, and then group on that id. It is more verbose but does get the job done:
def safe_groupby(df, group_cols, agg_dict):
# set name of group col to unique value
group_id = 'group_id'
while group_id in df.columns:
group_id += 'x'
# get final order of columns
agg_col_order = (group_cols + list(agg_dict.keys()))
# create unique index of grouped values
group_idx = df[group_cols].drop_duplicates()
group_idx[group_id] = np.arange(group_idx.shape[0])
# merge unique index on dataframe
df = df.merge(group_idx, on=group_cols)
# group dataframe on group id and aggregate values
df_agg = df.groupby(group_id, as_index=True)\
.agg(agg_dict)
# merge grouped value index to results of aggregation
df_agg = group_idx.set_index(group_id).join(df_agg)
# rename index
df_agg.index.name = None
# return reordered columns
return df_agg[agg_col_order]
Note that you can now simply do the following:
data_block = [np.tile([None, 'A'], 3),
np.repeat(['B', 'C'], 3),
[1] * (2 * 3)]
col_names = ['col_a', 'col_b', 'value']
test_df = pd.DataFrame(data_block, index=col_names).T
grouped_df = safe_groupby(test_df, ['col_a', 'col_b'],
OrderedDict([('value', 'sum')]))
This will return the successful result without having to worry about overwriting real data that is mistaken as a dummy value.
Font awesome use SVG icons. So, you can resize it for your requirment.
just use CSS class for that,
.large-icon{
font-size:10em;
//or
font-size:200%;
//or
font-size:50px;
}
Another handy alternative is to use screen command to run the main program and direct the stderr and stdout to a file, then use tail -f to view the file as it is being written to.
You could also open another session if you don't want to use screen.
You're missing the data-toggle="tab"
data-tag on your menu urls so your scripts can't tell where your tab switches are:
HTML
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
Nice question, a while ago I've experimented a bit with this, but haven't used it a lot because it's still not bulletproof. I divided the plot area into a 32x32 grid and calculated a 'potential field' for the best position of a label for each line according the following rules:
The code was something like this:
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
def my_legend(axis = None):
if axis == None:
axis = plt.gca()
N = 32
Nlines = len(axis.lines)
print Nlines
xmin, xmax = axis.get_xlim()
ymin, ymax = axis.get_ylim()
# the 'point of presence' matrix
pop = np.zeros((Nlines, N, N), dtype=np.float)
for l in range(Nlines):
# get xy data and scale it to the NxN squares
xy = axis.lines[l].get_xydata()
xy = (xy - [xmin,ymin]) / ([xmax-xmin, ymax-ymin]) * N
xy = xy.astype(np.int32)
# mask stuff outside plot
mask = (xy[:,0] >= 0) & (xy[:,0] < N) & (xy[:,1] >= 0) & (xy[:,1] < N)
xy = xy[mask]
# add to pop
for p in xy:
pop[l][tuple(p)] = 1.0
# find whitespace, nice place for labels
ws = 1.0 - (np.sum(pop, axis=0) > 0) * 1.0
# don't use the borders
ws[:,0] = 0
ws[:,N-1] = 0
ws[0,:] = 0
ws[N-1,:] = 0
# blur the pop's
for l in range(Nlines):
pop[l] = ndimage.gaussian_filter(pop[l], sigma=N/5)
for l in range(Nlines):
# positive weights for current line, negative weight for others....
w = -0.3 * np.ones(Nlines, dtype=np.float)
w[l] = 0.5
# calculate a field
p = ws + np.sum(w[:, np.newaxis, np.newaxis] * pop, axis=0)
plt.figure()
plt.imshow(p, interpolation='nearest')
plt.title(axis.lines[l].get_label())
pos = np.argmax(p) # note, argmax flattens the array first
best_x, best_y = (pos / N, pos % N)
x = xmin + (xmax-xmin) * best_x / N
y = ymin + (ymax-ymin) * best_y / N
axis.text(x, y, axis.lines[l].get_label(),
horizontalalignment='center',
verticalalignment='center')
plt.close('all')
x = np.linspace(0, 1, 101)
y1 = np.sin(x * np.pi / 2)
y2 = np.cos(x * np.pi / 2)
y3 = x * x
plt.plot(x, y1, 'b', label='blue')
plt.plot(x, y2, 'r', label='red')
plt.plot(x, y3, 'g', label='green')
my_legend()
plt.show()
And the resulting plot:
Simply, row_num = df.shape[0] # gives number of rows, here's the example:
import pandas as pd
import numpy as np
In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])
In [323]: df
Out[323]:
col_1 col_2
0 -0.894268 1.309041
1 -0.120667 -0.241292
2 0.076168 -1.071099
3 1.387217 0.622877
4 -0.488452 0.317882
In [324]: df.shape
Out[324]: (5, 2)
In [325]: df.shape[0] ## Gives no. of rows/records
Out[325]: 5
In [326]: df.shape[1] ## Gives no. of columns
Out[326]: 2
import numpy as np
def date(df):
df['weekday'] = df['date'].dt.day_name()
conditions = [(df['weekday'] == 'Sunday'),
(df['weekday'] == 'Monday'),
(df['weekday'] == 'Tuesday'),
(df['weekday'] == 'Wednesday'),
(df['weekday'] == 'Thursday'),
(df['weekday'] == 'Friday'),
(df['weekday'] == 'Saturday')]
choices = [0, 1, 2, 3, 4, 5, 6]
df['week'] = np.select(conditions, choices)
return df
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
If you're creating a program that doesn't require user input you could always just create it as a service. A service won't show any kind of UI.
With Godaddy certs you most likely will have a domain.key
, gd_bundle_something.crt
and (random alphanumeric string) 4923hg4k23jh4.crt
You'll need to: cat gd_bundle_something.crt >> 4923hg4k23jh4.crt
And then, on nginx, you will use
ssl on;
ssl_certificate /etc/ssl/certs/4923hg4k23jh4.crt;
ssl_certificate_key /etc/ssl/certs/domain.key;
error in the very first line public class StaticDemo {
Any Class A
which has access modifier as public
must have a separate source file as A.java
or A.jav
. This is specified in JLS 7.6 section:
If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
The type is referred to by code in other compilation units of the package in which the type is declared.
The type is declared public (and therefore is potentially accessible from code in other packages).
However, you may have to remove public
access modifier from the Class declaration StaticDemo
. Then as StaticDemo
class will have no modifier it will become package-private, That is, it will be visible only within its own package.
Check out Controlling Access to Members of a Class
Use the -ExpandProperty
flag of Select-Object
$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority
Update to answer the other question:
Note that you can as well just access the property:
$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
So to get multiple of these into variables:
$var=Get-WSManInstance -enumerate wmicimv2/win32_process
$prio = $var.Priority
$pid = $var.ProcessID
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
Not exactly in-place, but some idea to do it:
a = ['a', 'b']
def inplace(a):
c = []
while len(a) > 0:
e = a.pop(0)
if e == 'b':
c.append(e)
a.extend(c)
You can extend the function to call you filter in the condition.
I wrote these classes which served me well. It's simple yet pragmatic.
public class HtmlAttribute
{
public string Name { get; set; }
public string Value { get; set; }
public HtmlAttribute(string name) : this(name, null) { }
public HtmlAttribute(
string name,
string @value)
{
this.Name = name;
this.Value = @value;
}
public override string ToString()
{
if (string.IsNullOrEmpty(this.Value))
return this.Name;
if (this.Value.Contains('"'))
return string.Format("{0}='{1}'", this.Name, this.Value);
return string.Format("{0}=\"{1}\"", this.Name, this.Value);
}
}
public class HtmlElement
{
protected List<HtmlAttribute> Attributes { get; set; }
protected List<object> Childs { get; set; }
public string Name { get; set; }
protected HtmlElement Parent { get; set; }
public HtmlElement() : this(null) { }
public HtmlElement(string name, params object[] childs)
{
this.Name = name;
this.Attributes = new List<HtmlAttribute>();
this.Childs = new List<object>();
if (childs != null && childs.Length > 0)
{
foreach (var c in childs)
{
Add(c);
}
}
}
public void Add(object o)
{
var a = o as HtmlAttribute;
if (a != null)
this.Attributes.Add(a);
else
{
var h = o as HtmlElement;
if (h != null && !string.IsNullOrEmpty(this.Name))
{
h.Parent = this;
this.Childs.Add(h);
}
else
this.Childs.Add(o);
}
}
public override string ToString()
{
var result = new StringBuilder();
if (!string.IsNullOrEmpty(this.Name))
{
result.Append(string.Format("<{0}", this.Name));
if (this.Attributes.Count > 0)
{
result.Append(" ");
foreach (var attr in this.Attributes)
{
result.Append(attr.ToString());
result.Append(" ");
}
result = new StringBuilder(result.ToString().TrimEnd(' '));
}
if (this.Childs.Count == 0)
{
result.Append(" />");
}
else
{
result.AppendLine(">");
foreach (var c in this.Childs)
{
var cParts = c.ToString().Split('\n');
foreach (var p in cParts)
{
result.AppendLine(string.Format("{0}", p));
}
}
result.Append(string.Format("</{0}>", this.Name));
}
}
else
{
foreach (var c in this.Childs)
{
var cParts = c.ToString().Split('\n');
foreach (var p in cParts)
{
result.AppendLine(string.Format("{0}", p));
}
}
}
var head = GetHeading(this);
var ps = result.ToString().Split('\n');
return string.Join("\r\n", (from p in ps select head + p.TrimEnd('\r')).ToArray());
}
string GetHeading(HtmlElement h)
{
if (h.Parent != null)
return " ";
else
return string.Empty;
}
}
This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.
It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.
The relevant section is:
select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
quirksmode has a good description of the 'text-overflow' property, but you may need to apply some additional properties like 'white-space: nowrap'
Whilst I'm not 100% how this will behave in a select object, it could be worth trying this first:
Just Simple Answer. FETCH DELETE
function deleteData(item, url) {
return fetch(url + '/' + item, {
method: 'delete'
})
.then(response => response.json());
}
DELETE FROM ... WHERE id=...;
protected function templateRemove($id){
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));
if ($entity != null){
$em->remove($entity);
$em->flush();
}
}
In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.
HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.
I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:
I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I'm wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.
However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).
I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).
Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as ".\curl.exe -s google.com", etc.
The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.
I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.
The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.
I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.
There are always numerous ways to accomplish what you are trying to set out to do; it's just a matter of combining the right tools for the job, and many times it boils down to personal preference.
There are correct solutions in the comments, but to summarize them into a single answer:
You have to use DECIMAL(6,4).
Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.
A good way to findout what header file you are missing:
man <section> <function call>
To find out the section use:
apropos <function call>
Example:
man 3 memset
man 2 send
Edit in response to James Morris:
Source: Wikipedia Man Page
Make sure you put multiple properties in the same line (since you only showed 1 line of code, you may have had the same problem I did).
Mine would set the default date, but didn't gray out old dates. This doesn't work:
$('#date_end').datepicker({ defaultDate: +31 })
$('#date_end').datepicker({ minDate: 1 })
This does both:
$('#date_end').datepicker({ defaultDate: +31, minDate: 1 })
1 and +1 work the same (or 0 and +0 in your case).
Me: Windows 7 x64, Rails 3.2.3, Ruby 1.9.3
Since your files are not yet committed in branch1
:
git stash
git checkout branch2
git stash pop
or
git stash
git checkout branch2
git stash list # to check the various stash made in different branch
git stash apply x # to select the right one
As commented by benjohn (see git stash
man page):
To also stash currently untracked (newly added) files, add the argument
-u
, so:
git stash -u
As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.
read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"
It seems fetch support URL scheme with "http" or "https" for CORS request.
Install node fetch library npm install node-fetch
, read the file and parse to json.
const fs = require('fs')
const readJson = filename => {
return new Promise((resolve, reject) => {
if (filename.toLowerCase().endsWith(".json")) {
fs.readFile(filename, (err, data) => {
if (err) {
reject(err)
return
}
resolve(JSON.parse(data))
})
}
else {
reject(new Error("Invalid filetype, <*.json> required."))
return
}
})
}
// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))
I think this way is better :
SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
ORDER BY id=1 DESC, id=3 DESC, id=2 DESC, id=4 DESC
Nested forms are not supported and are not part of the w3c standard ( as many of you have stated ).
However HTML5 adds support for inputs that don't have to be descendants of any form, but can be submitted in several forms - by using the "form" attribute. This doesn't exactly allow nested forms, but by using this method, you can simulate nested forms.
The value of the "form" attribute must be id of the form, or in case of multiple forms, separate form id's with space.
You can read more here
Simple answer: give these two tds a style field.
<tr>
<td>One</td>
<td style="padding-right: 10px">Two</td>
<td>Three</td>
<td>Four</td>
</tr>
Tidy one: use class name
<tr>
<td>One</td>
<td class="more-padding-on-right">Two</td>
<td>Three</td>
<td>Four</td>
</tr>
.more-padding-on-right {
padding-right: 10px;
}
Complex one: using nth-child selector in CSS and specify special padding values for these two, which works in modern browsers.
tr td:nth-child(2) {
padding-right: 10px;
}?
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
This happens when you index a row/column with a number that is larger than the dimensions of your dataframe
. For instance, getting the eleventh column when you have only three.
import pandas as pd
df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})
You have 5 rows and three columns:
Name City Car
0 Mark Lisbon Tesla
1 Laura Montreal Audi
2 Adam Lisbon Porsche
3 Roger Berlin Ford
4 Anna Glasgow Honda
Let's try to index the eleventh column (it doesn't exist):
df.iloc[:, 10] # there is obviously no 11th column
IndexError: single positional indexer is out-of-bounds
If you are a beginner with Python, remember that df.iloc[:, 10]
would refer to the eleventh column.
ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?
data = 'data you want inside the file'.
You can use File.write('name of file here', data)
Trying to answer my question:
No, there doesn't seem to be any simpler way than the one in the question, out of box.
After typing that in too many times, just pasted the shorter one into an executable file named 'git-conflicts', made accessible to git, now I can just:
git conflicts
to get the list I wanted.
Update: as Richard suggests, you can set up an git alias, as alternative to the executable
git config --global alias.conflicts '!git ls-files -u | cut -f 2 | sort -u'
An advantage of using the executable over the alias is that you can share that script with team members (in a bin dir part of the repo).
Just assign the import to a data property
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
then loop through the myJson
property in your template using v-for
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
NOTE
If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.
Vue converts all the properties in the data
option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.
So you can create a custom option as follows:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
then loop through the custom option in your template using $options
:
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
i actually deveopped something functional for one of my projects before and here is the code :
/**
* @param url is the URI address of the WebService
* @param parameterObject the object where all parameters are passed.
* @param returnType the return type you are expecting. Exemple : someClass.class
*/
public static <T> T getObject(String url, Object parameterObject, Class<T> returnType) {
try {
ResponseEntity<T> res;
ObjectMapper mapper = new ObjectMapper();
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
String json = mapper.writeValueAsString(restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, returnType).getBody());
return new Gson().fromJson(json, returnType);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @param url is the URI address of the WebService
* @param parameterObject the object where all parameters are passed.
* @param returnType the type of the returned object. Must be an array. Exemple : someClass[].class
*/
public static <T> List<T> getListOfObjects(String url, Object parameterObject, Class<T[]> returnType) {
try {
ObjectMapper mapper = new ObjectMapper();
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
ResponseEntity<Object[]> results = restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, Object[].class);
String json = mapper.writeValueAsString(results.getBody());
T[] arr = new Gson().fromJson(json, returnType);
return Arrays.asList(arr);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I hope that this will help somebody !
@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:
function checkAuth(req, res, next) {
// if logined or it's login request, then go next route
if (isLogin || (req.path === '/login' && req.method === 'POST')) {
next()
} else {
res.send('Not logged in yet.')
}
}
app.use('/', checkAuth)
According to the Java Language Specification (specifically §10.7 Array Members) it is a field:
- The
public
final
fieldlength
, which contains the number of components of the array (length may be positive or zero).
Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.
The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:
[...] arrays have a third header field, for the array size.
Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.
In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:
*/10 * * * * /usr/bin/php /opt/test.php
In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.
*
is a wildcard, meaning "every time".
Start with finding out your PHP binary by typing in command line:
whereis php
The output should be something like:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
crontab -e
To see what you got in crontab.
To exit from vim editor without saving just click:
Shift+:
And then type q!