I Thing you can Try this Code, It's Run for my Case:
<?php_x000D_
_x000D_
$con = mysqli_connect('localhost', 'root', 'NOTSHOWN', 'test');_x000D_
_x000D_
$filename = 'dbbackupmember.sql';_x000D_
$handle = fopen($filename, 'r+');_x000D_
$contents = fread($handle, filesize($filename));_x000D_
_x000D_
$sql = explode(";", $contents);_x000D_
foreach ($sql as $query) {_x000D_
$result = mysqli_query($con, $query);_x000D_
if ($result) {_x000D_
echo "<tr><td><br></td></tr>";_x000D_
echo "<tr><td>".$query."</td></tr>";_x000D_
echo "<tr><td><br></td></tr>";_x000D_
}_x000D_
}_x000D_
_x000D_
fclose($handle);_x000D_
echo "success";_x000D_
_x000D_
_x000D_
?>
_x000D_
Another option is to use the csvsql command from the csvkit library.
Example usage directly on command line:
csvsql --db mysql:///test --tables yourtable --insert yourfile.csv
This can be executed directly on the command line, or built into a python or shell script for automation if you need to do this for a number of files.
csvsql allows you to create database tables on the fly based on the structure of your csv, so it is a lite-code way of getting the first row of your csv to automagically be cast as the MySQL table header.
Full documentation and further examples here: https://csvkit.readthedocs.io/en/1.0.3/scripts/csvsql.html
Typically for a use case which involves a sequence of pages and in the final stage or page we post the data to the server. In this scenario we need to maintain the state. In the below snippet we maintain the state on the client side
As mentioned in the above post. The session is created using the factory recipe.
Client side session can be maintained using the value provider recipe as well.
Please refer to my post for the complete details. session-tracking-in-angularjs
Let's take an example of a shopping cart which we need to maintain across various pages / angularjs controller.
In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.
Here we create the custom injectable service having a cart inside using the "value provider recipe".
'use strict';
function Cart() {
return {
'cartId': '',
'cartItem': []
};
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart
app.value('sessionService', {
cart: new Cart(),
clear: function () {
this.cart = new Cart();
// mechanism to create the cart id
this.cart.cartId = 1;
},
save: function (session) {
this.cart = session.cart;
},
updateCart: function (productId, productQty) {
this.cart.cartItem.push({
'productId': productId,
'productQty': productQty
});
},
//deleteItem and other cart operations function goes here...
});
the data object is a buffer of bytes. Simply call .toString()
to get human-readable code:
console.log( data.toString() );
reference: Node.js buffers
You can and should never assume that $_SERVER['HTTP_REFERER']
will be present.
If you control the previous page, you can pass the URL as a parameter "site.com/page2.php?prevUrl=".urlencode("site.com/page1.php")
.
If you don't control the page, then there is nothing you can do.
"Performance and speed"? Aren't those kind of ... synonyms, here?
Anyway, the recv()
call takes flags that read()
doesn't, which makes it more powerful, or at least more convenient. That is one difference. I don't think there is a significant performance difference, but haven't tested for it.
Try the following code with an added request property:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class SocketConnection
{
public static String getURLSource(String url) throws IOException
{
URL urlObject = new URL(url);
URLConnection urlConnection = urlObject.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
return toString(urlConnection.getInputStream());
}
private static String toString(InputStream inputStream) throws IOException
{
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
{
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
}
return stringBuilder.toString();
}
}
}
The following creates a generic function, taking an array of any size and of any type by reference:
template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
// do stuff
}
Keep 2 stacks, let's call them inbox
and outbox
.
Enqueue:
inbox
Dequeue:
If outbox
is empty, refill it by popping each element from inbox
and pushing it onto outbox
Pop and return the top element from outbox
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.
Here's an implementation in Java:
public class Queue<E>
{
private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();
public void queue(E item) {
inbox.push(item);
}
public E dequeue() {
if (outbox.isEmpty()) {
while (!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}
}
I think what you want is:
abstract class Component {
public deps: any = {};
public props: any = {};
public makePropSetter<T>(prop: string): (val: T) => T {
return function(val) {
this.props[prop] = val
return val
}
}
}
class Post extends Component {
public toggleBody: (val: boolean) => boolean;
constructor () {
super()
this.toggleBody = this.makePropSetter<boolean>('showFullBody')
}
showMore (): boolean {
return this.toggleBody(true)
}
showLess (): boolean {
return this.toggleBody(false)
}
}
The important change is in setProp
(i.e., makePropSetter
in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.
The <T>
on makePropSetter
allows you to lock that function in to a specific type. The <boolean>
in the subclass's constructor is actually optional. Since you're assigning to toggleBody
, and that already has the type fully specified, the TS compiler will be able to work it out on its own.
Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody
respect that same signature.
I have done some work on a pretty complete port of the Django template language for Simon Willisons djangode project (Utilities functions for node.js that borrow some useful concepts from Django).
See the documentation here.
Hi this is due to new version of the jQuery => 1.9.0
you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/
jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js
replace :
<script src="http://code.jquery.com/jquery-latest.js"></script>
by :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>
in your page and its working.
It is a string formatting syntax (which it borrows from C).
Please see "PyFormat":
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the
%s
placeholder.
Edit: Here is a really simple example:
#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python3+
name = input("who are you? ")
print("hello %s" % (name,))
The %s
token allows me to insert (and potentially format) a string. Notice that the %s
token is replaced by whatever I pass to the string after the %
symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
Here is a general SQL query syntax to join three or more table. This SQL query should work in all major relation database e.g. MySQL, Oracle, Microsoft SQLServer, Sybase and PostgreSQL :
SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey = table2.foreignkey
join table3 ON table2.primarykey = table3.foreignkey
We first join table 1 and table 2 which produce a temporary table with combined data from table1 and table2, which is then joined to table3. This formula can be extended for more than 3 tables to N tables, You just need to make sure that SQL query should have N-1 join statement in order to join N tables. like for joining two tables we require 1 join statement and for joining 3 tables we need 2 join statement.
% echo -e '\u2620' # \u takes four hexadecimal digits
?
% echo -e '\U0001f602' # \U takes eight hexadecimal digits
This works in Zsh (I've checked version 4.3) and in Bash 4.2 or newer.
Start with npm root
-- it will show you the root folder for NPM packages for the current user.
Add -g
and you get a global folder. Don't forget to substract node_modules
.
Use npm config
/ npm config -g
and check that it'd create you a new .npmrc
/ npmrc
file for you.
Tested on Windows 10 Pro, NPM v.6.4.1:
C:\Users\%username%\AppData\Roaming\npm\etc\npmrc
C:\Users\%username%\.npmrc
C:\Program Files\nodejs\node_modules\npm\npmrc
References:
Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.
<select multiple='multiple' id='selectListName'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
In some function called based on some event, the following code would clear all selected options.
$("#selectListName").prop('selectedIndex', -1);
This is a slight modification from a previous solution. My example looks for stderr redirection in bash scripts:
grep '2>' $(find . -name "*.bash")
Solution included in the EditText action listenner:
public void onCreate(Bundle savedInstanceState) {
...
...
edittext = (EditText) findViewById(R.id.EditText01);
edittext.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(edittext.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
...
...
}
As of now (studio 0.61) maintaining proper project structure is enough. No need to create separate test project as in eclipse (see below).
This is a quite old post, but if you use Apache HTTPD, you can limit the DH size. See http://httpd.apache.org/docs/current/ssl/ssl_faq.html#javadh
Have you tried explicitly declaring the version of mail.jar you want? Maven's dependency resolution should use this for dependency resolution over all other versions.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>jruby</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<artifactId>base</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>VERSION-#</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>ALL-DEPS</artifactId>
<version>1.0</version>
<scope>provided</scope>
<type>pom</type>
</dependency>
</dependencies>
</project>
function sortFunc(a, b) {
var sortingArr = ["A", "B", "C"];
return sortingArr.indexOf(a.type) - sortingArr.indexOf(b.type);
}
const itemsArray = [
{
type: "A",
},
{
type: "C",
},
{
type: "B",
},
];
console.log(itemsArray);
itemsArray.sort(sortFunc);
console.log(itemsArray);
_x000D_
/* Assuming this is a while loop -> e.g. video stream where img is obtained from say web camera.*/
cvShowImage("Window",img);
/* A small interval of 10 milliseconds. This may be necessary to display the image correctly */
cvWaitKey(10);
/* to wait until user feeds keyboard input replace with cvWaitKey(0); */
Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs)
Here are a couple examples that use define which cannot be replaced by a variable:
#define min(i, j) (((i) < (j)) ? (i) : (j))
note this is evaluated by the pre-processor, not during runtime
It's been a few good days with node, and you're right to say that you can't create a webserver without gzip.
There are quite a lot options given on the modules page on the Node.js Wiki. I tried out most of them, but this is the one which I'm finally using -
https://github.com/donnerjack13589/node.gzip
v1.0 is also out and it has been quite stable so far.
You can use the excecl command
int execl(const char *path, const char *arg, ...);
Like shown here
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
int main (void) {
return execl ("/bin/pwd", "pwd", NULL);
}
The second argument will be the name of the process as it will appear in the process table.
Alternatively, you can use the getcwd() function to get the current working directory:
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255
int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';
if(getcwd(wd, MAX-1) == NULL) {
printf ("Can not get current working directory\n");
}
else {
printf("%s\n", wd);
}
return 0;
}
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
To quote from man rand :
The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
So, with no seed value, rand()
assumes the seed as 1 (every time in your case) and with the same seed value, rand()
will produce the same sequence of numbers.
The easiest and fastest way would be with phpmyadmin structure table.
There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.
Couldn't comment so writing answer here. This is the clearest one-line I have seen:
import os
[os.path.join(path, name) for path, subdirs, files in os.walk(root) for name in files]
And if you want to vary the speed and include callbacks simply add them like this :
jQuery.fn.extend({
slideRightShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, speed, callback);
});
},
slideRightHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, speed, callback);
});
}
});
You can try this script, that converts all of your databases and tables to utf8.
Just for the sake of completeness, appending values to a vector in a for loop is not really the philosophy in R. R works better by operating on vectors as a whole, as @BrodieG pointed out. See if your code can't be rewritten as:
ouput <- sapply(values, function(v) return(2*v))
Output will be a vector of return values. You can also use lapply
if values is a list instead of a vector.
Create a macro and use the following code to grab the data and put it in a new sheet (Sheet2):
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1
For i = 1 To 700 Step 7
strCellNum = "A" & i
strValue = Worksheets("Sheet1").Range(strCellNum).Value
Debug.Print strValue
Worksheets("Sheet2").Range("A" & x).Value = strValue
x = x + 1
Next
Let me know if this helps! JFV
Very easy from My side:-
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").click(function() {
$('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="testdiv"></div>
<input type="button" value="Add" />
</body>
</html>
The main issue is that the inner query cannot be related to your where
clause on the outer update
statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.
Update
Competition as C
inner join (
select CompetitionId, count(*) as NumberOfTeams
from PicksPoints as p
where UserCompetitionID is not NULL
group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams
Python is not purely lexically scoped.
See this: Using global variables in a function
and this: https://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/
The maximum name size is 30 characters because of the data dictionary which allows the storage only for 30 bytes
I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
you can use PATTERN:
<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
<div *ngIf="name.errors?.pattern">Is not a number</div>
</div>
Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.
export default function useGoogleMapMarker(props) {
const [marker, setMarker] = useState();
useEffect(() => {
// ...code
const marker = new maps.Marker({ position, map, title, icon });
// ...code
setMarker(marker);
return () => marker.setMap(null); // to remove markers when unmounts
}, []);
return marker;
}
Once you have your PropertyInfo
(from GetProperty
), you need to call GetValue
and pass in the instance that you want to get the value from. In your case:
d.GetType().GetProperty("value2").GetValue(d, null);
As of SciPy version 0.17.0, there is a new option for scipy.interpolate.interp1d that allows extrapolation. Simply set fill_value='extrapolate' in the call. Modifying your code in this way gives:
import numpy as np
from scipy import interpolate
x = np.arange(0,10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y, fill_value='extrapolate')
print f(9)
print f(11)
and the output is:
0.0497870683679
0.010394302658
You will notice a big change when selecting options if you type in "java -version" after doing so. So if you run update-alternatives --config java
and select option 3
, you will be using the Sun implementation.
Also, with regards to auto
vs manual mode
, making a selection should take it out of auto mode
per this page stating:
When using the
--config
option, alternatives will list all of the choices for the link group of which given name is the master link. You will then be prompted for which of the choices to use for the link group. Once you make a change, the link group will no longer be inauto mode
. You will need to use the--auto
option in order to return to the automatic state.
And I believe auto mode
is set when you install the first/only JRE/JDK.
The command pg_lsclusters
(at least under Linux / Ubuntu) can be used to list the existing clusters and with it also the data directory:
Ver Cluster Port Status Owner Data directory Log file
9.5 main 5433 down postgres /var/lib/postgresql/9.5/main /var/log/postgresql/postgresql-9.5-main.log
10 main 5432 down postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log
Dictionary.Add(key, value)
and Dictionary[key] = value
have different purposes:
Add
method to add new key/value pair, existing keys will not be replaced (an ArgumentException
is thrown).just this as img tag is a content element
img {
content:url(http://example.com/image.png);
}
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}
Or add this part
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
after the HTML, like:
<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</html>
Try this:
select distinct a.FirstName, a.LastName, v.District
from AddTbl a
inner join ValTbl v
on a.LastName = v.LastName
order by a.FirstName;
Or this (it does the same, but the syntax is different):
select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;
Linq With Or Condition by using Lambda expression you can do as below
DataTable dtEmp = new DataTable();
dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));
dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);
var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
== 1 || emp.Field<int>("EmpID") == 2);
foreach (DataRow row in res2)
{
Label2.Text += "Emplyee ID: " + row[0] + " & Emplyee Name: " + row[1] + ", ";
}
Here is a variation of @SiegeX's answer which works with traditional Bourne shell (which has no support for +=
assignments).
password=''
while IFS= read -r -s -n1 pass; do
if [ -z "$pass" ]; then
echo
break
else
printf '*'
password="$password$pass"
fi
done
fork()
- creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).vfork()
- creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork()
, child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()
! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec()
(create a new virtual address space and a transition to a different stack) or _exit()
(termination of the process execution). vfork()
is the optimization of fork()
for "fork-and-exec" model. It can be performed 4-5 times faster than the fork()
, because unlike the fork()
(even with COW kept in the mind), implementation of vfork()
system call does not include the creation of a new address space (the allocation and setting up of new page directories).clone()
- creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone()
system call is the base which is used for the implementation of pthread_create()
and all the family of the fork()
system calls.exec()
- resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork()
system call together form a classical UNIX process management model called "fork-and-exec".First uninstall all java software like JRE 7 or JRE 6 or JDK ,then open the following path :
START > CONTROL PANEL > ADVANCED SETTING > ENVIRONMENT VARIABLE > SYSTEM VARIABLE > PATH
Then click on Edit button and paste the following text to Variable_Value and click OK.
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\
Now go to this url http://java.com/en/download/manual.jsp and click on Windows Offline and click on run and start again eclipse.
Enjoy it!
return Deal::with(["redeem" => function($q){
$q->where('user_id', '=', 1);
}])->get();
this worked for me
extends LinearLayoutManager and catch this error
public class NoCrashLinearLayoutManager extends LinearLayoutManager {
public NoCrashLinearLayoutManager(Context context) {
super(context);
}
public NoCrashLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public NoCrashLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't waste your time, use this one line command to run command line as administrator:
echo createobject("shell.application").shellexecute "cmd.exe",,,"runas",1 > runas.vbs & start /wait runas.vbs & del /f runas.vbs
if you want to start any application with administrator privilege you will just write the hole path for this application like this notepad++ in my program files for example :
echo createobject("shell.application").shellexecute "%programfiles%\Notepad++\notepad++.exe",,,"runas",1 > runas.vbs & start /wait runas.vbs
I just had this problem and none of the suggested solutions worked for me. After a lot of googling, I did find a solution. This is what worked for me.
First, I had to run this command to start the server and I am guessing set the location of config file.
pg_ctl -D /usr/local/var/postgres start && brew services start postgresql
Then I ran this command to access postgres
psql postgres
And at the postgres prompt then I typed "\du" to list the roles
postgres=# \du
The postgres role was missing so I had to create it with this command
CREATE ROLE POSTGRES WITH SUPERUSER CREATEDB CREATEUSER CREATEROLE REPLICATION BYPASSRLS ;
That solved my problem and I hope this helps someone else.
Your first option is the good one. It's the least problematic one and you've already found the correct reasons why you couldn't use the other options.
By the way, your heading IS explicitly associated with the <ul>
: it's right before the list! ;)
edit: Steve Faulkner, one of the editors of W3C HTML5 and 5.1 has sketched out a definition of an lt
element. That's an unofficial draft that he'll discuss for HTML 5.2, nothing more yet.
Most likely, you want
SELECT username
FROM dba_users
That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case
SELECT username
FROM dba_users u
WHERE EXISTS (
SELECT 1
FROM dba_objects o
WHERE o.owner = u.username )
Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace
, i.e.
SELECT username
FROM dba_users
WHERE default_tablespace not in ('SYSTEM','SYSAUX')
or
SELECT username
FROM dba_users u
WHERE EXISTS (
SELECT 1
FROM dba_objects o
WHERE o.owner = u.username )
AND default_tablespace not in ('SYSTEM','SYSAUX')
It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace
of SYSTEM
, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.
malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL)
, you can do arithmetic within the brackets of malloc
but you shouldnt because you should use calloc
which has the definition of void calloc(count, size)
which means how many items you want to store ie count and size of data ie int
, char
etc.
This might help you. - from Narayana Vyas. It searches all columns of all tables in a given database. I have used it before and it works.
This is the Stored Proc from the above link - the only change I made was substituting the temp table for a table variable so you don't have to remember to drop it each time.
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @Results
END
Since the glyphicons image is a sprite, you really can't do that: fundamentally what you want is to limit the size of the background, but there's no way to specify how big the background is. Either you cut out the icon you want, size it down and use it, or use something like the input field prepend/append option (http://twitter.github.io/bootstrap/base-css.html#forms and then search for prepended inputs).
I don't know why Charles Bretana deleted his answer, so I'm adding it back in as a CW answer, but a persisted computed column is a REALLY good way to handle these cases where you need cleansed or transformed data almost all the time, but need to preserve the original garbage. His suggestion is relevant and appropriate REGARDLESS of how you decide to cleanse your data.
Specifically, in my current project, I have a persisted computed column which trims all the leading zeros (luckily this is realtively easily handled in straight T-SQL) from some particular numeric identifiers stored inconsistently with leading zeros. This is stored in persisted computed columns in the tables which need it and indexed because that conformed identifier is often used in joins.
This error is shown when your XCode is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.
We can solve this issue by following the below steps:-
If everything worked properly, your XCode has a new developer disk image. Close the finder now, and quit your XCode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.
Thanks
Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.
You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).
To make a POST request, you need to create a <form>
. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.
The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:
set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024
More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:
I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.
Queue
is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this isn't what you want to do for a collection. Instead, choose an existing implementation. For example:
Queue<Integer> q = new LinkedList<Integer>();
or
Queue<Integer> q = new ArrayDeque<Integer>();
Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.
No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do.
If you really want to deep copy:
cloneDeep
method.However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function.
Specify that all callbacks passed to mapCopy
must return new objects instead of mutating the existing object. For example:
mapCopy(state, e => {
if (e.id === action.id) {
return Object.assign({}, e, {
title: 'new item'
});
} else {
return e;
}
});
This makes use of Object.assign
to create a new object, sets properties of e
on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary.
mapCopy
can be really simple now:
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
output[key] = callback.call(this, object[key]);
return output;
}, {});
}
Essentially, mapCopy
is trusting its callers to do the right thing. This is why I said this assumes you control all call sites.
This is tested and easy to understand.
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x84:
base.WndProc(ref m);
if((int)m.Result == 0x1)
m.Result = (IntPtr)0x2;
return;
}
base.WndProc(ref m);
}
Since some of the other answers include info on rebuilding, and my use case also required a rebuild, I had a better solution (compared to those).
There's still a way to easily target just the one single worker
container that both rebuilds + restarts it in a single line, albeit it's not actually a single command. The best solution for me was simply rebuild and restart:
docker-compose build worker && docker-compose restart worker
This accomplishes both major goals at once for me:
worker
containerHope this helps anyone else getting here.
You can add "download" attribute inside your tag to download files.
<a href="/project/download" download> Download Document </a>
I often test for truthy value and also for empty spaces in the string:
if(!(!data || data.trim().length === 0)) {
// do something here
}
If you have a string consisting of one or more empty spaces it will evaluate to true.
Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like
div#left {
width: 600px;
float: left;
}
div#right {
width: 240px;
float: right;
}
div.clear {
clear:both;
}
place a the clear div under left and right container.
Alternative solution on Windows is to install python-certifi-win32 that will allow Python to use Windows Certificate Store.
pip install python-certifi-win32
Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.
One more that's not on his list:
[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816
But if all you want to do is subtract, why bother changing the input to base 10?
[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$
The dc
command is "desk calc". It will also take input from stdin, like bc
, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.
In the commands above we've got the following:
16i
-- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.BFCA3000
-- your initial number17FF
-- a random hex number I picked to subtract from your initial number-
-- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stackp
-- print the last item on the stack. This doesn't change the stack, so...10o
-- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".p
-- print the last item on the stack again ... this time in hex.You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.
Here is my experience:-
(Does not require any third-party library)
In this particular case the clearest solution is the S.Lott answer
But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.
Using De Morgan's law ¬(A^B) = ¬Av¬B
not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step
then
if u0 > u or u >= u0+step:
pass
... in this case the «clear» solution is not more clear :P
As defined in JLS for-each loop can have two forms:
If the type of Expression is a subtype of Iterable
then translation is as:
List<String> someList = new ArrayList<String>();
someList.add("Apple");
someList.add("Ball");
for (String item : someList) {
System.out.println(item);
}
// IS TRANSLATED TO:
for(Iterator<String> stringIterator = someList.iterator(); stringIterator.hasNext(); ) {
String item = stringIterator.next();
System.out.println(item);
}
If the Expression necessarily has an array type T[]
then:
String[] someArray = new String[2];
someArray[0] = "Apple";
someArray[1] = "Ball";
for(String item2 : someArray) {
System.out.println(item2);
}
// IS TRANSLATED TO:
for (int i = 0; i < someArray.length; i++) {
String item2 = someArray[i];
System.out.println(item2);
}
Java 8 has introduced streams which perform generally better. We can use them as:
someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);
Just add disabled as a class on your anchor:
<a class="dropdown-toggle disabled" href="http://google.com">
Dropdown <b class="caret"></b></a>
So all together something like:
<ul class="nav">
<li class="dropdown">
<a class="dropdown-toggle disabled" href="http://google.com">
Dropdown <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
</ul>
You can refer to https://curl.haxx.se/docs/http-cookies.html for a complete tutorial of how to work with cookies. You can use
curl -c /path/to/cookiefile http://yourhost/
to write to a cookie file and start engine and to use cookie you can use
curl -b /path/to/cookiefile http://yourhost/
to read cookies from and start the cookie engine, or if it isn't a file it will pass on the given string.
Based on a comment in another answer, here's my shell function.
# mvp = move + create parents
function mvp () {
source="$1"
target="$2"
target_dir="$(dirname "$target")"
mkdir --parents $target_dir; mv $source $target
}
Include this in .bashrc or similar so you can use it everywhere.
Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:
data.busNum = 12345;
...
Lets assume you created a Ubuntu VM on your local machine. It's IP address is 192.168.1.104.
You login into VM, and installed Kubernetes. Then you created a pod where nginx image running on it.
1- If you want to access this nginx pod inside your VM, you will create a ClusterIP bound to that pod for example:
$ kubectl expose deployment nginxapp --name=nginxclusterip --port=80 --target-port=8080
Then on your browser you can type ip address of nginxclusterip with port 80, like:
2- If you want to access this nginx pod from your host machine, you will need to expose your deployment with NodePort. For example:
$ kubectl expose deployment nginxapp --name=nginxnodeport --port=80 --target-port=8080 --type=NodePort
Now from your host machine you can access to nginx like:
In my dashboard they appear as:
Below is a diagram shows basic relationship.
For those who do not see Plugins->NPPExport,
Download Plugin Manager from this. Extract contents and place under C/ProgramFile/NP++ installation, plugins & updater folder. Restart NP++. You should be able to see Plugins->Plugin Manager then. You can download any plugin, including NPPExport and install it to see the Copy command.
There is also a new option now in http://vimr.org/, which looks quite promising.
There is also an AngularJS module called angular-gestures which is based on hammer.js: https://github.com/wzr1337/angular-gestures
md-icons aren't in the bower release of angular-material yet. I've been using Polymer's icons, they'll probably be the same anyway.
bower install polymer/core-icons
I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)
.grad {
background-color: #F07575; /* fallback color if gradients are not supported */
background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}
from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch
instead of []
. For fetch
not to throw an exception when the key is not found, pass it a default value.
puts "ok" if hash.fetch('key', nil) == 'X'
Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .
If you can't start Wamp anymore right after a Windows update, this is often caused because of Windows that has automatically re-turned on the World Wide Web Publishing Service.
To solve: Click on Start, type Services, click Services, find World Wide Web Publishing Service, double click it, set Startup type to Disabled and click Stop button, OK this dialog and try to restart Wamp.
you need to enable the Show Assistant Editor:
You will not able to test the app using the Google-Play-Service library
in emulator. In order to test that app in emulator you need to install some system framework in your emulator to make it work.
https://stackoverflow.com/a/11213598/1405008
Refer the above answer to install Google play service on your emulator.
You can use
str1.compareTo(str2);
If str1 is lexicographically less than str2, a negative number
will be returned, 0
if equal or a positive number
if str1 is greater.
E.g.,
"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns 0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException
Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
Since API 22 getResources().getDrawable()
is deprecated, so we can use following solution.
Drawable vectorDrawable = VectorDrawableCompat.create(getResources(), R.drawable.logo, getContext().getTheme());
Bitmap myLogo = ((BitmapDrawable) vectorDrawable).getBitmap();
If the output from ReflectionToStringBuilder.toString()
is not enough readable for you, here is code that:
1) sorts field names alphabetically
2) flags non-null fields with asterisks in the beginning of the line
public static Collection<Field> getAllFields(Class<?> type) {
TreeSet<Field> fields = new TreeSet<Field>(
new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
int res = o1.getName().compareTo(o2.getName());
if (0 != res) {
return res;
}
res = o1.getDeclaringClass().getSimpleName().compareTo(o2.getDeclaringClass().getSimpleName());
if (0 != res) {
return res;
}
res = o1.getDeclaringClass().getName().compareTo(o2.getDeclaringClass().getName());
return res;
}
});
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
fields.addAll(Arrays.asList(c.getDeclaredFields()));
}
return fields;
}
public static void printAllFields(Object obj) {
for (Field field : getAllFields(obj.getClass())) {
field.setAccessible(true);
String name = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
System.out.printf("%s %s.%s = %s;\n", value==null?" ":"*", field.getDeclaringClass().getSimpleName(), name, value);
}
}
test harness:
public static void main(String[] args) {
A a = new A();
a.x = 1;
B b = new B();
b.x=10;
b.y=20;
System.out.println("=======");
printAllFields(a);
System.out.println("=======");
printAllFields(b);
System.out.println("=======");
}
class A {
int x;
String z = "z";
Integer b;
}
class B extends A {
int y;
private double z = 12345.6;
public int a = 55;
}
I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.
We can check this with ls -l /var/lib/mysql
command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod
commands.
After these changes, restart the mysqld daemon and login with root with command:
mysql -u root
Then change passwords or create other users for logging into mysql.
HTH
I tried everything on here and finally discovered that it was the setup in my web.config. I removed that section and it worked fine; I will go back and troubleshoot later as to why it was busted.
*Edit: I removed the statusCode="503" because of an issue with the App_Offline.htm file and the way in which the errors were configured. I've removed the line below (it isn't needed locally), and everything is working perfectly.
<remove statusCode="503"/>
I encountered an issue like this using the Maven Release Plugin. Resolving using relative paths (i.e. for the parent pom in the child module ../parent/pom.xml) did not seem to work in this scenario, it keeps looking for the released parent pom in the Nexus repository. Moving the parent pom to the parent folder of the module resolved this.
Double is a wrapper class,
The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.
The double data type,
The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
Check each datatype with their ranges : Java's Primitive Data Types.
Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double
IsNullOrEmpty
is essentially shorthand for the following:
return str == null || str == String.Empty;
So, no there is no function that just checks for nulls because it would be too simple. obj != null
is the correct way. But you can create such a (superfluous) function yourself using the following extension:
public bool IsNull(this object obj)
{
return obj == null;
}
Then you are able to run anyObject.IsNull()
.
To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace
function since it is not a mutator function:
myString = myString.replace('username1','');
You can convert the current time like this
t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'
To convert a date in string to different formats.
import datetime,time
def createDateObject(str_date,strFormat="%Y-%m-%d"):
timeStamp = time.mktime(time.strptime(str_date,strFormat))
return datetime.datetime.fromtimestamp(timeStamp)
def FormatDate(objectDate,strFormat="%Y-%m-%d"):
return objectDate.strftime(strFormat)
Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')
Output 03-03-2013
1) A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
2) $( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state
3) $( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state
Mostly we want to use for DOM object rather then custom attribute
like data-img, data-xyz
.
Also some of difference when accessing checkbox
value and href
with attr()
and prop()
as thing change with DOM output with
prop()
as full link from origin
and Boolean
value for checkbox
(pre-1.6)
We can only access DOM elements with prop
other then it gives undefined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>prop demo</title>_x000D_
<style>_x000D_
p {_x000D_
margin: 20px 0 0;_x000D_
}_x000D_
b {_x000D_
color: blue;_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
_x000D_
<script>_x000D_
$("input").change(function() {_x000D_
var $input = $(this);_x000D_
$("p").html(_x000D_
".attr( \"checked\" ): <b>" + $input.attr("checked") + "</b><br>" +_x000D_
".prop( \"checked\" ): <b>" + $input.prop("checked") + "</b><br>" +_x000D_
".is( \":checked\" ): <b>" + $input.is(":checked")) + "</b>";_x000D_
}).change();_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
If you can get SSH to it you can an SSH Port-forwarded SVN server.
Use SSHs -L
( or -R
, I forget, it always confuses me ) to make an ssh tunnel so that
127.0.0.1:3690
is really connecting to remote:3690 over the ssh tunnel, and then you can use it via
svn co svn://127.0.0.1/....
IMHO the biggest advantage that REST enables is that of reducing client/server coupling. It is much easier to evolve a REST interface over time without breaking existing clients.
As the error message says, this is not supported on sql server. The only way to ensure refrerential integrity is to work with triggers.
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
Execute following commands:
brew update
brew install openssl
echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
You will have the latest version of openssl installed and accessible from cli (command line/terminal). Since the third command will add export path to .bash_profile
, the newly installed version of openssl will be accessible across system restarts.
Assuming self
is a UIViewController
:
func displayAlert() {
let alert = UIAlertController(title: "Test",
message: "I am a modal alert",
preferredStyle: .alert)
let defaultButton = UIAlertAction(title: "OK",
style: .default) {(_) in
// your defaultButton action goes here
}
alert.addAction(defaultButton)
present(alert, animated: true) {
// completion goes here
}
}
For subsections it's as easy as leveraging strings in ng-include:
<ul id="subNav">
<li><a ng-click="subPage='section1/subpage1.htm'">Sub Page 1</a></li>
<li><a ng-click="subPage='section1/subpage2.htm'">Sub Page 2</a></li>
<li><a ng-click="subPage='section1/subpage3.htm'">Sub Page 3</a></li>
</ul>
<ng-include src="subPage"></ng-include>
Or you can create an object in case you have links to sub pages all over the place:
$scope.pages = { page1: 'section1/subpage1.htm', ... };
<ul id="subNav">
<li><a ng-click="subPage='page1'">Sub Page 1</a></li>
<li><a ng-click="subPage='page2'">Sub Page 2</a></li>
<li><a ng-click="subPage='page3'">Sub Page 3</a></li>
</ul>
<ng-include src="pages[subPage]"></ng-include>
Or you can even use $routeParams
$routeProvider.when('/home', ...);
$routeProvider.when('/home/:tab', ...);
$scope.params = $routeParams;
<ul id="subNav">
<li><a href="#/home/tab1">Sub Page 1</a></li>
<li><a href="#/home/tab2">Sub Page 2</a></li>
<li><a href="#/home/tab3">Sub Page 3</a></li>
</ul>
<ng-include src=" '/home/' + tab + '.html' "></ng-include>
You can also put an ng-controller at the top-most level of each partial
Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
It doesn't. It makes 0 <= r < 1
, but your original is 0 <= r <= 1
.
Note that this can lead to undefined behavior if RAND_MAX + 1
overflows.
This forum on MSDN tells you.
Form.Close()
sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.If you do a
form1.Show()
orApplication.Run(new Form1())
, Dispose will be called whenClose()
is called.However, if you do
form1.ShowDialog()
to show the form modally, the form will not be disposed, and you'll need to callform1.Dispose()
yourself. I believe this is the only time you should worry about disposing the form yourself.
This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:
#include <functional>
#include <random>
class Rand_double
{
public:
Rand_double(double low, double high)
:r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}
double operator()(){ return r(); }
private:
std::function<double()> r;
};
#include <iostream>
int main() {
// create the random number generator:
Rand_double rd{0,0.5};
// print 10 random number between 0 and 0.5
for (int i=0;i<10;++i){
std::cout << rd() << ' ';
}
return 0;
}
That's a known issue. Currently you have to use a workaround like shown in your question.
This is working as intended. When the change event is emitted ngModelChange
(the (...)
part of [(ngModel)]
hasn't updated the bound model yet:
<input type="checkbox" (ngModelChange)="myModel=$event" [ngModel]="mymodel">
See also
Great gugly muglys! This was harder than it needed to be.
This is a great opportunity to use spread (...
in { ...Matters, ...Contacts }
below:
// imports/collections/Matters.js
export default { // default export
hello: 'World',
something: 'important',
};
// imports/collections/Contacts.js
export default { // default export
hello: 'Moon',
email: '[email protected]',
};
// imports/collections/index.js
import Matters from './Matters'; // import default export as var 'Matters'
import Contacts from './Contacts';
export default { // default export
...Matters, // spread Matters, overwriting previous properties
...Contacts, // spread Contacts, overwriting previosu properties
};
// imports/test.js
import collections from './collections'; // import default export as 'collections'
console.log(collections);
Then, to run babel compiled code from the command line (from project root /):
$ npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
(trimmed)
$ npx babel-node --presets @babel/preset-env imports/test.js
{ hello: 'Moon',
something: 'important',
email: '[email protected]' }
If you'd prefer to not overwrite properties, change:
// imports/collections/index.js
import Matters from './Matters'; // import default as 'Matters'
import Contacts from './Contacts';
export default { // export default
Matters,
Contacts,
};
And the output will be:
$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: { hello: 'World', something: 'important' },
Contacts: { hello: 'Moon', email: '[email protected]' } }
If you're dedicated to DRY, the syntax on the imports changes as well:
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
This creates 2 named exports w/ no default export. Then change:
// imports/test.js
import { Matters, Contacts } from './collections';
console.log(Matters, Contacts);
And the output:
$ npx babel-node --presets @babel/preset-env imports/test.js
{ hello: 'World', something: 'important' } { hello: 'Moon', email: '[email protected]' }
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
// imports/test.js
// Import all named exports as 'collections'
import * as collections from './collections';
console.log(collections); // interesting output
console.log(collections.Matters, collections.Contacts);
Notice the destructuring import { Matters, Contacts } from './collections';
in the previous example.
$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: [Getter], Contacts: [Getter] }
{ hello: 'World', something: 'important' } { hello: 'Moon', email: '[email protected]' }
Given these source files:
/myLib/thingA.js
/myLib/thingB.js
/myLib/thingC.js
Creating a /myLib/index.js
to bundle up all the files defeats the purpose of import/export. It would be easier to make everything global in the first place, than to make everything global via import/export via index.js "wrapper files".
If you want a particular file, import thingA from './myLib/thingA';
in your own projects.
Creating a "wrapper file" with exports for the module only makes sense if you're packaging for npm or on a multi-year multi-team project.
Made it this far? See the docs for more details.
Also, yay for Stackoverflow finally supporting three `s as code fence markup.
char grid[row][col];
memset(grid, ' ', sizeof(grid));
That's for initializing char array elements to space characters.
Use git-diff
:
git diff -- yourfile
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
The only way I have found to change this is directly on the code :
at the very beginning of your app you set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
you should include the system.net
class
I did this before calling a web service because we had to block tls1 too.
Maybe... :
datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
layout=%d{${datestamp}} ms=%-4r [%t] %-5p %l %n%m %n%n
# infoFile
log4j.appender.infoFile=org.apache.log4j.RollingFileAppender
log4j.appender.infoFile.File=${MY_HOME}/logs/message.log
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=${layout}
I looked into this a bit more and the actual problem seems to be with assigning initial
to page width
under the print
media rule. It seems like in Chrome width: initial
on the .page
element results in scaling of the page content if no specific length value is defined for width
on any of the parent elements (width: initial
in this case resolves to width: auto
... but actually any value smaller than the size defined under the @page
rule causes the same issue).
So not only the content is now too long for the page (by about 2cm
), but also the page padding will be slightly more than the initial 2cm
and so on (it seems to render the contents under width: auto
to the width of ~196mm
and then scale the whole content up to the width of 210mm
~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm
).
To fix this problem you can simply in the print
media rule assign the A4 paper width and hight to html, body
or directly to .page
and in this case avoid the initial
keyword.
@page {
size: A4;
margin: 0;
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
/* ... the rest of the rules ... */
}
This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).
#define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d))
a = 8.000000
sqrt(a) = r = 2.828427
roundz(r,2) = 2.830000
roundz(r,3) = 2.828000
roundz(r,5) = 2.828430
There's a native DOM API that achieves this out of the box — getBoundingClientRect
:
document.querySelector("#whatever").getBoundingClientRect().right
If you want to just untrack a file and not delete from local and remote repo then use this command:
git update-index --assume-unchanged file_name_with_path
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
None of these answers worked for me for python. I solved by this
a[not(@id='XX')]
Also you can use or condition in your xpath by |
operator. Such as
a[not(@id='XX')]|a[not(@class='YY')]
Sometimes we want element which has no class. So you can do like
a[not(@class)]
since answers are disappointing I would like suggest a way in which I got deleted stuff back.
I use an ide to code and accidently I used rm -rf from terminal to remove complete folder. Thanks to ide I recoved it back by reverting the change from ide's local history.
(my ide is intelliJ but all ide's support history backup)
You have to set the path. See here.
You can use index arrays, simply pass your ind_pos
as an index argument as below:
a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])
print(a[ind_pos])
# [88,85,16]
Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).
For me Fake Sendmail works.
What to do:
1) Edit C:\wamp\sendmail\sendmail.ini:
smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password
2) Edit php.ini
and set sendmail_path
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
That's it. Now you can test a mail.
I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was
Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)
Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...
All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.
This point was not made clear in a precise manner in any place.
I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function myTimer() {
console.log(' each 1 second...');
}
var myVar = setInterval(myTimer, 1000);
call this line to stop the loop:
clearInterval(myVar);
By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.
var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}
var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}
So, do not convert to set if you have repeated values in your array.
// Create object of SharedPreferences.
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("name", required_Text);
//commits your edits
editor.commit();
// Its used to retrieve data
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
if (name.equalsIgnoreCase("required_Text")) {
Log.v("Matched","Required Text Matched");
} else {
Log.v("Not Matched","Required Text Not Matched");
}
I think the following code is more pythonic:
from hashlib import md5
def get_md5(fname):
m = md5()
with open(fname, 'rb') as fp:
for chunk in fp:
m.update(chunk)
return m.hexdigest()
Not possible. The background will always be as large as it can be, but you can stop it from repeating itself with background-repeat
.
background-repeat: no-repeat;
Secondly, the background does not go into margin-area of a box, so if you want to have the background only be on the actual contents of a box, you can use margin instead of padding.
Thirdly, you can control where the background image starts. By default it's the top left corner of a box, but you can control that with background-position
, like this:
background-position: center top;
or perhaps
background-position: 20px -14px;
Negative positioning is used a lot with CSS sprites.
It does seem odd. I found this thread, also thinking I'd seen one in the past, but couldn't find it in Javadoc.
I can see the Java developers' point about using specialised classes, and that the presence of a generic Pair class could cause developers to be lazy (perish the thought!)
However, in my experience, there are undoubtedly times when the thing you're modelling really is just a pair of things and coming up with a meaningful name for the relationship between the two halves of the pair, is actually more painful than just getting on with it. So instead, we're left to create a 'bespoke' class of practically boiler-plate code - probably called 'Pair'.
This could be a slippery slope, but a Pair and a Triplet class would cover a very large proportion of the use-cases.
I was searching how to find out prime number and went through above code which are too long. I found out a new easy solution for prime number and add them using filter. Kindly suggest me if there is any mistake in my code as I am a beginner.
function sumPrimes(num) {
let newNum = [];
for(let i = 2; i <= num; i++) {
newNum.push(i)
}
for(let i in newNum) {
newNum = newNum.filter(item => item == newNum[i] || item % newNum[i] !== 0)
}
return newNum.reduce((a,b) => a+b)
}
sumPrimes(10);
It doesn't inherit from Element
because not all event targets are elements.
Element, document, and window are the most common event targets, but other objects can be event targets too, for example XMLHttpRequest, AudioNode, AudioContext, and others.
Even the KeyboardEvent
you're trying to use can occur on a DOM element or on the window object (and theoretically on other things), so right there it wouldn't make sense for evt.target
to be defined as an Element
.
If it is an event on a DOM element, then I would say that you can safely assume evt.target
. is an Element
. I don't think this is an matter of cross-browser behavior. Merely that EventTarget
is a more abstract interface than Element
.
Further reading: https://typescript.codeplex.com/discussions/432211
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff
What is Heap-Offloading ?
Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.
However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.
One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).
So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.
The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.
It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).
Sample usage scenarios:
Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.
Another way of doing this, assuming we have weights at the same index as the elements in the element array.
import numpy as np
weights = [0.1, 0.3, 0.5] #weights for the item at index 0,1,2
# sum of weights should be <=1, you can also divide each weight by sum of all weights to standardise it to <=1 constraint.
trials = 1 #number of trials
num_item = 1 #number of items that can be picked in each trial
selected_item_arr = np.random.multinomial(num_item, weights, trials)
# gives number of times an item was selected at a particular index
# this assumes selection with replacement
# one possible output
# selected_item_arr
# array([[0, 0, 1]])
# say if trials = 5, the the possible output could be
# selected_item_arr
# array([[1, 0, 0],
# [0, 0, 1],
# [0, 0, 1],
# [0, 1, 0],
# [0, 0, 1]])
Now let's assume, we have to sample out 3 items in 1 trial. You can assume that there are three balls R,G,B present in large quantity in ratio of their weights given by weight array, the following could be possible outcome:
num_item = 3
trials = 1
selected_item_arr = np.random.multinomial(num_item, weights, trials)
# selected_item_arr can give output like :
# array([[1, 0, 2]])
you can also think number of items to be selected as number of binomial/ multinomial trials within a set. So, the above example can be still work as
num_binomial_trial = 5
weights = [0.1,0.9] #say an unfair coin weights for H/T
num_experiment_set = 1
selected_item_arr = np.random.multinomial(num_binomial_trial, weights, num_experiment_set)
# possible output
# selected_item_arr
# array([[1, 4]])
# i.e H came 1 time and T came 4 times in 5 binomial trials. And one set contains 5 binomial trails.
If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:
The overflow property can be used to clear floats with no additional mark-up:
.container { overflow: hidden; }
This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):
.container { zoom: 1; }
Simply add the following:
from sys import *
path_to_current_file = sys.argv[0]
print(path_to_current_file)
Or:
from sys import *
print(sys.argv[0])
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
declare @PrevMonth as nvarchar(256)
SELECT @PrevMonth = DateName( month,DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)) +
'-' + substring(DateName( Year, getDate() ) ,3,4)
I looked around for an answer to this and the best way I found was to use Flex and inline styling on different components.
For example, to make two paper components divide my full screen in 2 vertical components (in ration of 1:4), the following code works fine.
const styles = {
div:{
display: 'flex',
flexDirection: 'row wrap',
padding: 20,
width: '100%'
},
paperLeft:{
flex: 1,
height: '100%',
margin: 10,
textAlign: 'center',
padding: 10
},
paperRight:{
height: 600,
flex: 4,
margin: 10,
textAlign: 'center',
}
};
class ExampleComponent extends React.Component {
render() {
return (
<div>
<div style={styles.div}>
<Paper zDepth={3} style={styles.paperLeft}>
<h4>First Vertical component</h4>
</Paper>
<Paper zDepth={3} style={styles.paperRight}>
<h4>Second Vertical component</h4>
</Paper>
</div>
</div>
)
}
}
Now, with some more calculations, you can easily divide your components on a page.
Navigate to Settings > About Phone > scroll to the bottom > tap Build number seven (7) times. You'll get a short pop-up in the lower area of your display saying that you're now a developer. 2. Go back and now access the Developer options menu, check 'USB debugging' and click OK on the prompt. This Guide Might Help You : How to Enable USB Debugging in Android Phones
While it is quite late to answer now, there is a simple way one could find if Nth bit is set or not, simply using POWER and MODULUS mathematical operators.
Let us say we want to know if 'temp' has Nth bit set or not. The following boolean expression will give true if bit is set, 0 otherwise.
Consider the following example:
If I want to know if 3rd bit is set or not, I get
So expression returns true, indicating 3rd bit is set.
Adding the following to the PySpark did the job for me:
self.spark.sparkContext.setLogLevel("ERROR")
self.spark is the spark session (self.spark = spark_builder.getOrCreate()
)
You can use method_defined?
as follows:
String.method_defined? :upcase # => true
Much easier, portable and efficient than the instance_methods.include?
everyone else seems to be suggesting.
Keep in mind that you won't know if a class responds dynamically to some calls with method_missing
, for example by redefining respond_to?
, or since Ruby 1.9.2 by defining respond_to_missing?
.
try this:
timeout 5 ssh user@ip
timeout executes the ssh command (with args) and sends a SIGTERM if ssh doesn't return after 5 second. for more details about timeout, read this document: http://man7.org/linux/man-pages/man1/timeout.1.html
or you can use the param of ssh:
ssh -o ConnectTimeout=3 user@ip
var GDNUtils = {};
GDNUtils.loadJquery = function () {
var checkjquery = window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery);
if (!checkjquery) {
var theNewScript = document.createElement("script");
theNewScript.type = "text/javascript";
theNewScript.src = "http://code.jquery.com/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
// jQuery MAY OR MAY NOT be loaded at this stage
}
};
GDNUtils.searchJsonValue = function (jsonData, keytoSearch, valuetoSearch, keytoGet) {
GDNUtils.loadJquery();
alert('here' + jsonData.length.toString());
GDNUtils.loadJquery();
$.each(jsonData, function (i, v) {
if (v[keytoSearch] == valuetoSearch) {
alert(v[keytoGet].toString());
return;
}
});
};
GDNUtils.searchJson = function (jsonData, keytoSearch, valuetoSearch) {
GDNUtils.loadJquery();
alert('here' + jsonData.length.toString());
GDNUtils.loadJquery();
var row;
$.each(jsonData, function (i, v) {
if (v[keytoSearch] == valuetoSearch) {
row = v;
}
});
return row;
}
When a search engine spider finds 301 status code in the response header of a webpage, it understands that this webpage no longer exists, it searches for location header in response pick the new URL and replace the indexed URL with the new one and also transfer pagerank.
So search engine refreshes all indexed URL that no longer exist (301 found) with the new URL, this will retain your old webpage traffic, pagerank and divert it to the new one (you will not lose you traffic of old webpage).
Browser: if a browser finds 301 status code then it caches the mapping of the old URL with the new URL, the client/browser will not attempt to request the original location but use the new location from now on unless the cache is cleared.
When a search engine spider finds 302 status for a webpage, it will only redirect temporarily to the new location and crawl both of the pages. The old webpage URL still exists in the search engine database and it always attempts to request the old location and crawl it. The client/browser will still attempt to request the original location.
Read more about how to implement it in asp.net c# and what is the impact on search engines - http://www.dotnetbull.com/2013/08/301-permanent-vs-302-temporary-status-code-aspnet-csharp-Implementation.html
users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1
for i in ${users[@]}; do
t=$(( t + 1 ))
if [ $t -eq 0 ]; then
for j in ${!users[@]}; do
index[$j]=$j
done
fi
echo "${index[$t]} is $i"
done
the input does not have to be a list of records - it can be a single dictionary as well:
pd.DataFrame.from_records({'a':1,'b':2}, index=[0])
a b
0 1 2
Which seems to be equivalent to:
pd.DataFrame({'a':1,'b':2}, index=[0])
a b
0 1 2
I get get the same minicom error, "cannot open /dev/ttyUSB0: No such file or directory"
Three notes:
I get the error when the device attached to the serial port end of my Prolific Technology PL2303 USB/Serial adapter is turned off. After turning on the device (an embedded controller running Linux) minicom connected fine.
I have to run as super user (i.e. sudo minicom
)
Sometimes I have to unplug and plug back in the USB-to-serial adapter to get minicom to connect to it.
I am running Ubuntu 10.04 LTS (Lucid Lynx) under VMware (running on Windows 7). In this situation, make sure the device is attached to VM operating system by right clicking on the USB/Serial USB icon in the lower right of the VMware window and select Connect (Disconnect from Host).
Remember to press Ctrl + A to get minicom's prompt, and type X to exit the program. Just exiting the terminal session running minicom will leave the process running.
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
From the documentation, "the right way is to define a separate server for example.org":
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
...
}
For those who want a solution including https://
...
server {
listen 80;
server_name www.domain.com;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 $scheme://domain.com$request_uri;
}
server {
listen 80;
server_name domain.com;
# here goes the rest of your config file
# example
location / {
rewrite ^/cp/login?$ /cp/login.php last;
# etc etc...
}
}
Note: I have not originally included https://
in my solution since we use loadbalancers and our https:// server is a high-traffic SSL payment server: we do not mix https:// and http://.
To check the nginx version, use nginx -v
.
Strip www from url with nginx redirect
server {
server_name www.domain.com;
rewrite ^(.*) http://domain.com$1 permanent;
}
server {
server_name domain.com;
#The rest of your configuration goes here#
}
So you need to have TWO server codes.
Add the www to the url with nginx redirect
If what you need is the opposite, to redirect from domain.com to www.domain.com, you can use this:
server {
server_name domain.com;
rewrite ^(.*) http://www.domain.com$1 permanent;
}
server {
server_name www.domain.com;
#The rest of your configuration goes here#
}
As you can imagine, this is just the opposite and works the same way the first example. This way, you don't get SEO marks down, as it is complete perm redirect and move. The no WWW is forced and the directory shown!
server {
server_name www.google.com;
rewrite ^(.*) http://google.com$1 permanent;
}
server {
listen 80;
server_name google.com;
index index.php index.html;
####
# now pull the site from one directory #
root /var/www/www.google.com/web;
# done #
location = /favicon.ico {
log_not_found off;
access_log off;
}
}
Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str()
.
min(as.numeric(data[,2]))
If its possible uninstall wamp then run installation as administrator then change you mysql.conf file like that
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
Allow from all
</Directory>
Not: Before I reinstall as admin the solution above didn't work for me
The simplest way to delete rows and columns from arrays is the numpy.delete
method.
Suppose I have the following array x
:
x = array([[1,2,3],
[4,5,6],
[7,8,9]])
To delete the first row, do this:
x = numpy.delete(x, (0), axis=0)
To delete the third column, do this:
x = numpy.delete(x,(2), axis=1)
So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.
SQL Server Script
declare @iDate datetime
set @iDate=GETDATE()
print year(@iDate) -- for Year
print month(@iDate) -- for Month
print day(@iDate) -- for Day
You can run a JAR file from the command line like this:
java -jar myJARFile.jar
Is it possible to refactor the nested for loop into a private method? That way you could simply 'return' out of the method to exit the loop.
These are exactly the same. android:onClick
was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener
on the Button, which calls your DoIt
method.
Here is what using a android:onClick="DoIt"
does internally:
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DoIt(v);
}
});
The only thing you trade off by using android:onClick
, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt
method.
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char
, terminated by a null character \0
. Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x[] = {'h','e','l','l','o','\0'};
The correct way would be:
char s[100];
strncpy(s, "hello", 100);
or better yet:
#define STRMAX 100
char s[STRMAX];
size_t len;
len = strncpy(s, "hello", STRMAX);
Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:
GRANT ALL ON table1 TO doctor
Users in that role will have no permissions whatsoever to other tables (not even read).
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
In my scenario, using EF, upon trying to create this new Foreign Key on existing data, I was wrongly trying to populate the data (make the links) AFTER creating the foreign key.
The fix is to populate your data before creating the foreign key since it checks all of them to see if the links are indeed valid. So it couldn't possibly work if you haven't populated it yet.
In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):
let sav = "";
for (let e in process.env) {
if (/VUE_APP_/i.test(e)) {
sav += `$${e}: "${process.env[e]}";`;
}
}
module.exports = {
css: {
loaderOptions: {
sass: {
data: sav,
},
},
},
}
The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.
You can then use these variables in your sass section of a vue file:
<style lang="scss">
.MyDiv {
margin: 1em 0 0 0;
background-image: url($VUE_APP_CDN+"/MyImg.png");
}
</style>
or in a .scss file:
.MyDiv {
margin: 1em 0 0 0;
background-image: url($VUE_APP_CDN+"/MyImg.png");
}
from https://www.matt-helps.com/post/expose-env-variables-vue-cli-sass/
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
Use this method:
$_product = wc_get_product( $id );
Official API-docs: wc_get_product
use
sudo pip install virtualenv
You have a permission denied error. This states your current user does not have the root permissions.So run the command as a super user.
Your tuples are basically key-value pairs--a python dict
--so:
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
val = dict(l)[53]
Edit -- aha, you say you want the index value of (53, "xuxa"). If this is really what you want, you'll have to iterate through the original list, or perhaps make a more complicated dictionary:
d = dict((n,i) for (i,n) in enumerate(e[0] for e in l))
idx = d[53]
The checked
and selected
attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.
If you don't want to set the attribute, then the entire attribute must be omitted.
Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).
Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:
<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ... checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked > <!-- Only HTML 5 and later -->
<input ... checked="" > <!-- Only HTML 5 and later -->
Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true"
, checked="yes"
, and checked="false"
will all trigger the checked state.
I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.
(And all the above applies equally to selected
as it does to checked
.)
Nick's answer works great and the default settings are nice, but you can more fully control the scrolling by completing all of the optional settings.
here is what it looks like in the API:
.animate( properties [, duration] [, easing] [, complete] )
so you could do something like this:
.animate(
{scrollTop:'300px'},
300,
swing,
function(){
alert(animation complete! - your custom code here!);
}
)
here is the jQuery .animate function api page: http://api.jquery.com/animate/
you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)
When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ
:
$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;
If you are using CloudFlare or a similar CDN you will get an infinite loop error with the %{HTTPS} solutions provided here. If you're a CloudFlare user you'll need to use this:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
You want your change to sit on top of the current state of the remote branch. So probably you want to pull right before you commit yourself. After that, push your changes again.
"Dirty" local files are not an issue as long as there aren't any conflicts with the remote branch. If there are conflicts though, the merge will fail, so there is no risk or danger in pulling before committing local changes.
http://guides.rubyonrails.org should be a good site if you're trying to get through the basic stuff in Ruby on Rails.
Here is a link to associate models while you generate them: http://guides.rubyonrails.org/getting_started.html#associating-models
This is the fastest and easiest way that I have found;
while (tableModel.getRowCount()>0)
{
tableModel.removeRow(0);
}
This clears the table lickety split and leaves it ready for new data.
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort()
.
See the documentation:
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
UPDATE: As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).
UPDATE 2:
As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr
any more. See the 3.0 blog here.
UPDATE 3: xhr.abort()
still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.
The performance should be identical, but I would suggest using the join-version due to improved clarity when it comes to outer joins.
Also unintentional cartesian products can be avoided using the join-version.
A third effect is an easier to read SQL with a simpler WHERE-condition.
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
In PHP, use random_bytes()
. Reason: your are seeking the way to get a password reminder token, and, if it is a one-time login credentials, then you actually have a data to protect (which is - whole user account)
So, the code will be as follows:
//$length = 78 etc
$token = bin2hex(random_bytes($length));
Update: previous versions of this answer was referring to uniqid()
and that is incorrect if there is a matter of security and not only uniqueness. uniqid()
is essentially just microtime()
with some encoding. There are simple ways to get accurate predictions of the microtime()
on your server. An attacker can issue a password reset request and then try through a couple of likely tokens. This is also possible if more_entropy is used, as the additional entropy is similarly weak. Thanks to @NikiC and @ScottArciszewski for pointing this out.
For more details see
I think the usual use case is to call it when no exception was thrown in a negative test.
Something like the following pseudo-code:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
In most of cases it is data log problem. Follow the steps.
i) Go to data folder of mysql. For xampp go to C:\xampp\mysql\data.
ii) Look for log file name like ib_logfile0 and ib_logfile1.
iii) Create backup and delete those files.
iv) Restart apache and mysql.
This OTN-thread contains several ways to do string aggregation, including a performance comparison: http://forums.oracle.com/forums/message.jspa?messageID=1819487#1819487
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '¶m=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.