This is my favorite method, but your browser support must be very progressive. With the mask property you create a mask that is applied to an element. Everywhere the mask is opaque, or solid, the underlying image shows through. Where it’s transparent, the underlying image is masked out, or hidden. The syntax for a CSS mask-image is similar to background-image.look at the codepenmask
You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance()
{
return instance;
}
}
I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array.
const https = require('https');
const apiUrl = "https://example.com/api/movies/search/?Title=";
let finaldata = [];
let someCallBack = function(data){
finaldata.push(...data);
console.log(finaldata);
};
const getData = function (substr, pageNo=1, someCallBack) {
let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
let mydata = []
https.get(actualUrl, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', async () => {
if (JSON.parse(data).total_pages!==null){
pageNo+=1;
somCallBack(JSON.parse(data).data);
await getData(substr, pageNo, someCallBack);
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
getData("spiderman", pageNo=1, someCallBack);
Like @ackuser mentioned we can use other module but In my use case I had to use the node https
. Hoping this will help others.
There is no such particular way in which you can initialize the array after declaring it once.
There are three options only:
1.) initialize them in different lines :
int array[SIZE];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...
But thats not what you want i guess.
2.) Initialize them using a for or while loop:
for (i = 0; i < MAX ; i++) {
array[i] = i;
}
This is the BEST WAY by the way to achieve your goal.
3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.
And can I ask you why specifically you want to do so???
Whilst this isn't strictly an answer to this question I think it's useful.
Arrays and Collections can bother be converted to Iterable which can avoid the need for performing a hard conversion.
For instance I wrote this to join lists/arrays of stuff into a string with a seperator
public static <T> String join(Iterable<T> collection, String delimiter) {
Iterator<T> iterator = collection.iterator();
if (!iterator.hasNext())
return "";
StringBuilder builder = new StringBuilder();
T thisVal = iterator.next();
builder.append(thisVal == null? "": thisVal.toString());
while (iterator.hasNext()) {
thisVal = iterator.next();
builder.append(delimiter);
builder.append(thisVal == null? "": thisVal.toString());
}
return builder.toString();
}
Using iterable means you can either feed in an ArrayList or similar aswell as using it with a String...
parameter without having to convert either.
Actually, I solved the problem. I run it by eclipse jetty plugin.
I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.
I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
if you want to write in column:
for x in np.nditer(a.T, order='C'):
file.write(str(x))
file.write("\n")
Here 'a' is the name of numpy array and 'file' is the variable to write in a file.
If you want to write in row:
writer= csv.writer(file, delimiter=',')
for x in np.nditer(a.T, order='C'):
row.append(str(x))
writer.writerow(row)
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.
As David pointed out, I would go with KB in most cases.
php_value post_max_size 2K
Note: my form is simple, just a few text boxes, not long text.
(PHP shorthand for KB is K, as outlined here.)
It is possible. But you have to hack it a little, there is a code What you have to do is to run stand alone server and "patch" RemoteWebDriver
public class CustomRemoteWebDriver : RemoteWebDriver
{
public static bool newSession;
public static string capPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionCap");
public static string sessiodIdPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionid");
public CustomRemoteWebDriver(Uri remoteAddress)
: base(remoteAddress, new DesiredCapabilities())
{
}
protected override Response Execute(DriverCommand driverCommandToExecute, Dictionary<string, object> parameters)
{
if (driverCommandToExecute == DriverCommand.NewSession)
{
if (!newSession)
{
var capText = File.ReadAllText(capPath);
var sidText = File.ReadAllText(sessiodIdPath);
var cap = JsonConvert.DeserializeObject<Dictionary<string, object>>(capText);
return new Response
{
SessionId = sidText,
Value = cap
};
}
else
{
var response = base.Execute(driverCommandToExecute, parameters);
var dictionary = (Dictionary<string, object>) response.Value;
File.WriteAllText(capPath, JsonConvert.SerializeObject(dictionary));
File.WriteAllText(sessiodIdPath, response.SessionId);
return response;
}
}
else
{
var response = base.Execute(driverCommandToExecute, parameters);
return response;
}
}
}
As a note ,
for those who need to have null value for things other than "true" or "false" strings , you can use the function below
public Boolean tryParseBoolean(String inputBoolean)
{
if(!inputBoolean.equals("true")&&!inputBoolean.equals("false")) return null;
return Boolean.valueOf(inputBoolean);
}
There are some references and pointers in the comments on this page at PHP.net:
Torsten says
"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."
Jetboy says
"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.
Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
It has nothing to do with jQuery, it's just a handy js method built into modern browsers.
Think of it as a handy alternative to debugging via window.alert()
Using @extend is a fine solution, but be aware that the compiled css will break up the class definition. Any classes that extends the same placeholder will be grouped together and the rules that aren't extended in the class will be in a separate definition. If several classes become extended, it can become unruly to look up a selector in the compiled css or the dev tools. Whereas a mixin will duplicate the mixin code and add any additional styles.
You can see the difference between @extend and @mixin in this sassmeister
I find Core Graphics to be pretty simple for Swift 3:
if let cgcontext = UIGraphicsGetCurrentContext() {
cgcontext.strokeEllipse(in: CGRect(x: center.x-diameter/2, y: center.y-diameter/2, width: diameter, height: diameter))
}
Here is a little work around that I created. I checked it with R and it works correct.
import numpy as np
import statsmodels.api as sm
y = [1,2,3,4,3,4,5,4,5,5,4,5,4,5,4,5,6,5,4,5,4,3,4]
x = [
[4,2,3,4,5,4,5,6,7,4,8,9,8,8,6,6,5,5,5,5,5,5,5],
[4,1,2,3,4,5,6,7,5,8,7,8,7,8,7,8,7,7,7,7,7,6,5],
[4,1,2,5,6,7,8,9,7,8,7,8,7,7,7,7,7,7,6,6,4,4,4]
]
def reg_m(y, x):
ones = np.ones(len(x[0]))
X = sm.add_constant(np.column_stack((x[0], ones)))
for ele in x[1:]:
X = sm.add_constant(np.column_stack((ele, X)))
results = sm.OLS(y, X).fit()
return results
Result:
print reg_m(y, x).summary()
Output:
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.535
Model: OLS Adj. R-squared: 0.461
Method: Least Squares F-statistic: 7.281
Date: Tue, 19 Feb 2013 Prob (F-statistic): 0.00191
Time: 21:51:28 Log-Likelihood: -26.025
No. Observations: 23 AIC: 60.05
Df Residuals: 19 BIC: 64.59
Df Model: 3
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1 0.2424 0.139 1.739 0.098 -0.049 0.534
x2 0.2360 0.149 1.587 0.129 -0.075 0.547
x3 -0.0618 0.145 -0.427 0.674 -0.365 0.241
const 1.5704 0.633 2.481 0.023 0.245 2.895
==============================================================================
Omnibus: 6.904 Durbin-Watson: 1.905
Prob(Omnibus): 0.032 Jarque-Bera (JB): 4.708
Skew: -0.849 Prob(JB): 0.0950
Kurtosis: 4.426 Cond. No. 38.6
pandas
provides a convenient way to run OLS as given in this answer:
If you need or want a simple HTTP server with the following:
I built one on top of the excellent SimpleHTTPAuthServer already on PyPI. This adds handling of POST requests: https://github.com/arielampol/SimpleHTTPAuthServerWithPOST
Otherwise, all the other options publicly available are already so good and robust.
You just have to put the <form ... >
tag before the <table>
tag and the </form>
at the end.
Hopte it helps.
There are several problems in your code.
First the big ones:
You are creating a new figure and a new axes in every iteration of your loop ?
put fig = plt.figure
and ax = fig.add_subplot(1,1,1)
outside of the loop.
Don't use the Locators. Call the functions ax.set_xticks()
and ax.grid()
with the correct keywords.
With plt.axes()
you are creating a new axes again. Use ax.set_aspect('equal')
.
The minor things:
You should not mix the MATLAB-like syntax like plt.axis()
with the objective syntax.
Use ax.set_xlim(a,b)
and ax.set_ylim(a,b)
This should be a working minimal example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
# And a corresponding grid
ax.grid(which='both')
# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
plt.show()
Output is this:
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
I have a proper solution of this problem, lets try and understand the root cause of this issue. This issue comes when remote servers ssl cannot be verified using root certificates in your system's certificate store or remote ssl is not installed along with chain certificates. If you have a linux system with root ssh access, then in this case you can try updating your certificate store with below command:
update-ca-certificates
If still, it doesn't work then you need to add root and interim certificate of remote server in your cert store. You can download root and intermediate certs and add them in /usr/local/share/ca-certificates directory and then run command update-ca-certificates
. This should do the trick. Similarly for windows you can search how to add root and intermediate cert.
The other way you can solve this problem is by asking remote server team to add ssl certificate as a bundle of domain root cert, intermediate cert and root cert.
If you don't want to wrap a table under any div:
table{
table-layout: fixed;
}
tbody{
display: block;
overflow: auto;
}
Using requests and json makes it simple.
json.loads
functionRequests module provides you useful function to loop for success and failure.
if(Response.ok)
: will help help you determine if your API call is successful (Response code - 200)
Response.raise_for_status()
will help you fetch the http code that is returned from the API.
Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.
#Python 2.7.6
#RestfulClient.py
import requests
from requests.auth import HTTPDigestAuth
import json
# Replace with the correct URL
url = "http://api_url"
# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)
# For successful API call, response code will be 200 (OK)
if(myResponse.ok):
# Loading the response data into a dict variable
# json.loads takes in only binary or string variables so using content to fetch binary content
# Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
jData = json.loads(myResponse.content)
print("The response contains {0} properties".format(len(jData)))
print("\n")
for key in jData:
print key + " : " + jData[key]
else:
# If response code is not ok (200), print the resulting http error code with description
myResponse.raise_for_status()
If your collection gets too big, I have found that Xml serialization gets quite slow. Another option to serialize your dictionary would be "roll your own" using a BinaryReader and BinaryWriter.
Here's some sample code just to get you started. You can make these generic extension methods to handle any type of Dictionary, and it works quite well, but is too verbose to post here.
class Account
{
public string AccountName { get; set; }
public int AccountNumber { get; set; }
internal void Serialize(BinaryWriter bw)
{
// Add logic to serialize everything you need here
// Keep in synch with Deserialize
bw.Write(AccountName);
bw.Write(AccountNumber);
}
internal void Deserialize(BinaryReader br)
{
// Add logic to deserialize everythin you need here,
// Keep in synch with Serialize
AccountName = br.ReadString();
AccountNumber = br.ReadInt32();
}
}
class Program
{
static void Serialize(string OutputFile)
{
// Write to disk
using (Stream stream = File.Open(OutputFile, FileMode.Create))
{
BinaryWriter bw = new BinaryWriter(stream);
// Save number of entries
bw.Write(accounts.Count);
foreach (KeyValuePair<string, List<Account>> accountKvp in accounts)
{
// Save each key/value pair
bw.Write(accountKvp.Key);
bw.Write(accountKvp.Value.Count);
foreach (Account account in accountKvp.Value)
{
account.Serialize(bw);
}
}
}
}
static void Deserialize(string InputFile)
{
accounts.Clear();
// Read from disk
using (Stream stream = File.Open(InputFile, FileMode.Open))
{
BinaryReader br = new BinaryReader(stream);
int entryCount = br.ReadInt32();
for (int entries = 0; entries < entryCount; entries++)
{
// Read in the key-value pairs
string key = br.ReadString();
int accountCount = br.ReadInt32();
List<Account> accountList = new List<Account>();
for (int i = 0; i < accountCount; i++)
{
Account account = new Account();
account.Deserialize(br);
accountList.Add(account);
}
accounts.Add(key, accountList);
}
}
}
static Dictionary<string, List<Account>> accounts = new Dictionary<string, List<Account>>();
static void Main(string[] args)
{
string accountName = "Bob";
List<Account> newAccounts = new List<Account>();
newAccounts.Add(AddAccount("A", 1));
newAccounts.Add(AddAccount("B", 2));
newAccounts.Add(AddAccount("C", 3));
accounts.Add(accountName, newAccounts);
accountName = "Tom";
newAccounts = new List<Account>();
newAccounts.Add(AddAccount("A1", 11));
newAccounts.Add(AddAccount("B1", 22));
newAccounts.Add(AddAccount("C1", 33));
accounts.Add(accountName, newAccounts);
string saveFile = @"C:\accounts.bin";
Serialize(saveFile);
// clear it out to prove it works
accounts.Clear();
Deserialize(saveFile);
}
static Account AddAccount(string AccountName, int AccountNumber)
{
Account account = new Account();
account.AccountName = AccountName;
account.AccountNumber = AccountNumber;
return account;
}
}
Here you go:
Just change the line1 style as per below:
line1: {
backgroundColor: '#FDD7E4',
width:'100%',
alignSelf:'center'
}
Here's some Unicode-friendly ones you can make if you pull in ICU4j. I guess "ignore case" is questionable for the method names because although primary strength comparisons do ignore case, it's described as the specifics being locale-dependent. But it's hopefully locale-dependent in a way the user would expect.
public static boolean containsIgnoreCase(String haystack, String needle) {
return indexOfIgnoreCase(haystack, needle) >= 0;
}
public static int indexOfIgnoreCase(String haystack, String needle) {
StringSearch stringSearch = new StringSearch(needle, haystack);
stringSearch.getCollator().setStrength(Collator.PRIMARY);
return stringSearch.first();
}
All the above works, and here is another way if you just want to number of days/time back rather a entering date
select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
if not exists (select * from sysobjects where name='cars' and xtype='U')
create table cars (
Name varchar(64) not null
)
go
The above will create a table called cars
if the table does not already exist.
The TypeInitializationException
that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.
TypeInitializationException is also called static constructors.
This is the correct way to perform the check as-per Microsoft's knowledgebase reference ( http://support.microsoft.com/kb/556009 ) that I have re-edited into just a single line of code.
It doesn't rely on any environment variables or folder names and instead checks directly in the registry.
As shown in a full batch file below it sets an environment variable OS equal to either 32BIT or 64BIT that you can use as desired.
@echo OFF
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT
if %OS%==32BIT echo This is a 32bit operating system
if %OS%==64BIT echo This is a 64bit operating system
The C and C++ declaration syntax has repeatedly been described as a failed experiment, by the original designers.
Instead, let's name the type “pointer to Type
”; I’ll call it Ptr_
:
template< class Type >
using Ptr_ = Type*;
Now Ptr_<char>
is a pointer to char
.
Ptr_<const char>
is a pointer to const char
.
And const Ptr_<const char>
is a const
pointer to const char
.
There.
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
ls -l | grep "^-"
Hope this one would serve your purpose.
If your detached HEAD is a fast forward of master and you just want the commits upstream, you can
git push origin HEAD:master
to push directly, or
git checkout master && git merge [ref of HEAD]
will merge it back into your local master.
string1.equals(string2)
is the way.
It returns true
if string1
is equals to string2
in value. Else, it will return false
.
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
Also, GitHub pages doesn't currently support Git LFS. As such, if you have images (or other binary assets) in GitHub pages committed with Git LFS, you'll get 404 not found for those files.
This will be quite common for documentation generated with Doxygen or similar tool.
The solution in this case is to simply not commit those files with Git LFS.
d
stands for Declaration Files:
When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.
The concept of declaration files is analogous to the concept of header file found in C/C++.
declare module arithmetics {
add(left: number, right: number): number;
subtract(left: number, right: number): number;
multiply(left: number, right: number): number;
divide(left: number, right: number): number;
}
Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.
I suggest you step through the code in your debugger as debugging programs is what it is for.
What I would expect you would see is that every time the code loops int x = 0;
is set.
You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
Use Carbon\Carbon;
$targetDate = "2014-06-26 04:07:31";
Carbon::parse($targetDate)->format('Y-m-d');
If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views
You can use $_SERVER['HTTP_REFERER']
this will give you whole URL for example:
suppose you want to get url of site name www.example.com
then $_SERVER['HTTP_REFERER']
will give you https://www.example.com
I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running
which myscript.py
Also, if myscripy.py
depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.
$python
Python 2.7.8 blahblahblah
...
>from mymodule.submodule import ClassName
>test = ClassName()
>^D
$myscript_that_needs_mymodule.submodule.py
Traceback (most recent call last):
File "myscript_that_needs_mymodule.submodule.py", line 5, in <module>
from mymodule.submodule import ClassName
File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in <module>
from mymodule.submodule import ClassName
ImportError: No module named submodule
import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)
yields:
[[ 1. 1. 1.]
[ 2. 2. 2.]
[ 3. 3. 3.]]
I also like to define my own functions that take and return arguments in degrees rather than radians. I am sure there some capitalization purest who don't like my names, but I just use a capital first letter for my custom functions. The definitions and testing code are below.
#Definitions for trig functions using degrees.
def Cos(a):
return cos(radians(a))
def Sin(a):
return sin(radians(a))
def Tan(a):
return tan(radians(a))
def ArcTan(a):
return degrees(arctan(a))
def ArcSin(a):
return degrees(arcsin(a))
def ArcCos(a):
return degrees(arccos(a))
#Testing Code
print(Cos(90))
print(Sin(90))
print(Tan(45))
print(ArcTan(1))
print(ArcSin(1))
print(ArcCos(0))
Note that I have imported math (or numpy) into the namespace with
from math import *
Also note, that my functions are in the namespace in which they were defined. For instance,
math.Cos(45)
does not exist.
For excluding multiple file types, you can use '+' to concatenate other lists. For example:
xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan
Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/
Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/
Searched several houres before I found there were some linebreaks in the included files.
If you still want to group only by one column (as I wanted) you can nest the query:
select c1, count(*) from (select distinct c1, c2 from t) group by c1
Another source of stack smashing is (incorrect) use of vfork()
instead of fork()
.
I just debugged a case of this, where the child process was unable to execve()
the target executable and returned an error code rather than calling _exit()
.
Because vfork()
had spawned that child, it returned while actually still executing within the parent's process space, not only corrupting the parent's stack, but causing two disparate sets of diagnostics to be printed by "downstream" code.
Changing vfork()
to fork()
fixed both problems, as did changing the child's return
statement to _exit()
instead.
But since the child code precedes the execve()
call with calls to other routines (to set the uid/gid, in this particular case), it technically does not meet the requirements for vfork()
, so changing it to use fork()
is correct here.
(Note that the problematic return
statement was not actually coded as such -- instead, a macro was invoked, and that macro decided whether to _exit()
or return
based on a global variable. So it wasn't immediately obvious that the child code was nonconforming for vfork()
usage.)
For more information, see:
You can do the following to learn/test the concept:
Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module
In newly added Module1 add the declaration; Public Global1 As String
in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:
Sub setMe() Global1 = "Hello" End Sub
Sub showMe() Debug.Print (Global1) End Sub
setMe()
and then Sub showMe()
to test the global visibility/accessibility of the var Global1
Hope this will help.
Html:
<div class="outerDiv">
<div class="innerDiv">Content</div>
</div>
CSS:
.outerDiv{
background: #000;
padding: 10px;
}
.innerDiv{
border: 2px dashed #fff;
min-height: 200px; //adding min-height as there is no content inside
}
After creating your QVBoxLayout
in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout
, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout
should now stretch to fit the window and will resize automatically when the entire window is resized.
You could also get all relevant details from performance_schema:
SELECT
OBJECT_SCHEMA
,OBJECT_NAME
,GROUP_CONCAT(DISTINCT EXTERNAL_LOCK)
FROM performance_schema.table_handles
WHERE EXTERNAL_LOCK IS NOT NULL
GROUP BY
OBJECT_SCHEMA
,OBJECT_NAME
This works similar as
show open tables WHERE In_use > 0
you can make use of the following code:
from __future__ import division, unicode_literals
import codecs
from bs4 import BeautifulSoup
f=codecs.open("test.html", 'r', 'utf-8')
document= BeautifulSoup(f.read()).get_text()
print document
If you want to delete all the blank lines in between and get all the words as a string (also avoid special characters, numbers) then also include:
import nltk
from nltk.tokenize import word_tokenize
docwords=word_tokenize(document)
for line in docwords:
line = (line.rstrip())
if line:
if re.match("^[A-Za-z]*$",line):
if (line not in stop and len(line)>1):
st=st+" "+line
print st
*define st
as a string
initially, like st=""
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>
From here.
For IIS7 and above, you also need to add the lines below:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
Use --net="host"
in your docker run
command, then localhost
in your docker container will point to your docker host.
Poor man's configuration file:
Add to your index.html as first líne in the body tag:
<script lang="javascript" src="assets/config.js"></script>
Add assets/config.js:
var config = {
apiBaseUrl: "http://localhost:8080"
}
Add config.ts:
export const config: AppConfig = window['config']
export interface AppConfig {
apiBaseUrl: string
}
This blog post was helpful for me. I used the "Homebrew built Vim" solution, which in my case saved the new version in /usr/local/bin. At this point, the post suggested hiding the system vim, which didn't work for me, so I used an alias instead.
$ brew install vim
$ alias vim='/path/to/new/vim
$ which vim
vim: aliased to /path/to/new/vim
Mount GDrive:
from google.colab import drive
drive.mount('/content/gdrive')
Open the link -> copy authorization code -> paste that into the prompt and press "Enter"
Check GDrive access:
!ls "/content/gdrive/My Drive"
Unzip (q stands for "quiet") file from GDrive:
!unzip -q "/content/gdrive/My Drive/dataset.zip"
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1
. If you have multiple checkboxes named c1
how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call
part to convert the NodeList
returned by document.querySelectorAll
into an array that you can call some
on.
A H4 elemental is a block display type element. You could force the H4 to have a inline display type, or simply use an inline element like P instead and style it however you require.
For reference: http://www.w3.org/TR/CSS21/visuren.html#propdef-display
So you'd change the display type of the H4 like:
<html>
<head>
<title>test</title>
<style type='text/css'>
h4 { display: inline }
</style>
</head>
<body>
<img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/><h4 class='liketext'>$likes</h4>
<img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/><h4 class='liketext'>$dislikes</h4>
</body>
</html>
Using typescript, I use a custom interface that only applies to my function. Example use case.
handleChange(event: { target: HTMLInputElement; }) {
this.setState({ value: event.target.value });
}
In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.
Later in my code I can use
<input type='text' value={this.state.value} onChange={this.handleChange} />
A cleaner approach would be to put the interface to a separate file.
interface HandleNameChangeInterface {
target: HTMLInputElement;
}
then later use the following function definition:
handleChange(event: HandleNameChangeInterface) {
this.setState({ value: event.target.value });
}
In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.
HTML:
<button type="submit" onclick="window.open('file.doc')">Download!</button>
I had gotten frustrated with this problem myself and so I modified the filter that was created by @Trevor Senior as I was running into an issue with my console saying that it could not use the reverse method. I also, wanted to keep the integrity of the object because this is what Angular is originally using in a ng-repeat directive. In this case I used the input of stupid (key) because the console will get upset saying there are duplicates and in my case I needed to track by $index.
Filter:
angular.module('main').filter('reverse', function() {
return function(stupid, items) {
var itemss = items.files;
itemss = itemss.reverse();
return items.files = itemss;
};
});
HTML:
<div ng-repeat="items in items track by $index | reverse: items">
Or this in windows powershell
$env:RANDFILE=".rnd"
Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.
In order to match PyQt5's behavior, you have to create the started signal yourself.
Here is an easy solution:
# Use this class instead of QThread
class QThread2(QThread):
# Use this signal instead of "started"
started2 = Signal()
def __init__(self):
QThread.__init__(self)
self.started.connect(self.onStarted)
def onStarted(self):
self.started2.emit()
Had the same problem (is not a method) with jQuery when working on autocomplete. It appeared the code was executed before the autocomplete.js was loaded. So make sure the ui.colorpicker.js is loaded before calling colorpicker.
under my .git/hooks folder, some sample files were missing. like commit-msg,post-commit.sample,post-update.sample...adding these files resolved my change id missing issue.
With hidden field you need to use like this:
$("._statusDDL").val(2);
$("._statusDDL").change();
or
$("._statusDDL").val(2).change();
Aangular 2 final has updated APIs. They have added many methods for this.
To update the form control from controller do this:
this.form.controls['dept'].setValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
No need to reset the errors
References
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
https://toddmotto.com/angular-2-form-controls-patch-value-set-value
There's a truly horrifying amount of ancient code out there in the wild, much of it in the form of common CPAN modules. I've found I have to be fairly careful enabling Unicode if I use external modules that might be affected by it, and am still trying to identify and fix some Unicode-related failures in several Perl scripts I use regularly (in particular, iTiVo fails badly on anything that's not 7-bit ASCII due to transcoding issues).
I faced the same problem couple of times and each time the reason was different:
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
For those who wants to type password within the command line. It is possible but recommend to pass it inside quotes so that the special character won't cause any issue.
mysqldump -h'my.address.amazonaws.com' -u'my_username' -p'password' db_name > /path/backupname.sql
According to your sample,
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="abc.js" type="text/javascript">
</script>
<link rel="stylesheets" type="text/css" href="abc.css"></link>
<style>h2{font-wight:bold;}</style>
<script>
$(document).ready(function(){
$("#img").attr("src", "kkk.png");
});
</script>
</head>
<body>
<img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
<script src="kkk.js" type="text/javascript"></script>
</body>
</html>
roughly the execution flow is about as follows:
<script src="jquery.js" ...
jquery.js
is downloaded and parsed<script src="abc.js" ...
abc.js
is downloaded, parsed and run<link href="abc.css" ...
abc.css
is downloaded and parsed<style>...</style>
<script>...</script>
<img src="abc.jpg" ...
abc.jpg
is downloaded and displayed<script src="kkk.js" ...
kkk.js
is downloaded, parsed and runNote that the download may be asynchronous and non-blocking due to behaviours of the browser. For example, in Firefox there is this setting which limits the number of simultaneous requests per domain.
Also depending on whether the component has already been cached or not, the component may not be requested again in a near-future request. If the component has been cached, the component will be loaded from the cache instead of the actual URL.
When the parsing is ended and document is ready and loaded, the events onload
is fired. Thus when onload
is fired, the $("#img").attr("src","kkk.png");
is run. So:
$("#img").attr("src", "kkk.png");
kkk.png
is downloaded and loads into #img
The $(document).ready()
event is actually the event fired when all page components are loaded and ready. Read more about it: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
By default, and from my current understanding, browser usually runs each page on 3 ways: HTML parser, Javascript/DOM, and CSS.
The HTML parser is responsible for parsing and interpreting the markup language and thus must be able to make calls to the other 2 components.
For example when the parser comes across this line:
<a href="#" onclick="alert('test');return false;" style="font-weight:bold">a hypertext link</a>
The parser will make 3 calls, two to Javascript and one to CSS. Firstly, the parser will create this element and register it in the DOM namespace, together with all the attributes related to this element. Secondly, the parser will call to bind the onclick event to this particular element. Lastly, it will make another call to the CSS thread to apply the CSS style to this particular element.
The execution is top down and single threaded. Javascript may look multi-threaded, but the fact is that Javascript is single threaded. This is why when loading external javascript file, the parsing of the main HTML page is suspended.
However, the CSS files can be download simultaneously because CSS rules are always being applied - meaning to say elements are always repainted with the freshest CSS rules defined - thus making it unblocking.
An element will only be available in the DOM after it has been parsed. Thus when working with a specific element, the script is always placed after, or within the window onload event.
Script like this will cause error (on jQuery):
<script type="text/javascript">/* <![CDATA[ */
alert($("#mydiv").html());
/* ]]> */</script>
<div id="mydiv">Hello World</div>
Because when the script is parsed, #mydiv
element is still not defined. Instead this would work:
<div id="mydiv">Hello World</div>
<script type="text/javascript">/* <![CDATA[ */
alert($("#mydiv").html());
/* ]]> */</script>
OR
<script type="text/javascript">/* <![CDATA[ */
$(window).ready(function(){
alert($("#mydiv").html());
});
/* ]]> */</script>
<div id="mydiv">Hello World</div>
I use this startup script on Ubuntu.
#!/bin/sh
### BEGIN INIT INFO
# Provides: mongodb
# Required-Sart:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: mongodb
# Description: mongo db server
### END INIT INFO
. /lib/lsb/init-functions
PROGRAM=/opt/mongo/bin/mongod
MONGOPID=`ps -ef | grep 'mongod' | grep -v grep | awk '{print $2}'`
test -x $PROGRAM || exit 0
case "$1" in
start)
log_begin_msg "Starting MongoDB server"
ulimit -v unlimited.
ulimit -n 100000
/opt/mongo/bin/mongod --fork --quiet --dbpath /data/db --bind_ip 127.0.0.1 --rest --config /etc/mongod.conf.
log_end_msg 0
;;
stop)
log_begin_msg "Stopping MongoDB server"
if [ ! -z "$MONGOPID" ]; then
kill -15 $MONGOPID
fi
log_end_msg 0
;;
status)
;;
*)
log_success_msg "Usage: /etc/init.d/mongodb {start|stop|status}"
exit 1
esac
exit 0
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1]) # bashrc
print(extension_b[-1]) # txt
function getCustomHeaders()
{
$headers = array();
foreach($_SERVER as $key => $value)
{
if(preg_match("/^HTTP_X_/", $key))
$headers[$key] = $value;
}
return $headers;
}
I use this function to get the custom headers, if the header starts from "HTTP_X_" we push in the array :)
Test whether something exists at given path using the -e
file-test operator.
print "$base_path exists!\n" if -e $base_path;
However, this test is probably broader than you intend. The code above will generate output if a plain file exists at that path, but it will also fire for a directory, a named pipe, a symlink, or a more exotic possibility. See the documentation for details.
Given the extension of .TGZ
in your question, it seems that you expect a plain file rather than the alternatives. The -f
file-test operator asks whether a path leads to a plain file.
print "$base_path is a plain file!\n" if -f $base_path;
The perlfunc documentation covers the long list of Perl's file-test operators that covers many situations you will encounter in practice.
-r
File is readable by effective uid/gid.-w
File is writable by effective uid/gid.-x
File is executable by effective uid/gid.-o
File is owned by effective uid.-R
File is readable by real uid/gid.-W
File is writable by real uid/gid.-X
File is executable by real uid/gid.-O
File is owned by real uid.-e
File exists.-z
File has zero size (is empty).-s
File has nonzero size (returns size in bytes).-f
File is a plain file.-d
File is a directory.-l
File is a symbolic link (false if symlinks aren’t supported by the file system).-p
File is a named pipe (FIFO), or Filehandle is a pipe.-S
File is a socket.-b
File is a block special file.-c
File is a character special file.-t
Filehandle is opened to a tty.-u
File has setuid bit set.-g
File has setgid bit set.-k
File has sticky bit set.-T
File is an ASCII or UTF-8 text file (heuristic guess).-B
File is a “binary” file (opposite of-T
).-M
Script start time minus file modification time, in days.-A
Same for access time.-C
Same for inode change time (Unix, may differ for other platforms)
Another work around would be to use javascript:
//jquery
$('textarea#someid').html($('textarea#someid').html().trim());
//without jquery
document.getElementById('someid').innerHTML = document.getElementById('someid').innerHTML.trim();
This is what I did. Removing white-spaces and line-breaks in the code makes the line too long.
The gradle versions in android studio and your code is not the same. This is why even after you update the gradle version on android studio, the error still persist.
So, edit the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file:
distributionUrl = https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
Ref: https://developer.android.com/studio/releases/gradle-plugin.html#updating-gradle
Use a server implementation to send messages to your client and use data type of messages rather than notification type of messages.
This will help you get a callback to onMessageReceived
irrespective if your app is in background or foreground and you can generate your custom notification then
To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:
val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
case Process("b", _) => println("first: 'a', some rest")
case Process(_, rest) => println("some first, rest: " + rest)
// etc.
}
DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY
Replace N with your day count
Also to find the position of the element "which" can be used as
pop <- c(3,4,5,7,13)
which(pop==13)
and to find the elements which are not contained in the target vector, one may do this:
pop <- c(1,2,4,6,10)
Tset <- c(2,10,7) # Target set
pop[which(!(pop%in%Tset))]
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.
There is no need for capture groups. Just match id=
then forget those characters with \K
, then isolate the following one or more digital characters.
Code (Demo)
$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
Output:
736375493
Works on UBUNTU 16.04.3 Just open
usr/share/libraries/sql.lib.php
modify
|| (count($analyzed_sql_results['select_expr'] == 1)
To
|| ((count($analyzed_sql_results['select_expr']) == 1)
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
You can try to use TCPView utility.
Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.
Its really works for me.
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.
A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.
Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.
I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.
Parse a filename from the fully qualified path name (e.g., c:\temp\my.bat) to any component (e.g., File.ext).
Single line of code:
For %%A in ("C:\Folder1\Folder2\File.ext") do (echo %%~fA)
You can change out "C:\Folder1\Folder2\File.ext" for any full path and change "%%~fA" for any of the other options you will find by running "for /?" at the command prompt.
Elaborated Code
set "filename=C:\Folder1\Folder2\File.ext"
For %%A in ("%filename%") do (
echo full path: %%~fA
echo drive: %%~dA
echo path: %%~pA
echo file name only: %%~nA
echo extension only: %%~xA
echo expanded path with short names: %%~sA
echo attributes: %%~aA
echo date and time: %%~tA
echo size: %%~zA
echo drive + path: %%~dpA
echo name.ext: %%~nxA
echo full path + short name: %%~fsA)
Standalone Batch Script
Save as C:\cmd\ParseFn.cmd.
Add C:\cmd to your PATH environment variable and use it to store all of you reusable batch scripts.
@echo off
@echo ::___________________________________________________________________::
@echo :: ::
@echo :: ParseFn ::
@echo :: ::
@echo :: Chris Advena ::
@echo ::___________________________________________________________________::
@echo.
::
:: Process arguements
::
if "%~1%"=="/?" goto help
if "%~1%"=="" goto help
if "%~2%"=="/?" goto help
if "%~2%"=="" (
echo !!! Error: ParseFn requires two inputs. !!!
goto help)
set in=%~1%
set out=%~2%
:: echo "%in:~3,1%" "%in:~0,1%"
if "%in:~3,1%"=="" (
if "%in:~0,1%"=="/" (
set in=%~2%
set out=%~1%)
)
::
:: Parse filename
::
set "ret="
For %%A in ("%in%") do (
if "%out%"=="/f" (set ret=%%~fA)
if "%out%"=="/d" (set ret=%%~dA)
if "%out%"=="/p" (set ret=%%~pA)
if "%out%"=="/n" (set ret=%%~nA)
if "%out%"=="/x" (set ret=%%~xA)
if "%out%"=="/s" (set ret=%%~sA)
if "%out%"=="/a" (set ret=%%~aA)
if "%out%"=="/t" (set ret=%%~tA)
if "%out%"=="/z" (set ret=%%~zA)
if "%out%"=="/dp" (set ret=%%~dpA)
if "%out%"=="/nx" (set ret=%%~nxA)
if "%out%"=="/fs" (set ret=%%~fsA)
)
echo ParseFn result: %ret%
echo.
goto end
:help
@echo off
:: @echo ::___________________________________________________________________::
:: @echo :: ::
:: @echo :: ParseFn Help ::
:: @echo :: ::
:: @echo :: Chris Advena ::
:: @echo ::___________________________________________________________________::
@echo.
@echo ParseFn parses a fully qualified path name (e.g., c:\temp\my.bat)
@echo into the requested component, such as drive, path, filename,
@echo extenstion, etc.
@echo.
@echo Syntax: /switch filename
@echo where,
@echo filename is a fully qualified path name including drive,
@echo folder(s), file name, and extension
@echo.
@echo Select only one switch:
@echo /f - fully qualified path name
@echo /d - drive letter only
@echo /p - path only
@echo /n - file name only
@echo /x - extension only
@echo /s - expanded path contains short names only
@echo /a - attributes of file
@echo /t - date/time of file
@echo /z - size of file
@echo /dp - drive + path
@echo /nx - file name + extension
@echo /fs - full path + short name
@echo.
:end
:: @echo ::___________________________________________________________________::
:: @echo :: ::
:: @echo :: ParseFn finished ::
:: @echo ::___________________________________________________________________::
:: @echo.
Another indexed approach able to process any number of arrays at once:
// Calculate intersection of multiple array or object values.
function intersect (arrList) {
var arrLength = Object.keys(arrList).length;
// (Also accepts regular objects as input)
var index = {};
for (var i in arrList) {
for (var j in arrList[i]) {
var v = arrList[i][j];
if (index[v] === undefined) index[v] = 0;
index[v]++;
};
};
var retv = [];
for (var i in index) {
if (index[i] == arrLength) retv.push(i);
};
return retv;
};
It works only for values that can be evaluated as strings and you should pass them as an array like:
intersect ([arr1, arr2, arr3...]);
...but it transparently accepts objects as parameter or as any of the elements to be intersected (always returning array of common values). Examples:
intersect ({foo: [1, 2, 3, 4], bar: {a: 2, j:4}}); // [2, 4]
intersect ([{x: "hello", y: "world"}, ["hello", "user"]]); // ["hello"]
EDIT: I just noticed that this is, in a way, slightly buggy.
That is: I coded it thinking that input arrays cannot itself contain repetitions (as provided example doesn't).
But if input arrays happen to contain repetitions, that would produce wrong results. Example (using below implementation):
intersect ([[1, 3, 4, 6, 3], [1, 8, 99]]);
// Expected: [ '1' ]
// Actual: [ '1', '3' ]
Fortunately this is easy to fix by simply adding second level indexing. That is:
Change:
if (index[v] === undefined) index[v] = 0;
index[v]++;
by:
if (index[v] === undefined) index[v] = {};
index[v][i] = true; // Mark as present in i input.
...and:
if (index[i] == arrLength) retv.push(i);
by:
if (Object.keys(index[i]).length == arrLength) retv.push(i);
Complete example:
// Calculate intersection of multiple array or object values.
function intersect (arrList) {
var arrLength = Object.keys(arrList).length;
// (Also accepts regular objects as input)
var index = {};
for (var i in arrList) {
for (var j in arrList[i]) {
var v = arrList[i][j];
if (index[v] === undefined) index[v] = {};
index[v][i] = true; // Mark as present in i input.
};
};
var retv = [];
for (var i in index) {
if (Object.keys(index[i]).length == arrLength) retv.push(i);
};
return retv;
};
intersect ([[1, 3, 4, 6, 3], [1, 8, 99]]); // [ '1' ]
Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr)
thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)
have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)
SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
You can also use HTTP_HOST
instead of SERVER_NAME
as Herman commented. See this related question for a full discussion. In short, you are probably OK with using either. Here is the 'host' version:
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
Typically, I set ServerName
in the VirtualHost
because I want that to be the canonical form of the website. The $_SERVER['HTTP_HOST']
is set based on the request headers. If the server responds to any/all domain names at that IP address, a user could spoof the header, or worse, someone could point a DNS record to your IP address, and then your server / website would be serving out a website with dynamic links built on an incorrect URL. If you use the latter method you should also configure your vhost
or set up an .htaccess
rule to enforce the domain you want to serve out, something like:
RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server
Hope that helps. The real point of this answer was just to provide the first line of code for those people who ended up here when searching for a way to get the complete URL with apache :)
this works in all browsers (IE is an oddball)
setTimeout( (function(x) {
return function() {
postinsql(x);
};
})(topicId) , 4000);
In my case, I have applied display:block
in outer class.
Need to experiment, where it fits.
Inside inline svg
adding class and style does not even remove the above white-space.
See: where the display:block
gets applied.
<div class="col-3 col-sm-3 col-md-2 front-tpcard"><a class="noDecoration" href="#">
<img class="img-thumbnail img-fluid"><svg id="Layer_1"></svg>
<p class="cardtxt">Text</p>
</a>
</div>
The class applied
.front-tpcard .img-thumbnail{
display: block; /*To hide the blank whitespace in svg*/
}
This worked for me.
Inner svg
class did not worked
To have newline in code you use _
Example:
Dim a As Integer
a = 500 _
+ 80 _
+ 90
MsgBox a
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.
sudo apt install valgrind # Ubuntu, Debian, etc.
sudo yum install valgrind # RHEL, CentOS, Fedora, etc.
Valgrind is readily usable for C/C++ code, but can even be used for other languages when configured properly (see this for Python).
To run Valgrind, pass the executable as an argument (along with any parameters to the program).
valgrind --leak-check=full \
--show-leak-kinds=all \
--track-origins=yes \
--verbose \
--log-file=valgrind-out.txt \
./executable exampleParam1
The flags are, in short:
--leak-check=full
: "each individual leak will be shown in detail"--show-leak-kinds=all
: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.--track-origins=yes
: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.--verbose
: Can tell you about unusual behavior of your program. Repeat for more verbosity.--log-file
: Write to a file. Useful when output exceeds terminal space.Finally, you would like to see a Valgrind report that looks like this:
HEAP SUMMARY:
in use at exit: 0 bytes in 0 blocks
total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated
All heap blocks were freed -- no leaks are possible
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
So, you have a memory leak, and Valgrind isn't saying anything meaningful. Perhaps, something like this:
5 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
by 0x40053E: main (in /home/Peri461/Documents/executable)
Let's take a look at the C code I wrote too:
#include <stdlib.h>
int main() {
char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
return 0;
}
Well, there were 5 bytes lost. How did it happen? The error report just says
main
and malloc
. In a larger program, that would be seriously troublesome to
hunt down. This is because of how the executable was compiled. We can
actually get line-by-line details on what went wrong. Recompile your program
with a debug flag (I'm using gcc
here):
gcc -o executable -std=c11 -Wall main.c # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c # add -ggdb3 to it
Now with this debug build, Valgrind points to the exact line of code allocating the memory that got leaked! (The wording is important: it might not be exactly where your leak is, but what got leaked. The trace helps you find where.)
5 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
by 0x40053E: main (main.c:4)
IndexOutOfBoundsException
type problems.Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:
gdb
perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.60 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
by 0x4005E4: resizeArray (main.c:12)
by 0x40062E: main (main.c:19)
And the code:
#include <stdlib.h>
#include <stdint.h>
struct _List {
int32_t* data;
int32_t length;
};
typedef struct _List List;
List* resizeArray(List* array) {
int32_t* dPtr = array->data;
dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
return array;
}
int main() {
List* array = calloc(1, sizeof(List));
array->data = calloc(10, sizeof(int32_t));
array = resizeArray(array);
free(array->data);
free(array);
return 0;
}
As a teaching assistant, I've seen this mistake often. The student makes use of
a local variable and forgets to update the original pointer. The error here is
noticing that realloc
can actually move the allocated memory somewhere else
and change the pointer's location. We then leave resizeArray
without telling
array->data
where the array was moved to.
1 errors in context 1 of 1:
Invalid write of size 1
at 0x4005CA: main (main.c:10)
Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
at 0x4C2B975: calloc (vg_replace_malloc.c:711)
by 0x400593: main (main.c:5)
And the code:
#include <stdlib.h>
#include <stdint.h>
int main() {
char* alphabet = calloc(26, sizeof(char));
for(uint8_t i = 0; i < 26; i++) {
*(alphabet + i) = 'A' + i;
}
*(alphabet + 26) = '\0'; //null-terminate the string?
free(alphabet);
return 0;
}
Notice that Valgrind points us to the commented line of code above. The array
of size 26 is indexed [0,25] which is why *(alphabet + 26)
is an invalid
write—it's out of bounds. An invalid write is a common result of
off-by-one errors. Look at the left side of your assignment operation.
1 errors in context 1 of 1:
Invalid read of size 1
at 0x400602: main (main.c:9)
Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
by 0x4005E1: main (main.c:6)
And the code:
#include <stdlib.h>
#include <stdint.h>
int main() {
char* destination = calloc(27, sizeof(char));
char* source = malloc(26 * sizeof(char));
for(uint8_t i = 0; i < 27; i++) {
*(destination + i) = *(source + i); //Look at the last iteration.
}
free(destination);
free(source);
return 0;
}
Valgrind points us to the commented line above. Look at the last iteration here,
which is
*(destination + 26) = *(source + 26);
. However, *(source + 26)
is
out of bounds again, similarly to the invalid write. Invalid reads are also a
common result of off-by-one errors. Look at the right side of your assignment
operation.
How do I know when the leak is mine? How do I find my leak when I'm using someone else's code? I found a leak that isn't mine; should I do something? All are legitimate questions. First, 2 real-world examples that show 2 classes of common encounters.
#include <jansson.h>
#include <stdio.h>
int main() {
char* string = "{ \"key\": \"value\" }";
json_error_t error;
json_t* root = json_loads(string, 0, &error); //obtaining a pointer
json_t* value = json_object_get(root, "key"); //obtaining a pointer
printf("\"%s\" is the value field.\n", json_string_value(value)); //use value
json_decref(value); //Do I free this pointer?
json_decref(root); //What about this one? Does the order matter?
return 0;
}
This is a simple program: it reads a JSON string and parses it. In the making,
we use library calls to do the parsing for us. Jansson makes the necessary
allocations dynamically since JSON can contain nested structures of itself.
However, this doesn't mean we decref
or "free" the memory given to us from
every function. In fact, this code I wrote above throws both an "Invalid read"
and an "Invalid write". Those errors go away when you take out the decref
line
for value
.
Why? The variable value
is considered a "borrowed reference" in the Jansson
API. Jansson keeps track of its memory for you, and you simply have to decref
JSON structures independent of each other. The lesson here:
read the documentation. Really. It's sometimes hard to understand, but
they're telling you why these things happen. Instead, we have
existing questions about this memory error.
#include "SDL2/SDL.h"
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
SDL_Quit();
return 0;
}
What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.
That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)
How do I know when the leak is mine?
It is. (99% sure, anyway)
How do I find my leak when I'm using someone else's code?
Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.
I found a leak that isn't mine; should I do something?
Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!
Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:
if
takes a command and checks its return value. [
is just a command.
if grep -q ...
then
....
else
....
fi
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
You can use .html()
to get content of span
and or div
elements.
example:
var monthname = $(this).html();
alert(monthname);
You should check with SMTP.
That means you have to connect to that email's SMTP server.
After connecting to the SMTP server you should send these commands:
HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
If you get "<[email protected]> Relay access denied" that means this email is Invalid.
There is a simple PHP class. You can use it:
http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html
Its very simple you just add this script,
$("#mydate").datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date());
Here, setDate set today date & dateFormat define which format you want set or show.
Hope its simple script work..
Hey! I'm the developer of wxMathPlot! The project is active: I just took a long time to get a new release, because the code needed a partial rewriting to introduce new features. Take a look to the new 0.1.0 release: it is a great improvement from old versions. Anyway, it doesn't provide 3D (even if I always thinking about it...).
The following line:
string getusername = command.ExecuteScalar();
... will try to implicitly convert the result to string, like below:
string getusername = (string)command.ExecuteScalar();
The regular casting operator will fail if the object is null. Try using the as-operator, like this:
string getusername = command.ExecuteScalar() as string;
You can use html5 tag to download the image directly
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>
For more information, check this link http://www.w3schools.com/tags/att_a_download.asp
robotex tools which are free will let you do this but they make you enter the ip of the domain first:
Declare an instance of the CBetfairAPI class or make it static.
There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.
You could simply use CSS animated text generator. There are pre-created templates already
It's valid to omit them in HTML4:
7.3 The HTML element
start tag: optional, End tag: optional
7.4.1 The HEAD element
start tag: optional, End tag: optional
http://www.w3.org/TR/html401/struct/global.html
In HTML5, there are no "required" or "optional" elements exactly, as HTML5 syntax is more loosely defined. For example, title
:
The title element is a required child in most situations, but when a higher-level protocol provides title information, e.g. in the Subject line of an e-mail when HTML is used as an e-mail authoring format, the title element can be omitted.
http://www.w3.org/TR/html5/semantics.html#the-title-element-0
It's not valid to omit them in true XHTML5, though that is almost never used (versus XHTML-acting-like-HTML5).
However, from a practical standpoint you often want browsers to run in "standards mode," for predictability in rendering HTML and CSS. Providing a DOCTYPE and a more structured HTML tree will guarantee more predictable cross-browser results.
The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command)
is a modern synonym for `command`
which stands for command substitution; it means run command
and put its output here. So
echo "Today is $(date). A fine day."
will run the date
command and include its output in the argument to echo
. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).
By contrast, ${variable}
is just a disambiguation mechanism, so you can say ${var}text
when you mean the contents of the variable var
, followed by text
(as opposed to $vartext
which means the contents of the variable vartext
).
The while
loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for
loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.
A for
loop like that can be rephrased as a while
loop. The expression
for ((init; check; step)); do
body
done
is equivalent to
init
while check; do
body
step
done
It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for
loop does quite a bit more than the while
loop.
Of course, this syntax is Bash-specific; classic Bourne shell only has
for variable in token1 token2 ...; do
(Somewhat more elegantly, you could avoid the echo
in the first example as long as you are sure that your argument string doesn't contain any %
format codes:
date +'Today is %c. A fine day.'
Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)
First, try omitting the quotes from 12 and 24. Worth a shot.
Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:
<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>
Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .
Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:
With annonymous class:
houseAddress.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
lambda expression:
houseAddress.forEach(s -> System.out.println(s));
or by using method reference:
houseAddress.forEach(System.out::print);
This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.
Use xlsread, it works just as well on .csv files as it does on .xls files. Specify that you want three outputs:
[num char raw] = xlsread('your_filename.csv')
and it will give you an array containing only the numeric data (num), an array containing only the character data (char) and an array that contains all data types in the same format as the .csv layout (raw).
Here's a jQuery solution.
<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#sub1").mouseover(function() {
$("#welcome").toggle();
});
});
</script>
Using this markup:
<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>
You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.
Except for the answer by @Ed G, all of the answers require knowing which bound is the lower and which is the upper one.
Here's a (rather non-obvious) way of doing it when you don't know which bound is which.
/// <summary>
/// Method to test if a value is "between" two other values, when the relative magnitude of
/// the two other values is not known, i.e., number1 may be larger or smaller than number2.
/// The range is considered to be inclusive of the lower value and exclusive of the upper
/// value, irrespective of which parameter (number1 or number2) is the lower or upper value.
/// This implies that if number1 equals number2 then the result is always false.
///
/// This was extracted from a larger function that tests if a point is in a polygon:
/// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
/// </summary>
/// <param name="testValue">value to be tested for being "between" the other two numbers</param>
/// <param name="number1">one end of the range</param>
/// <param name="number2">the other end of the range</param>
/// <returns>true if testValue >= lower of the two numbers and less than upper of the two numbers,
/// false otherwise, incl. if number1 == number2</returns>
private static bool IsInRange(T testValue, T number1, T number2)
{
return (testValue <= number1) != (testValue <= number2);
}
Note: This is NOT a generic method; it is pseudo code. The T in the above method should be replaced by a proper type, "int" or "float" or whatever. (There are ways of making this generic, but they're sufficiently messy that it's not worth while for a one-line method, at least not in most situations.)
If aim is to create a resources folder parallel to src/main/java, then do the following:
Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish
If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:
# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>
If you use it in multiple places, clean the params in the controller:
# your_controller.rb
@params = params.slice(:sort, :per_page)
# view
<%= link_to 'Link', @params.merge(per_page: 20) %>
It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongo and specify the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.properties file using:
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>
If you have ReSharper installed clicking Shift+Alt+L will move focus to the current file in Solution Explorer.
Active Item Tracking will also need to be enabled as described in the accepted answer
Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer
I had the issue as I copied my web.config file down from prod, changed everything not prod related except the Rewrite rules which were rewriting to httpS.
Removed those rules and ran fine.
I solved it by switching tohttp
protocol from the file
protocol.
live-server [dirPath]
You can create a SqlCommand with CommandText
equal to
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)
and execute int id = (int)command.ExecuteScalar
.
This MSDN article will give you some additional techniques.
For me, in Python 3, it's working simply in this way:
keep = keep.union((0,1,2,3,4,5,6,7,8,9,10))
I don't know if it may be correct...
hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:
x[:] = [value for value in x if len(value)==2]
However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).
glglgl's answer suffers from O(n²) complexity, because list.remove
is O(n).
Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del
keywork to remove by index:
to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
del x[index]
Now del x[i]
is also O(n) because you need to copy all elements after index i
(a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove
because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.
[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress
which was introduced in python 2.7:
from itertools import compress
selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:] # trim the end of the list
Switch to AppCompatActivity and add a 25 dp paddingTop on the toolbar and turn on
<item name="android:windowTranslucentStatus">true</item>
Then, the will toolbar go up top the top
If you want to know if "1" ou 1 can be casted to a number, you can use this code :
if (isNaN(i*1)) {
console.log('i is not a number');
}
by using cat
and -A
you can see new lines as $
, tabs as ^I
cat -A myfile
Forget regular expressions. JavaScript has a builtin function for this: isNaN()
:
isNaN(123) // false
isNaN(-1.23) // false
isNaN(5-2) // false
isNaN(0) // false
isNaN("100") // false
isNaN("Hello") // true
isNaN("2005/12/12") // true
Just call it like so:
if (isNaN( $("#whatever").val() )) {
// It isn't a number
} else {
// It is a number
}
I added the following 2 parameters:
/np /nfl
So together with the 5 parameters from AndyGeek's
answer, which are /njh /njs /ndl /nc /ns
you get the following and it's silent:
ROBOCOPY [source] [target] /NFL /NDL /NJH /NJS /nc /ns /np
/NFL : No File List - don't log file names.
/NDL : No Directory List - don't log directory names.
/NJH : No Job Header.
/NJS : No Job Summary.
/NP : No Progress - don't display percentage copied.
/NS : No Size - don't log file sizes.
/NC : No Class - don't log file classes.
I had the same problem and solved by doing following.
Go to Task Manager, click on services tab, order by pid's than if you find the related process, kill it otherwise, right click and click on show details, the process should be shown now. order by pid's than kill the related process.
I try to avoid this check as much as possible.
Obviously doesn't need to be done for columns that can't hold null
.
If you're storing in a Nullable value type (int?
, etc.), you can just convert using as int?
.
If you don't need to differentiate between string.Empty
and null
, you can just call .ToString()
, since DBNull will return string.Empty
.
RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.
Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.
To fix the problem follow this -
Alternatively you can also do this with just one command.
Open terminal and fire - 1. rm ~/Library/Preferences/com.apple.iphonesimulator.plist
This will do the trick in one step! Just make sure you quit Xcode and simulator before running this.
If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...
this.router.ngOnDestroy();
window.location.href = 'http://www.cnn.com/';
that will trigger the OnDestry callback in your component that you might like.
Ohh, and also:
import { Router } from '@angular/router';
is where you find the router.
---EDIT--- Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
Basically routing to any (dummy) route to force the hook, and then navigate as requested.
Yes, you can register a listener via setOnItemSelectedListener()
, as is demonstrated here.
An ASP.NET HTTP
handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file
, the request is processed by the page via the page handler.
The ASP.NET page handler is only one type of handler. ASP.NET comes with several other built-in handlers such as the Web service handler for .asmx files
.
You can create custom HTTP handlers when you want special handling that you can identify using file name extensions in your application. For example, the following scenarios would be good uses of custom HTTP handlers:
RSS feeds To create an RSS feed for a site, you can create a handler that emits RSS-formatted XML. You can then bind the .rss extension (for example) in your application to the custom handler. When users send a request to your site that ends in .rss, ASP.NET will call your handler to process the request.
Image server If you want your Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them back to the user as the handler's response.
HTTP handlers have access to the application context, including the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest
method on the appropriate handler. The handler's ProcessRequest
method creates a response, which is sent back to the requesting browser. As with any page request, the response goes through any HTTP modules that have subscribed to events that occur after the handler has run.
Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."
By default, all parameters are optional. The most basic approach is to simply check each one for $null
, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.
If you want to learn about all of the special support that Powershell can give you, check out these links:
<div class="col-md-6">
<div class="inner">
<!-- Put the col-6 elements in the inner div -->
</div>
</div>
This by default provides some padding inside the outer div the way you seem to need. Moreover you can also modify the padding using custom CSS.
From the official docs:
interval The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.
You can either pass this value with javascript or using a data-interval="false"
attribute.
Based off of other answers I wrote my own and it doesn't use patterns or parsing with exception checking.
It checks for a maximum of one minus sign and checks for a maximum of one decimal point.
Here are some examples and their results:
"1", "-1", "-1.5" and "-1.556" return true
"1..5", "1A.5", "1.5D", "-" and "--1" return false
Note: If needed you can modify this to accept a Locale parameter and pass that into the DecimalFormatSymbols.getInstance() calls to use a specific Locale instead of the current one.
public static boolean isNumeric(final String input) {
//Check for null or blank string
if(input == null || input.isBlank()) return false;
//Retrieve the minus sign and decimal separator characters from the current Locale
final var localeMinusSign = DecimalFormatSymbols.getInstance().getMinusSign();
final var localeDecimalSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
//Check if first character is a minus sign
final var isNegative = input.charAt(0) == localeMinusSign;
//Check if string is not just a minus sign
if (isNegative && input.length() == 1) return false;
var isDecimalSeparatorFound = false;
//If the string has a minus sign ignore the first character
final var startCharIndex = isNegative ? 1 : 0;
//Check if each character is a number or a decimal separator
//and make sure string only has a maximum of one decimal separator
for (var i = startCharIndex; i < input.length(); i++) {
if(!Character.isDigit(input.charAt(i))) {
if(input.charAt(i) == localeDecimalSeparator && !isDecimalSeparatorFound) {
isDecimalSeparatorFound = true;
} else return false;
}
}
return true;
}
In my case, it was a test environment and I had to make an existing application to work without any configuration changes, and if possible without any MySQL config changes. I was able to fix the issue by following @vinnyjames suggestion and changing server timezone to UTC:
ln -sf /usr/share/zoneinfo/UTC /etc/localtime
service mysqld restart
Doing that was enough for me to solve the issue.
Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.
If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.
There are many versions of MVC, this answer is about the original MVC in Smalltalk. In brief, it is
This talk droidcon NYC 2017 - Clean app design with Architecture Components clarifies it
Use onClick
with one of the following:
window.location.reload()
, i.e.:
<button onClick="window.location.reload();">Refresh Page</button>
Or history.go(0)
, i.e.:
<button onClick="history.go(0);">Refresh Page</button>
Or window.location.href=window.location.href
for 'full' reload, i.e.:
<button onClick="window.location.href=window.location.href">Refresh Page</button>
Try this:
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
Write-Warning "$filename absent from both locations"
} else {
Write-Host " $filename File is there in one or both Locations" #if file exists there at both locations or at least in one location
}
}
You can select the form like this:
$("#submit").click(function(){
var form = $(this).parents('form:first');
...
});
However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});
To select fields inside the form, use the form context. For example:
$("input[name='somename']",form).val();
1) Since the times are dates be sure to use "Date"
class, not "POSIXct"
or "POSIXlt"
. See R News 4/1 for advice and try this where Lines
is defined in the Note at the end. No packages are used here.
dm <- read.table(text = Lines, header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)
The use of text = Lines
is just to keep the example self-contained and in reality it would be replaced with something like "myfile.dat"
. (continued after image)
2) Since this is a time series you may wish to use a time series representation giving slightly simpler code:
library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
plot(z, xaxt = "n")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)
Depending on what you want the plot to look like it may be sufficient just to use plot(Visits ~ Date, dm)
in the first case or plot(z)
in the second case suppressing the axis
command entirely. It could also be done using xyplot.zoo
library(lattice)
xyplot(z)
or autoplot.zoo:
library(ggplot2)
autoplot(z)
Note:
Lines <- "Date Visits
11/1/2010 696537
11/2/2010 718748
11/3/2010 799355
11/4/2010 805800
11/5/2010 701262
11/6/2010 531579
11/7/2010 690068
11/8/2010 756947
11/9/2010 718757
11/10/2010 701768
11/11/2010 820113
11/12/2010 645259"
For me i put this codes in public\index.php
file. and it worked just fine for all CRUD operations.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");
Pscp.exe is painfully slow.
Uploading files using WinSCP is like 10 times faster.
So, to do that from command line, first you got to add the winscp.com
file to your %PATH%. It's not a top-level domain, but an executable .com
file, which is located in your WinSCP installation directory.
Then just issue a simple command and your file will be uploaded much faster putty ever could:
WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"
And make sure your check the synchronize folders feature, which is basically what rsync
does, so you won't ever want to use pscp.exe again.
WinSCP.com /command "help synchronize"
Your append line must be in your test()
function
EDIT:
Here are two versions:
Version 1: jQuery listener
$(function(){
$('button').on('click',function(){
var r= $('<input type="button" value="new button"/>');
$("body").append(r);
});
});
Version 2: With a function (like your example)
function createInput(){
var $input = $('<input type="button" value="new button" />');
$input.appendTo($("body"));
}
Note: This one can be done with either .appendTo
or with .append
.
The standard convention in SQL Server is:
FK_ForeignKeyTable_PrimaryKeyTable
So, for example, the key between notes and tasks would be:
FK_note_task
And the key between tasks and users would be:
FK_task_user
This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:
FK_task_user
FK_note_task
FK_note_user
So you can see that tasks depend on users, and notes depend on both tasks and users.
In Swift 4, one should use merging(_:uniquingKeysWith:)
:
let dictA = ["x" : 1, "y": 2, "z": 3]
let dictB = ["x" : 11, "y": 22, "w": 0]
let resultA = dictA.merging(dictB, uniquingKeysWith: { (first, _) in first })
let resultB = dictA.merging(dictB, uniquingKeysWith: { (_, last) in last })
print(resultA) // ["x": 1, "y": 2, "z": 3, "w": 0]
print(resultB) // ["x": 11, "y": 22, "z": 3, "w": 0]
Yes, in principe it is possible, but it doesn't come for free.
You need to create a StackTrace, and then you can have a look at the StackFrame's of the call stack.
if you could set the height of the wrapping div of the content (#header-content as shown in other's reply), instead of the entire #header, maybe you can also try this approach:
HTML
<div id="header">
<h1>some title</h1>
<div id="header-content">
<span>
first line of header text<br>
second line of header text<br>
third, last line of header text
</span>
</div>
</div>
CSS
#header-content{
height:100px;
}
#header-content::before{
display:inline-block;
content:'';
height:100%;
vertical-align:bottom;
}
#header-content span{
display:inline-block;
}
Great and exhaustive answerby @Kev!
Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location>
tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.
Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut
is in minutes, while the request executionTimeout
is in seconds!
And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).
<configuration>
...
<compilation debug="false" ...>
... other stuff ..
<location path="~/Admin/SomePage.aspx">
<system.web>
<sessionState timeout="240" />
<httpRuntime executionTimeout="14400" />
</system.web>
</location>
...
</configuration>
I'm a big fan of using EPPlus to perform these types of actions. EPPlus is a library you can reference in your project and easily create/modify spreadsheets on a server. I use it for any project that requires an export function.
Here's a nice blog entry that shows how to use the library, though the library itself should come with some samples that explain how to use it.
Third party libraries are a lot easier to use than Microsoft COM objects, in my opinion. I would suggest giving it a try.
keep it simple
<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>
I had an issue on AWS with mariadb - This is how I solved the STRICT_TRANS_TABLES issue
SSH into server and chanege to the ect directory
[ec2-user]$ cd /etc
Make a back up of my.cnf
[ec2-user etc]$ sudo cp -a my.cnf{,.strict.bak}
I use nano to edit but there are others
[ec2-user etc]$ sudo nano my.cnf
Add this line in the the my.cnf file
#
#This removes STRICT_TRANS_TABLES
#
sql_mode=""
Then exit and save
OR if sql_mode is there something like this:
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
Change to
sql_mode=""
exit and save
then restart the database
[ec2-user etc]$ sudo systemctl restart mariadb
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
creates a title less dialog
Git has changed some of its repo instructions - check that you have connected your local repo to the Git cloud - check each of these steps to see if you have missed any.
Git documentation[https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/connecting-to-github-with-ssh] if you prefer following documentation - it is far more detailed and worth reading to understand why the steps below have been summarised.
My Git Checklist:-
$rm -rf .git
which recursively removes gitwhich git
it should say /usr/local/bin/git
- if you are install git with Homebrew $brew install git
$git config --global user.name "Your Name"
$git config --global user.email "[email protected]"
$git config --global core.ignorecase false
If you have made a mistake you can update the file $ls -a
to locate file then $open .gitignore
and edit it, save and close.
ssh-keygen -t rsa -C "[email protected]"
SAVE THE KEYssh-add ~/.ssh/id_rsa
You can also find it by clicking your profile image and the edit key under it in the left nav.
Copy your key to the clipboard with the terminal command:
pbcopy < ~/.ssh/id_rsa.pub
In the Title field put something that identifies your machine, like YOUR_NAME's MacBook Air
In the Key field just hit cmd + V to paste the key that you created earlier - do not add or remove and characters or whitespace to the key
Click Add key and check everything works in the terminal by typing:
ssh -T [email protected]
You should see the following message:
Hi YOUR_NAME! You've successfully authenticated, but GitHub does not provide shell access.
Now that your local machine is connected to the cloud you can create a repo online or on your local machine. Git has changed the name master for a branch main. When linking repos it is easier to use the HTTPS key rather than the SSH key. While you need the SSH to link the repos initially to avoid the error in the question.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Follow the steps you now get on your repo - GitHub has added an additional step to create a branch (time of writing Oct 2020).
to create a new repository on the command line echo "# testing-with-jest" >> README.md git init git add README.md git commit -m "first commit" git branch -M main git remote add origin — (use HTTPS url not SSH) git push -u origin main
to push an existing repository from the command line git remote add origin (use HTTPS url not SSH) git branch -M main git push -u origin main
If you get it wrong you can always start all over by removing the initialisation from the git folder in your local machine $rm -rf .git
and start afresh - but it is useful to check first that none of the steps above are missed and always the best source of truth is the documentation - even if it takes longer to read and understand!
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
...
// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
client = new DefaultHttpClient(httpParams);
if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.
There's more to it than this, but you're probably looking for this list:
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
H hourly frequency
T minutely frequency
S secondly frequency
L milliseconds
U microseconds
Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
My team was hitting a situation with multiple databases on one server, depending on which database you connected to, the ROLE in question was not returned by SELECT * FROM pg_catalog.pg_user
, as proposed by @erwin-brandstetter and @a_horse_with_no_name. The conditional block executed, and we hit role "my_user" already exists
.
Unfortunately we aren't sure of exact conditions, but this solution works around the problem:
DO
$body$
BEGIN
CREATE ROLE my_user LOGIN PASSWORD 'my_password';
EXCEPTION WHEN others THEN
RAISE NOTICE 'my_user role exists, not re-creating';
END
$body$
It could probably be made more specific to rule out other exceptions.
For any Xamarin.iOS or Xamarin.Forms developers, additionally you will want to check the .csproj file (for the iOS project) and ensure that it contains references to the PNG's and not just the Asset Catalog i.e.
<ItemGroup>
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Contents.json" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-83.5%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad%402x.png" />
</ItemGroup>
(SELECT CASE WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE WHEN ISNULL(ChequeNo,0) IS NOT NULL THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE AND (Month= 1) AND (Year = 2020) AND )END AS Stat)
The DateTime class takes a string in the constructor. If you prefix the timestamp with a @-character you create a DateTime object with the timestamp. For formating use the 'c' format ... a predefined ISO 8601 compound format.
If could use the DateTime class like this ... set the right timezone or leave it out if you want a UTC time.
$dt = new DateTime('@1333699439');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('c');
In your PhP file there's going to be a variable called $_REQUEST
and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST);
and check if you're receiving the values.
Your Code is Fine just you need to place it inside the ready function.
$(document).ready( function() {
$("#cpa-form").submit(function(e){
e.preventDefault();
});
}
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Well to obtain all different values in a Dataframe
you can use distinct. As you can see in the documentation that method returns another DataFrame
. After that you can create a UDF
in order to transform each record.
For example:
val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")
// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct
// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)
// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))
I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t
<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>
Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.
7 years later and this code has helped me. However, my times still were not showing up correctly.
Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
I changed the format to (%H:%M) and the time displayed correctly.
All thanks to the community.
git add -A
git diff HEAD
Generate patch if required, and then:
git reset HEAD
The difference is subtle.
In JavaScript an undefined
variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a;
for instance, then a
will be undefined
, because it was never assigned any value.
But if you then assign a = null;
then a
will now be null
. In JavaScript null
is an object (try typeof null
in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined
is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional
parameter doSomething(1, 2) then
optional will be the "three"
string but if you pass doSomething(1, 2, null)
then optional will be null
.
As for the equal ==
and strictly equal ===
comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0"
will return true; while 0 === "0"
will return false, because a number is not a string.
You may use those operators to check between undefined
an null
. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:
public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
@Override
protected boolean hasError(HttpStatus statusCode)
{
if(statusCode == HttpStatus.BAD_REQUEST)
{
return false;
}
return statusCode.isError();
}
}
And you need to set this handler for restemplate bean:
@Bean
protected RestTemplate restTemplate(RestTemplateBuilder builder)
{
return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
}
$("body").on("custom-scroll", ".myDiv", function(){
console.log("Scrolled :P");
})
$("#btn").on("click", function(){
$("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
listenForScrollEvent($(".myDiv"));
});
function listenForScrollEvent(el){
el.on("scroll", function(){
el.trigger("custom-scroll");
})
}
see this post - Bind scroll Event To Dynamic DIV?
How about this?
select DATEPART(MM,'january 01 2011') -- returns 1
select DATEPART(MM,'march 01 2011') -- returns 3
select DATEPART(MM,'august 01 2011') -- returns 8
Suppose I create a new file, newFile.txt
:
Suppose I add the file accidentally, git add newFile.txt
:
Now I want to undo this add, before commit, git reset newFile.txt
:
Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()