Another way is to look at the source for Symfony\Component\HttpKernel\Kernel
for where const VERSION
is defined. Example on GitHub
Locally this would be located in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php
.
I found this solution worked perfectly fine for me. Doesn't require any third party apis
'test' is actually a folder will lots of file inside.
String folderPath= "C:\Users\Desktop\test";
String zipPath = "C:\Users\Desktop\test1.zip";
private boolean zipDirectory(String folderPath, String zipPath) throws IOException{
byte[] buffer = new byte[1024];
FileInputStream fis = null;
ZipOutputStream zos = null;
try{
zos = new ZipOutputStream(new FileOutputStream(zipPath));
updateSourceFolder(new File(folderPath));
if (sourceFolder == null) {
zos.close();
return false;
}
generateFileAndFolderList(new File(folderPath));
for (String unzippedFile: fileList) {
System.out.println(sourceFolder + unzippedFile);
ZipEntry entry = new ZipEntry(unzippedFile);
zos.putNextEntry(entry);
if ((unzippedFile.substring(unzippedFile.length()-1)).equals(File.separator))
continue;
try{
fis = new FileInputStream(sourceFolder + unzippedFile);
int len=0;
while ((len = fis.read(buffer))>0) {
zos.write(buffer,0,len);
}
} catch(IOException e) {
return false;
} finally {
if (fis != null)
fis.close();
}
}
zos.closeEntry();
} catch(IOException e) {
return false;
} finally {
zos.close();
fileList = null;
sourceFolder = null;
}
return true;
}
private void generateFileAndFolderList(File node) {
if (node.isFile()) {
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if (node.isDirectory()) {
String dir = node.getAbsoluteFile().toString();
fileList.add(dir.substring(sourceFolder.length(), dir.length()) + File.separator);
String[] subNode = node.list();
for (String fileOrFolderName : subNode) {
generateFileAndFolderList(new File(node, fileOrFolderName));
}
}
}
private void updateSourceFolder(File node) {
if (node.isFile() || node.isDirectory()) {
String sf = node.getAbsoluteFile().toString();
sourceFolder = sf.substring(0, (sf.lastIndexOf("/") > 0 ? sf.lastIndexOf("/") : sf.lastIndexOf("\\")));
sourceFolder += File.separator;
} else
sourceFolder = null;
}
private String generateZipEntry(String file) {
return file.substring(sourceFolder.length(), file.length());
}
If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:
this.Controls.Add(this.reportViewer1);
or
[ContainerControl].Controls.Add(this.reportViewer1);
You'll also need to make adjustments to the location and size manually after you've added the control.
Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
For some odd reason this DID NOT work (using Pandas: '0.25.1')
df[['col1', 'col2']].fillna(value=0, inplace=True)
Another solution:
subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]
Example:
df = pd.DataFrame(data={'col1':[1,2,np.nan,], 'col2':[1,np.nan,3], 'col3':[np.nan,2,3]})
output:
col1 col2 col3
0 1.00 1.00 nan
1 2.00 nan 2.00
2 nan 3.00 3.00
Apply list comp. to fillna values:
subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]
Output:
col1 col2 col3
0 1.00 1.00 nan
1 2.00 0.00 2.00
2 0.00 3.00 3.00
Locale
configuration
should be set in each activity
before setting the content - this.setContentView(R.layout.main);
Convert has a style parameter for date to string conversions.
I know this is an old question, but I'm going to answer it because I have to disagree with all the answers here.
Now, I'll agree that most of the time you either want to do a plain throw
, to preserve as much information as possible about what went wrong, or you want to throw a new exception that may contain that as an inner-exception, or not, depending on how likely you are to want to know about the inner events that caused it.
There is an exception though. There are several cases where a method will call into another method and a condition that causes an exception in the inner call should be considered the same exception on the outer call.
One example is a specialised collection implemented by using another collection. Let's say it's a DistinctList<T>
that wraps a List<T>
but refuses duplicate items.
If someone called ICollection<T>.CopyTo
on your collection class, it might just be a straight call to CopyTo
on the inner collection (if say, all the custom logic only applied to adding to the collection, or setting it up). Now, the conditions in which that call would throw are exactly the same conditions in which your collection should throw to match the documentation of ICollection<T>.CopyTo
.
Now, you could just not catch the execption at all, and let it pass through. Here though the user gets an exception from List<T>
when they were calling something on a DistinctList<T>
. Not the end of the world, but you may want to hide those implementation details.
Or you could do your own checking:
public CopyTo(T[] array, int arrayIndex)
{
if(array == null)
throw new ArgumentNullException("array");
if(arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "Array Index must be zero or greater.");
if(Count > array.Length + arrayIndex)
throw new ArgumentException("Not enough room in array to copy elements starting at index given.");
_innerList.CopyTo(array, arrayIndex);
}
That's not the worse code because it's boilerplate and we can probably just copy it from some other implementation of CopyTo
where it wasn't a simple pass-through and we had to implement it ourselves. Still, it's needlessly repeating the exact same checks that are going to be done in _innerList.CopyTo(array, arrayIndex)
, so the only thing it has added to our code is 6 lines where there could be a bug.
We could check and wrap:
public CopyTo(T[] array, int arrayIndex)
{
try
{
_innerList.CopyTo(array, arrayIndex);
}
catch(ArgumentNullException ane)
{
throw new ArgumentNullException("array", ane);
}
catch(ArgumentOutOfRangeException aore)
{
throw new ArgumentOutOfRangeException("Array Index must be zero or greater.", aore);
}
catch(ArgumentException ae)
{
throw new ArgumentException("Not enough room in array to copy elements starting at index given.", ae);
}
}
In terms of new code added that could potentially be buggy, this is even worse. And we don't gain a thing from the inner exceptions. If we pass a null array to this method and receive an ArgumentNullException
, we're not going to learn anything by examining the inner exception and learning that a call to _innerList.CopyTo
was passed a null array and threw an ArgumentNullException
.
Here, we can do everything we want with:
public CopyTo(T[] array, int arrayIndex)
{
try
{
_innerList.CopyTo(array, arrayIndex);
}
catch(ArgumentException ae)
{
throw ae;
}
}
Every one of the exceptions that we expect to have to throw if the user calls it with incorrect arguments, will correctly be thrown by that re-throw. If there's a bug in the logic used here, it's in one of two lines - either we were wrong in deciding this was a case where this approach works, or we were wrong in having ArgumentException
as the exception type looked for. It's the only two bugs that the catch block can possibly have.
Now. I still agree that most of the time you either want a plain throw;
or you want to construct your own exception to more directly match the problem from the perspective of the method in question. There are cases like the above where re-throwing like this makes more sense, and there are plenty of other cases. E.g. to take a very different example, if an ATOM file reader implemented with a FileStream
and an XmlTextReader
receives a file error or invalid XML, then it will perhaps want to throw exactly the same exception it received from those classes, but it should look to the caller that it is AtomFileReader
that is throwing a FileNotFoundException
or XmlException
, so they might be candidates for similarly re-throwing.
Edit:
We can also combine the two:
public CopyTo(T[] array, int arrayIndex)
{
try
{
_innerList.CopyTo(array, arrayIndex);
}
catch(ArgumentException ae)
{
throw ae;
}
catch(Exception ex)
{
//we weren't expecting this, there must be a bug in our code that put
//us into an invalid state, and subsequently let this exception happen.
LogException(ex);
throw;
}
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push()
method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form
, however you don't have a form on the page. In order for this to work you would need to have <form>
tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick
attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert()
function uses the references to each input field to get their value. It then uses the push()
method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow()
function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value
property of each input to an empty string. It then clears out the .innerHTML
of our message box. Lastly, it calls the join()
method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
If you want to also support array-like objects, use Array.from (ES2015):
Array.from(arrayLike, x => x.foo);
The advantage it has over Array.prototype.map() method is the input can also be a Set:
let arrayLike = new Set([{foo: 1}, {foo: 2}, {foo: 3}]);
To put a sequence or another numpy array into a numpy array, Just change this line:
kOUT=np.zeros(N+1)
to:
kOUT=np.asarray([None]*(N+1))
Or:
kOUT=np.zeros((N+1), object)
Facing same issue.
I got success following ways.
Open your buldle.gradle file and upgrade the versions for following both classpath
classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.google.gms:google-services:4.2.0'
Then Sync and after get one dilaog for update Gradle version as well then click that link and wait for download all required updates(Hope internet available). After taking long time you got Success.
And i can't alter the object. I can't put new methods on it.
How do i do this?
In case you also mean how do I make the object immutable and prevent subclassing: use the final
keyword
public final class Blog { //final classes can't be extended/subclassed
private final String title; //final members have to be set in the constructor and can't be changed
private final String author;
private final String url;
private final String description;
...
}
Edit: I just saw some of your comments and it seems you want to change the class but can't (third party I assume).
To prevent duplicates you might use a wrapper that implements appropriate equals()
and hashCode()
, then use the Set
aproach mentioned by the others:
class BlogWrapper {
private Blog blog; //set via constructor etc.
public int hashCode() {
int hashCode = blog.getTitle().hashCode(); //check for null etc.
//add the other hash codes as well
return hashCode;
}
public boolean equals(Object other) {
//check if both are BlogWrappers
//remember to check for null too!
Blog otherBlog = ((BlogWrapper)other).getBlog();
if( !blog.getTitle().equals(otherBlog.getTitle()) {
return false;
}
... //check other fields as well
return true
}
}
Note that this is just a rough and simple version and doesn't contain the obligatory null checks.
Finally use a Set<BlogWrapper>
, loop through all the blogs and try to add new BlogWrapper(blog)
to the set. In the end, you should only have unique (wrapped) blogs in the set.
Adding to @behzad.nouri 's answer - we can create a helper routine to handle this common scenario:
def csvDf(dat,**kwargs):
from numpy import array
data = array(dat)
if data is None or len(data)==0 or len(data[0])==0:
return None
else:
return pd.DataFrame(data[1:,1:],index=data[1:,0],columns=data[0,1:],**kwargs)
Let's try it out:
data = [['','a','b','c'],['row1','row1cola','row1colb','row1colc'],
['row2','row2cola','row2colb','row2colc'],['row3','row3cola','row3colb','row3colc']]
csvDf(data)
In [61]: csvDf(data)
Out[61]:
a b c
row1 row1cola row1colb row1colc
row2 row2cola row2colb row2colc
row3 row3cola row3colb row3colc
hdfs dfs -count <dir>
info from man page:
-count [-q] [-h] [-v] [-t [<storage type>]] [-u] <path> ... :
Count the number of directories, files and bytes under the paths
that match the specified file pattern. The output columns are:
DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME
or, with the -q option:
QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA
DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME
Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:
df3 = df1[df1.index.isin(df2.index)]
or where df1 index does not exist in df2...
df3 = df1[~df1.index.isin(df2.index)]
You can simply do this
$(function() {
$( "#datepicker" ).datepicker({ maxDate: new Date });
});
FYI: while checking the documentation, found that it also accepts numeric values too.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
so 0
represents today. Therefore you can do this too
$( "#datepicker" ).datepicker({ maxDate: 0 });
thead {
position: fixed;
height: 10px; /* This is whatever height you want */
}
tbody {
position: fixed;
margin-top: 10px; /* This has to match the height of thead */
height: 300px; /* This is whatever height you want */
}
This BASH script will execute the python unittest test directory from anywhere in the file system, no matter what working directory you are in.
This is useful when staying in the ./src
or ./example
working directory and you need a quick unit test:
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
python -m unittest discover -s "$readlink"/test -v
No need for a test/__init__.py
file to burden your package/memory-overhead during production.
Use this String.valueOf(value);
public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {
JSONObject jResult = new JSONObject();// main object
JSONArray jArray = new JSONArray();// /ItemDetail jsonArray
for (int i = 0; i < list.size(); i++) {
JSONObject jGroup = new JSONObject();// /sub Object
try {
jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
jGroup.put("ID", list.get(i).get("id"));
jGroup.put("Name", list.get(i).get("name"));
jGroup.put("Category", list.get(i).get("category"));
jArray.put(jGroup);
// /itemDetail Name is JsonArray Name
jResult.put("itemDetail", jArray);
return jResult;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:
$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
mb_substr( $str, -7, null, 'UTF-8') ;
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.
I'm assuming you already know how to bind a service with an Activity. I do something sort of like the code below to handle this kind of problem:
class MyService extends Service {
MyFragment mMyFragment = null;
MyFragment mMyOtherFragment = null;
private void networkLoop() {
...
//received new data for list.
if(myFragment != null)
myFragment.updateList();
}
...
//received new data for textView
if(myFragment !=null)
myFragment.updateText();
...
//received new data for textView
if(myOtherFragment !=null)
myOtherFragment.updateSomething();
...
}
}
class MyFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=null;
}
public void updateList() {
runOnUiThread(new Runnable() {
public void run() {
//Update the list.
}
});
}
public void updateText() {
//as above
}
}
class MyOtherFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=null;
}
public void updateSomething() {//etc... }
}
I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.
Not saying this is the best approach, but it seems to work for me.
The full code may be found at: Example code at: https://github.com/dbleicher/recyclerview-grid-quickreturn
First off, add the expanded area to your cell/item layout, and make the enclosing cell layout animateLayoutChanges="true". This will ensure that the expand/collapse is animated:
<LinearLayout
android:id="@+id/llCardBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:animateLayoutChanges="true"
android:padding="4dp"
android:orientation="vertical">
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|fill_horizontal"
android:padding="10dp"
android:gravity="center"
android:background="@android:color/holo_green_dark"
android:text="This is a long title to show wrapping of text in the view."
android:textColor="@android:color/white"
android:textSize="16sp" />
<TextView
android:id="@+id/tvSubTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|fill_horizontal"
android:background="@android:color/holo_purple"
android:padding="6dp"
android:text="My subtitle..."
android:textColor="@android:color/white"
android:textSize="12sp" />
<LinearLayout
android:id="@+id/llExpandArea"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:text="Item One" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:text="Item Two" />
</LinearLayout>
</LinearLayout>
Then, make your RV Adapter class implement View.OnClickListener so that you can act on the item being clicked. Add an int field to hold the position of the one expanded view, and initialize it to a negative value:
private int expandedPosition = -1;
Finally, implement your ViewHolder, onBindViewHolder() methods and override the onClick() method. You will expand the view in onBindViewHolder if it's position is equal to "expandedPosition", and hide it if not. You set the value of expandedPosition in the onClick listener:
@Override
public void onBindViewHolder(RVAdapter.ViewHolder holder, int position) {
int colorIndex = randy.nextInt(bgColors.length);
holder.tvTitle.setText(mDataset.get(position));
holder.tvTitle.setBackgroundColor(bgColors[colorIndex]);
holder.tvSubTitle.setBackgroundColor(sbgColors[colorIndex]);
if (position == expandedPosition) {
holder.llExpandArea.setVisibility(View.VISIBLE);
} else {
holder.llExpandArea.setVisibility(View.GONE);
}
}
@Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
String theString = mDataset.get(holder.getPosition());
// Check for an expanded view, collapse if you find one
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
// Set the current position to "expanded"
expandedPosition = holder.getPosition();
notifyItemChanged(expandedPosition);
Toast.makeText(mContext, "Clicked: "+theString, Toast.LENGTH_SHORT).show();
}
/**
* Create a ViewHolder to represent your cell layout
* and data element structure
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvSubTitle;
LinearLayout llExpandArea;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
tvSubTitle = (TextView) itemView.findViewById(R.id.tvSubTitle);
llExpandArea = (LinearLayout) itemView.findViewById(R.id.llExpandArea);
}
}
This should expand only one item at a time, using the system-default animation for the layout change. At least it works for me. Hope it helps.
Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.
This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.
A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.
A VBA 'Array to Range' function
Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)
' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.
' This subroutine saves repetitive coding for a common VBA and Excel task.
' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.
On Error Resume Next
'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code
Dim rngOutput As Excel.Range
Dim iRowCount As Long
Dim iColCount As Long
Dim iRow As Long
Dim iCol As Long
Dim arrTemp As Variant
Dim iDimensions As Integer
Dim iRowOffset As Long
Dim iColOffset As Long
Dim iStart As Long
Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
rngTarget.ClearContents
End If
Application.EnableEvents = True
If IsEmpty(InputArray) Then
Exit Sub
End If
If TypeName(InputArray) = "Range" Then
InputArray = InputArray.Value
End If
' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
rngTarget.Cells(1, 1).Value2 = InputArray
Exit Sub
End If
iDimensions = ArrayDimensions(InputArray)
If iDimensions < 1 Then
rngTarget.Value = CStr(InputArray)
ElseIf iDimensions = 1 Then
iRowCount = UBound(InputArray) - LBound(InputArray)
iStart = LBound(InputArray)
iColCount = 1
If iRowCount > (655354 - rngTarget.Row) Then
iRowCount = 655354 + iStart - rngTarget.Row
ReDim Preserve InputArray(iStart To iRowCount)
End If
iRowCount = UBound(InputArray) - LBound(InputArray)
iColCount = 1
' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
arrTemp(iRow, 1) = InputArray(iRow)
Next
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
rngOutput.Value2 = arrTemp
Set rngTarget = rngOutput
End With
Erase arrTemp
ElseIf iDimensions = 2 Then
iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)
iStart = LBound(InputArray, 1)
If iRowCount > (65534 - rngTarget.Row) Then
iRowCount = 65534 - rngTarget.Row
InputArray = ArrayTranspose(InputArray)
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
InputArray = ArrayTranspose(InputArray)
End If
iStart = LBound(InputArray, 2)
If iColCount > (254 - rngTarget.Column) Then
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
End If
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))
Err.Clear
Application.EnableEvents = False
rngOutput.Value2 = InputArray
Application.EnableEvents = True
If Err.Number <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Formula = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
If Left(InputArray(iRow, iCol), 1) = "=" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "+" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "*" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Value2 = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsObject(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
ElseIf IsArray(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
ElseIf IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
If Len(InputArray(iRow, iCol)) > 255 Then
' Block-write operations fail on strings exceeding 255 chars. You *have*
' to go back and check, and write this masterpiece one cell at a time...
InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Text = InputArray
End If 'err<>0
If Err <> 0 Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
iRowOffset = LBound(InputArray, 1) - 1
iColOffset = LBound(InputArray, 2) - 1
For iRow = 1 To iRowCount
If iRow Mod 100 = 0 Then
Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
End If
For iCol = 1 To iColCount
rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
Next iCol
Next iRow
Application.StatusBar = False
Application.ScreenUpdating = True
End If 'err<>0
Set rngTarget = rngOutput ' resizes the range This is useful, *most* of the time
End With
End If
End Sub
You will need the source for ArrayDimensions:
This API declaration is required in the module header:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
...And here's the function itself:
Private Function ArrayDimensions(arr As Variant) As Integer
'-----------------------------------------------------------------
' will return:
' -1 if not an array
' 0 if an un-dimmed array
' 1 or more indicating the number of dimensions of a dimmed array
'-----------------------------------------------------------------
' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
' Code written by Chris Rae, 25/5/00
' Originally published by R. B. Smissaert.
' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax
Dim ptr As Long
Dim vType As Integer
Const VT_BYREF = &H4000&
'get the real VarType of the argument
'this is similar to VarType(), but returns also the VT_BYREF bit
CopyMemory vType, arr, 2
'exit if not an array
If (vType And vbArray) = 0 Then
ArrayDimensions = -1
Exit Function
End If
'get the address of the SAFEARRAY descriptor
'this is stored in the second half of the
'Variant parameter that has received the array
CopyMemory ptr, ByVal VarPtr(arr) + 8, 4
'see whether the routine was passed a Variant
'that contains an array, rather than directly an array
'in the former case ptr already points to the SA structure.
'Thanks to Monte Hansen for this fix
If (vType And VT_BYREF) Then
' ptr is a pointer to a pointer
CopyMemory ptr, ByVal ptr, 4
End If
'get the address of the SAFEARRAY structure
'this is stored in the descriptor
'get the first word of the SAFEARRAY structure
'which holds the number of dimensions
'...but first check that saAddr is non-zero, otherwise
'this routine bombs when the array is uninitialized
If ptr Then
CopyMemory ArrayDimensions, ByVal ptr, 2
End If
End Function
Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module
statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.
for /f "delims=" %%i in ('dir /b /a-d *.txt') do ren "%%~i" "%%~ni 1.1%%~xi"
If you use the simple for
loop without the /f
parameter, already renamed files will be again renamed.
At least on Debian and all its derivatives, there is a 'sensible-browser' shell script which choose the browser best suited for the given url.
declare
cntr number :=0;
cursor c1 is
select salary from employees order by salary desc;
z c1%rowtype;
begin
open c1;
fetch c1 into z;
while (c1%found) and (cntr <= 1) loop
cntr := cntr + 1;
fetch c1 into z;
dbms_output.put_line(z.salary);
end loop;
end;
If you're doing some performance tuning it's often recommended to set both -XX:PermSize
and -XX:MaxPermSize
to the same value to increase JVM
efficiency.
Here is some information:
You can also specify -XX:+CMSClassUnloadingEnabled
to enable class unloading
option if you are using CMS
GC
. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space
Simply use if statement
if(!isset($_SESSION))
{
session_start();
}
or
check the session status with session_status that Returns the current session status and if current session is already working then return with nothing else if session not working start the session
session_status() === PHP_SESSION_ACTIVE ?: session_start();
You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:
print({k:d[k] for k in l if k in d})
Some timings:
{k:d[k] for k in set(d).intersection(l)}
In [22]: %%timeit
l = xrange(100000)
{k:d[k] for k in l}
....:
100 loops, best of 3: 11.5 ms per loop
In [23]: %%timeit
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
....:
10 loops, best of 3: 20.4 ms per loop
In [24]: %%timeit
l = xrange(100000)
l = set(l)
{key: d[key] for key in d.viewkeys() & l}
....:
10 loops, best of 3: 24.7 ms per
In [25]: %%timeit
l = xrange(100000)
{k:d[k] for k in l if k in d}
....:
100 loops, best of 3: 17.9 ms per loop
I don't see how {k:d[k] for k in l}
is not readable or elegant and if all elements are in d then it is pretty efficient.
JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
I know this is late but it could help somebody.
You can use a constraintLayout and add the following property in the xml,
android:elevation="4dp"
Do this for a cool border
and font
effect:
#ck-button:hover { /*ADD :hover */
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid red; /*change border color*/
overflow:auto;
float:left;
color:red; /*add font color*/
}
Example: http://jsfiddle.net/zAFND/6/
There are two properties in a TabControl control that manages which tab page is selected.
SelectedIndex which offer the possibility to select it by index (an integer starting from 0 to the number of tabs you have minus one).
SelectedTab which offer the possibility to selected the tab object itself to select.
Setting either of these property will change the currently displayed tab.
Alternatively you can also use the Select method. It comes in three flavour, one where you pass the index of the tab, another the TabPage object itself and the last one a string representing the tab's name.
Is there any reason not to use threads? You can use the threading
class.
Instead of finished()
function use the isAlive()
. The result()
function could join()
the thread and retrieve the result. And, if you can, override the run()
and __init__
functions to call the function specified in the constructor and save the value somewhere to the instance of the class.
Very late to the party, but posting in case this may help someone in the future. For my use case, the following function worked the best. Works to pull any data type out of dictionary
dict is the dictionary containing our value
list is a list of "steps" towards our value
def getnestedvalue(dict, list):
length = len(list)
try:
for depth, key in enumerate(list):
if depth == length - 1:
output = dict[key]
return output
dict = dict[key]
except (KeyError, TypeError):
return None
return None
But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!
My first week of using cmake - after some years of GNU autotools - so I am still learning (better then writing m4 macros), but I think modifying CMAKE_INSTALL_PREFIX after setting project is the better place.
CMakeLists.txt
cmake_minimum_required (VERSION 2.8)
set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
project (BarkBark)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
First run (no cache)
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- The C compiler identification is GNU 4.4.7
-- etc, etc,...
CIP = /usr/local (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done
Second run
CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done
Let me know if I am mistaken, I have a lot of learning to do. It's fun.
If you want more alternatives, You can try installing a Modern command line HTTP client like httpie which is available for most of the Operating Systems with package managers like brew, apt-get, pip, yum etc
eg:- For OSX
brew install httpie
Then you can use it on command line with various options
http GET https://www.google.com
Telerik's Just Decompile is the best I've used. It's free once you sign up with an email.
In lldb as of beta 5, you can see the class of an object with the command:
fr v -d r shipDate
which outputs something like:
(DBSalesOrderShipDate_DBSalesOrderShipDate_ *) shipDate = 0x7f859940
The command expanded out means something like:
Frame Variable
(print a frame variable) -d run_target
(expand dynamic types)
Something useful to know is that using "Frame Variable" to output variable values guarantees no code is executed.
There are multiple nuget packages read in the following order:
NuGetDefaults.Config file
. You will find this in %ProgramFiles(x86)%\NuGet\Config
.%APPDATA%\NuGet\nuget.config
.nuget.config
beginning from the root of your drive up to the directory where nuget.exe is called.You can find more information here.
I wanted a vanilla, lightweight (jQuery UI Layout weighs in at 185 KB), no dependency option (all existing libraries require jQuery), so I wrote Split.js.
It weights less than 2 KB and does not require any special markup. It supports older browsers back to Internet Explorer 9 (or Internet Explorer 8 with polyfills). For modern browsers, you can use it with Flexbox and grid layouts.
You can try this:
header('Refresh: 10; URL=http://yoursite.com/page.php');
Where 10 is in seconds.
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")
Like these you can get era, year, month, date etc. by passing corresponding.
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
Reloading the configuration file (my.cnf
) cannot be done without restarting the mysqld
server.
FLUSH LOGS
only rotates a few log files.
SET @@...=...
sets it for anyone not yet logged in, but it will go away after the next restart. But that gives a clue... Do the SET
, and change my.cnf
; that way you are covered. Caveat: Not all settings can be performed via SET
.
New with MySQL 8.0...
SET PERSIST ...
will set the global setting and save it past restarts. Nearly all settings can be adjusted this way.
The question is too broad to be answered definitively. Are you talking about removing all tags from a real-world HTML document, like a web page? If so, you would have to:
That's just off the top of my head--I'm sure there's more. Once you've done all that, you'll end up with words, sentences and paragraphs run together in some places, and big chunks of useless whitespace in others.
But, assuming you're working with just a fragment and you can get away with simply removing all tags, here's the regex I would use:
@"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>"
Matching single- and double-quoted strings in their own alternatives is sufficient to deal with the problem of angle brackets in attribute values. I don't see any need to explicitly match the attribute names and other stuff inside the tag, like the regex in Ryan's answer does; the first alternative handles all of that.
In case you're wondering about those (?>...)
constructs, they're atomic groups. They make the regex a little more efficient, but more importantly, they prevent runaway backtracking, which is something you should always watch out for when you mix alternation and nested quantifiers as I've done. I don't really think that would be a problem here, but I know if I don't mention it, someone else will. ;-)
This regex isn't perfect, of course, but it's probably as good as you'll ever need.
you have enlosed start_date
with single quote causing it to become string, use backtick
instead
SELECT * FROM `la_schedule` WHERE `start_date` > '2012-11-18';
The accepted answer didn't work for me in Android 2.2. I don't know why, but it was "eating" some of my zeros (0) . Apache commons also didn't work on Android 2.2, because it uses methods that are supported only starting from Android 2.3.x. Also, if you want to just MD5 a string, Apache commons is too complex for that. Why one should keep a whole library to use just a small function from it...
Finally I found the following code snippet here which worked perfectly for me. I hope it will be useful for someone...
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
} catch(UnsupportedEncodingException ex){
}
return null;
}
You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumnName BIT
The other option would be to create a new column of type BIT
, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..
Try this:
$(".ui-widget-overlay").click(function () {
$(".ui-icon.ui-icon-closethick").trigger("click");
});
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
WEEK
select TRUNC(sysdate, 'iw') AS iso_week_start_date,
TRUNC(sysdate, 'iw') + 7 - 1/86400 AS iso_week_end_date
from dual;
MONTH
select
TRUNC (sysdate, 'mm') AS month_start_date,
LAST_DAY (TRUNC (sysdate, 'mm')) + 1 - 1/86400 AS month_end_date
from dual;
Alternatively, you can do this from a Windows commandline prompt/batch file:
sqlite3.exe DB.db ".read db.sql"
Where DB.db is the database file, and db.sql is the SQL file to run/import.
I would suggest a two step query
I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id
, substitute with whatever your PK is called.
1 - figure out the primary key number for column 1000.
SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000
2 - update the table.
UPDATE smartmeter_usage.users_reporting SET panel_id = 3
WHERE panel_id IS NULL AND id >= @id
ORDER BY id
LIMIT 1000
Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.
You should consider using a SharedModule for the essential material components of your app, and then import every single module you need to use into your feature modules. I wrote an article on medium explaining how to import Angular material, check it out:
https://medium.com/@benmohamehdi/how-to-import-angular-material-angular-best-practices-80d3023118de
Try this
SELECT *
FROM people P
where P.IDNo in (SELECT DISTINCT IDNo
FROM people)
select *
from tbl1
where
datetime_column >=
DATEADD(m, -6, convert(date, convert(varchar(6), getdate(),112) + '01'))
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
How to create a resource:
In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.
How to use a resource:
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called Properties.Resources
that gives you access to all your resources, so my code ended up being as simple as:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
Done! Finished! Everything is simple when you know how, isn't it?
@user812954's answer was quite helpful, except I had to do this this in two steps:
sudo su
cd directory
Then, to exit out of "super user" mode, just type exit
.
If you take a look at bootstrap source codes, you will notice that position can be modified using margin.
So, first you should change popover template to add own css class to not get in conflict with other popovers:
$(".trigger").popover({
html: true,
placement: 'bottom',
trigger: 'click',
template: '<div class="popover popover--topright" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
});
Then using css you can easily shift popover position:
.popover.popover--topright {
/* margin-top: 0px; // Use to change vertical position */
margin-right: 40px; /* Use to change horizontal position */
}
.popover.popover--topright .arrow {
left: 88% !important; /* fix arrow position */
}
This solution would not influence other popovers you have. Same solution can be used on tooltips as well because popover class inherit from tooltip class.
You can also use,
parent.jQuery("#testdiv").attr("style", content from form);
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then defining an array of length String[10]{} 0
While not contesting the other answers, I think the following is worthy of mentioning.
http-equiv
) notation and the “short” one are equal, whichever comes first wins;<meta>
tags;You can test by running echo 'HTTP/1.1 200 OK\r\nContent-type: text/html; charset=windows-1251\r\n\r\n\xef\xbb\xbf<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta charset="windows-1251"><title>??????</title></head><body>??????</body></html>' | nc -lp 4500
and pointing your browser at localhost:4500
. (Of course you will want to change or remove parts. The BOM part is \xef\xbb\xbf
. Be wary of the encoding of your shell.)
Please mind that it's very important that you explicitly declare the encoding. Letting browsers guess can lead to security issues.
Try PEAR's HTTP_Request2 package to easily send POST requests. Alternatively, you can use PHP's curl functions or use a PHP stream context.
HTTP_Request2 also makes it possible to mock out the server, so you can unit-test your code easily
Here's how I implemented it working from @mg1075's code. I wanted a bit more generic code so as not to have to assign classes to the modal trigger links/buttons:
Tested in Twitter Bootstrap 3.0.3.
HTML
<a href="#" data-target="#my_modal" data-toggle="modal" data-id="my_id_value">Open Modal</a>
JAVASCRIPT
$(document).ready(function() {
$('a[data-toggle=modal], button[data-toggle=modal]').click(function () {
var data_id = '';
if (typeof $(this).data('id') !== 'undefined') {
data_id = $(this).data('id');
}
$('#my_element_id').val(data_id);
})
});
You may use CString
, CStringA
, CStringW
to do automatic conversions and convert between these types. Further, you may also use CStrBuf
, CStrBufA
, CStrBufW
to get RAII pattern modifiable strings
In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.
<video controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>
We can add an external HLS js script in web application.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Your title</title>
<link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
<script src="https://unpkg.com/video.js/dist/video.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
</head>
<body>
<video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
data-setup='{}'>
<source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
</video>
<script>
var player = videojs('my_video_1');
player.play();
</script>
</body>
</html>
Super dated, but certainly good ways to accomodate this. Just wrote this up for a project and figured I'd share. Similar to some of the others, varied in style.
var ObjectListener = function(prop, value) {
if (value === undefined) value = null;
var obj = {};
obj.internal = value;
obj.watcher = (function(x) {});
obj.emit = function(fn) {
obj.watch = fn;
};
var setter = {};
setter.enumerable = true;
setter.configurable = true;
setter.set = function(x) {
obj.internal = x;
obj.watcher(x);
};
var getter = {};
getter.enumerable = true;
getter.configurable = true;
getter.get = function() {
return obj.internal;
};
return (obj,
Object.defineProperty(obj, prop, setter),
Object.defineProperty(obj, prop, getter),
obj.emit, obj);
};
user._licenseXYZ = ObjectListener(testProp);
user._licenseXYZ.emit(testLog);
function testLog() {
return function() {
return console.log([
'user._licenseXYZ.testProp was updated to ', value
].join('');
};
}
user._licenseXYZ.testProp = 123;
You could use a CASE statement, like
SELECT name
,address
,CASE WHEN a < b THEN '1'
ELSE '2' END AS one_or_two
FROM ...
It looks like you want:
public static string GetRandomBits()
Without static
, you would need an object before you can call the GetRandomBits()
method. However, since the implementation of GetRandomBits()
does not depend on the state of any Program
object, it's best to declare it static
.
three different approaches:
Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.
replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.
offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.
If you need to get quantity of selected checkboxes:
var selected = []; // initialize array
$('div#checkboxes input[type=checkbox]').each(function() {
if ($(this).is(":checked")) {
selected.push($(this));
}
});
var selectedQuantity = selected.length;
I just had the same error. After 5 minets google-ing I found that I didun't closed one shell witch were using the db. Just close it and try again ;)
I tried trim(). It works well with white spaces as well as the '\n'.
x = '\n Harden, J.\n '
trim(x)
Simply use something like the following - the string should be there already:
<?php
if(isset($_SERVER['SERVER_SOFTWARE'])){
echo $_SERVER['SERVER_SOFTWARE'];
}
?>
The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.
#
# invRegex.py
#
# Copyright 2008, Paul McGuire
#
# pyparsing script to expand a regular expression into all possible matching strings
# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation
#
__all__ = ["count","invert"]
from pyparsing import (Literal, oneOf, printables, ParserElement, Combine,
SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
Suppress, ParseResults, srange)
class CharacterRangeEmitter(object):
def __init__(self,chars):
# remove duplicate chars in character range, but preserve original order
seen = set()
self.charset = "".join( seen.add(c) or c for c in chars if c not in seen )
def __str__(self):
return '['+self.charset+']'
def __repr__(self):
return '['+self.charset+']'
def makeGenerator(self):
def genChars():
for s in self.charset:
yield s
return genChars
class OptionalEmitter(object):
def __init__(self,expr):
self.expr = expr
def makeGenerator(self):
def optionalGen():
yield ""
for s in self.expr.makeGenerator()():
yield s
return optionalGen
class DotEmitter(object):
def makeGenerator(self):
def dotGen():
for c in printables:
yield c
return dotGen
class GroupEmitter(object):
def __init__(self,exprs):
self.exprs = ParseResults(exprs)
def makeGenerator(self):
def groupGen():
def recurseList(elist):
if len(elist)==1:
for s in elist[0].makeGenerator()():
yield s
else:
for s in elist[0].makeGenerator()():
for s2 in recurseList(elist[1:]):
yield s + s2
if self.exprs:
for s in recurseList(self.exprs):
yield s
return groupGen
class AlternativeEmitter(object):
def __init__(self,exprs):
self.exprs = exprs
def makeGenerator(self):
def altGen():
for e in self.exprs:
for s in e.makeGenerator()():
yield s
return altGen
class LiteralEmitter(object):
def __init__(self,lit):
self.lit = lit
def __str__(self):
return "Lit:"+self.lit
def __repr__(self):
return "Lit:"+self.lit
def makeGenerator(self):
def litGen():
yield self.lit
return litGen
def handleRange(toks):
return CharacterRangeEmitter(srange(toks[0]))
def handleRepetition(toks):
toks=toks[0]
if toks[1] in "*+":
raise ParseFatalException("",0,"unbounded repetition operators not supported")
if toks[1] == "?":
return OptionalEmitter(toks[0])
if "count" in toks:
return GroupEmitter([toks[0]] * int(toks.count))
if "minCount" in toks:
mincount = int(toks.minCount)
maxcount = int(toks.maxCount)
optcount = maxcount - mincount
if optcount:
opt = OptionalEmitter(toks[0])
for i in range(1,optcount):
opt = OptionalEmitter(GroupEmitter([toks[0],opt]))
return GroupEmitter([toks[0]] * mincount + [opt])
else:
return [toks[0]] * mincount
def handleLiteral(toks):
lit = ""
for t in toks:
if t[0] == "\\":
if t[1] == "t":
lit += '\t'
else:
lit += t[1]
else:
lit += t
return LiteralEmitter(lit)
def handleMacro(toks):
macroChar = toks[0][1]
if macroChar == "d":
return CharacterRangeEmitter("0123456789")
elif macroChar == "w":
return CharacterRangeEmitter(srange("[A-Za-z0-9_]"))
elif macroChar == "s":
return LiteralEmitter(" ")
else:
raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")")
def handleSequence(toks):
return GroupEmitter(toks[0])
def handleDot():
return CharacterRangeEmitter(printables)
def handleAlternative(toks):
return AlternativeEmitter(toks[0])
_parser = None
def parser():
global _parser
if _parser is None:
ParserElement.setDefaultWhitespaceChars("")
lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")
reMacro = Combine("\\" + oneOf(list("dws")))
escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"
reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
reDot = Literal(".")
repetition = (
( lbrace + Word(nums).setResultsName("count") + rbrace ) |
( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
oneOf(list("*+?"))
)
reRange.setParseAction(handleRange)
reLiteral.setParseAction(handleLiteral)
reMacro.setParseAction(handleMacro)
reDot.setParseAction(handleDot)
reTerm = ( reLiteral | reRange | reMacro | reDot )
reExpr = operatorPrecedence( reTerm,
[
(repetition, 1, opAssoc.LEFT, handleRepetition),
(None, 2, opAssoc.LEFT, handleSequence),
(Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
]
)
_parser = reExpr
return _parser
def count(gen):
"""Simple function to count the number of elements returned by a generator."""
i = 0
for s in gen:
i += 1
return i
def invert(regex):
"""Call this routine as a generator to return all the strings that
match the input regular expression.
for s in invert("[A-Z]{3}\d{3}"):
print s
"""
invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()
return invReGenerator()
def main():
tests = r"""
[A-EA]
[A-D]*
[A-D]{3}
X[A-C]{3}Y
X[A-C]{3}\(
X\d
foobar\d\d
foobar{2}
foobar{2,9}
fooba[rz]{2}
(foobar){2}
([01]\d)|(2[0-5])
([01]\d\d)|(2[0-4]\d)|(25[0-5])
[A-C]{1,2}
[A-C]{0,3}
[A-C]\s[A-C]\s[A-C]
[A-C]\s?[A-C][A-C]
[A-C]\s([A-C][A-C])
[A-C]\s([A-C][A-C])?
[A-C]{2}\d{2}
@|TH[12]
@(@|TH[12])?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
(([ECMP]|HA|AK)[SD]|HS)T
[A-CV]{2}
A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
(a|b)|(x|y)
(a|b) (x|y)
""".split('\n')
for t in tests:
t = t.strip()
if not t: continue
print '-'*50
print t
try:
print count(invert(t))
for s in invert(t):
print s
except ParseFatalException,pfe:
print pfe.msg
print
continue
print
if __name__ == "__main__":
main()
If you need to know how many rows there are with "one or more NaN
s":
df.isnull().T.any().T.sum()
Or if you need to pull out these rows and examine them:
nan_rows = df[df.isnull().T.any()]
The problem here is that I don't know what is expected. With your current setup, invoking the plugin on the command line would just work:
$ mvn exec:exec [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Q3491937 [INFO] task-segment: [exec:exec] [INFO] ------------------------------------------------------------------------ [INFO] [exec:exec {execution: default-cli}] [INFO] laptop [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ ...
The global configuration
is used, the hostname
command is executed (laptop
is my hostname). In other words, the plugin works as expected.
Now, if you want a plugin to get executed as part of the build, you have to bind a goal on a specific phase. For example, to bind it on compile
:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<id>some-execution</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>hostname</executable>
</configuration>
</plugin>
And then:
$ mvn compile [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Q3491937 [INFO] task-segment: [compile] [INFO] ------------------------------------------------------------------------ [INFO] [resources:resources {execution: default-resources}] [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory /home/pascal/Projects/Q3491937/src/main/resources [INFO] [compiler:compile {execution: default-compile}] [INFO] Nothing to compile - all classes are up to date [INFO] [exec:exec {execution: some-execution}] [INFO] laptop [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ ...
Note that you can specify a configuration
inside an execution
.
This works fine
<?xml version="1.0" encoding="UTF-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1600"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="358" />
To reverse rotate:
<?xml version="1.0" encoding="UTF-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1600"
android:fromDegrees="358"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="0" />
You may have 0 to many <img>
tags inside of your <div>
.
To find an element, use a .find()
.
To keep your code safe, use a .each()
.
Using .find()
and .each()
together prevents null reference errors in the case of 0 <img>
elements while also allowing for handling of multiple <img>
elements.
// Set the click handler on your div_x000D_
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {_x000D_
_x000D_
// Find the image using.find() and .each()_x000D_
$(this).find("img").each(function() {_x000D_
_x000D_
var img = this; // "this" is, now, scoped to the image element_x000D_
_x000D_
// Do something with the image_x000D_
$(this).animate({_x000D_
width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"_x000D_
}, 500);_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
#mydiv {_x000D_
text-align: center;_x000D_
vertical-align: middle;_x000D_
background-color: #000000;_x000D_
cursor: pointer;_x000D_
padding: 50px;_x000D_
_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="mydiv">_x000D_
<img src="" width="100" height="100"/>_x000D_
</div>
_x000D_
I eventually figured out an easy way to do it:
https://``t.co/tQM43ftXyM
). Copy this URL and paste it in a new browser tab.https://twitter.com/UserName/status/828267001496784896/video/1
This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!
If the external configuration file is also valid batch file, you can just use:
call externalconfig.bat
inside your script. Try creating following a.bat:
@echo off
call b.bat
echo %MYVAR%
and b.bat:
set MYVAR=test
Running a.bat should generate output:
test
In Loops, I always prefer to use the Cells
class, using the R1C1 reference method, like this:
Cells(rr, col).Formula = ...
This allows me to quickly and easily loop over a Range of cells easily:
Dim r As Long
Dim c As Long
c = GetTargetColumn() ' Or you could just set this manually, like: c = 1
With Sheet1 ' <-- You should always qualify a range with a sheet!
For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)
' Here we're looping over all the cells in rows 1 to 10, in Column "c"
.Cells(r, c).Value = MyListOfStuff(r)
'---- or ----
'...to easily copy from one place to another (even with an offset of rows and columns)
.Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value
Next r
End With
Wouldn't:
z <- df[df$x > quantile(df$x, .25) - 1.5*IQR(df$x) &
df$x < quantile(df$x, .75) + 1.5*IQR(df$x), ] #rows
accomplish this task quite easily?
You can start the emulator with the command -avd Adfmf -http-proxy http://SYSTEM_IP:PORT
.
I used HTTP Analyzer, but it should work for anything else. More details can be found here:
http://stick2code.blogspot.in/2014/04/intercept-http-requests-sent-from-app.html
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
You need to place ScrollView as the first child of Layout file and now put your linearlayout inside it. Now, android will decide on the basis of content and device size available whether to show a scrollable or not.
Make sure linearlayout has no sibling because ScrollView can not have more than one child.
/etc/services
is only advisory, it's a listing of well-known ports. It doesn't mean that anything is actually running on that port or that the named service will run on that port.
In PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433.
You can see what is actually running using the netstat
tool (available on OS X, Windows, and Linux, with command line syntax varying across all three).
This is further complicated on Mac OS X systems by the horrible mess of different PostgreSQL packages - Apple's ancient version of PostgreSQL built in to the OS, Postgres.app, Homebrew, Macports, the EnterpriseDB installer, etc etc.
What ends up happening is that the user installs Pg and starts a server from one packaging, but uses the psql
and libpq
client from a different packaging. Typically this occurs when they're running Postgres.app or homebrew Pg and connecting with the psql
that shipped with the OS. Not only do these sometimes have different default ports, but the Pg that shipped with Mac OS X has a different default unix socket path, so even if the server is running on the same port it won't be listening to the same unix socket.
Most Mac users work around this by just using tcp/ip with psql -h localhost
. You can also specify a port if required, eg psql -h localhost -p 5433
. You might have multiple PostgreSQL instances running so make sure you're connecting to the right one by using select version()
and SHOW data_directory;
.
You can also specify a unix socket directory; check the unix_socket_directories
setting of the PostgreSQL instance you wish to connect to and specify that with psql -h
, e.g.psql -h /tmp
.
A cleaner solution is to correct your system PATH
so that the psql
and libpq
associated with the PostgreSQL you are actually running is what's found first on the PATH
. The details of that depend on your Mac OS X version and which Pg packages you have installed. I don't use Mac and can't offer much more detail on that side without spending more time than is currently available.
For people who have found this post from Google almost 6 years in the future (and beyond!), you may run into this problem with Apache 2 and PHP 7 while also using the UserDir
module.
Another possible cause of this problem could be that you are trying to run the script in a "user directory" from the the UserDir
module. Running PHP scripts in user directories is disabled by default. You will run into this problem if the script is in the public_html
directory in your home folder and you are trying to access it from http://localhost/~your_username
.
To fix this, open up /etc/apache2/mods-enabled/php7.2.conf
. You must comment or delete the tag block at the bottom that reads
<IfModule mod_userdir.c>
<Directory /home/*/public_html>
php_admin_flag engine Off
</Directory>
</IfModule>
According to the Apple docs:
As of iOS 8, the presence of a NSLocationWhenInUseUsageDescription
or a NSLocationAlwaysUsageDescription
key value in your app's Info.plist file is required. It's then also necessary to request permission from the user prior to registering for location updates, either by calling [self.myLocationManager requestWhenInUseAuthorization]
or [self.myLocationManager requestAlwaysAuthorization]
depending on your need. The string you entered into the Info.plist will then be displayed in the ensuing dialog.
If the user grants permission, it's business as usual. If they deny permission, then the delegate is not informed of location updates.
Use Assembly.GetTypes
. For example:
Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
Console.WriteLine(type.FullName);
}
If you want to never expire a session use 0
or negative value -1
.
<session-config>
<session-timeout>0</session-timeout>
</session-config>
or mention 1440
it indicates 1440 minutes
[24hours * 60 minutes
]
<session-config>
<session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>
Session will be expire after 24hours
.
If all the above doesn't work, especially if having big size dependency (like my case), both building and loading were taking a minimum of 15 seconds, so it seems the delay gave a false message "Invalid hook call." So what you can do is give some time to ensure the build is completed before testing.
Using the jQuery timer will also allow you to have a name associated with the timers that are attached to the object. So you could attach several timers to an object and stop any one of them.
$("#myid").oneTime(1000, "mytimer1" function() {
$("#something").hide();
}).oneTime(2000, "mytimer2" function() {
$("#somethingelse").show();
});
$("#myid").stopTime("mytimer2");
The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.
This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.
@print {
@page :footer {
display: none
}
@page :header {
display: none
}
}
I'd just like to add a very simple example for testing this functionality on Windows:
Create the following two files and save them to a web directory:
foreground.php:
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
echo "<pre>loading page</pre>";
function run_background_process()
{
file_put_contents("testprocesses.php","foreground start time = " . time() . "\n");
echo "<pre> foreground start time = " . time() . "</pre>";
// output from the command must be redirected to a file or another output stream
// http://ca.php.net/manual/en/function.exec.php
exec("php background.php > testoutput.php 2>&1 & echo $!", $output);
echo "<pre> foreground end time = " . time() . "</pre>";
file_put_contents("testprocesses.php","foreground end time = " . time() . "\n", FILE_APPEND);
return $output;
}
echo "<pre>calling run_background_process</pre>";
$output = run_background_process();
echo "<pre>output = "; print_r($output); echo "</pre>";
echo "<pre>end of page</pre>";
?>
background.php:
<?
file_put_contents("testprocesses.php","background start time = " . time() . "\n", FILE_APPEND);
sleep(10);
file_put_contents("testprocesses.php","background end time = " . time() . "\n", FILE_APPEND);
?>
Give IUSR permission to write to the directory in which you created the above files
Give IUSR permission to READ and EXECUTE C:\Windows\System32\cmd.exe
Hit foreground.php from a web browser
The following should be rendered to the browser w/the current timestamps and local resource # in the output array:
loading page
calling run_background_process
foreground start time = 1266003600
foreground end time = 1266003600
output = Array
(
[0] => 15010
)
end of page
You should see testoutput.php in the same directory as the above files were saved, and it should be empty
You should see testprocesses.php in the same directory as the above files were saved, and it should contain the following text w/the current timestamps:
foreground start time = 1266003600
foreground end time = 1266003600
background start time = 1266003600
background end time = 1266003610
If the question isn't just "how to access an integer form of the timedelta?" but "how to convert the timedelta column in the dataframe to an int?" the answer might be a little different. In addition to the .dt.days
accessor you need either df.astype
or pd.to_numeric
Either of these options should help:
df['tdColumn'] = pd.to_numeric(df['tdColumn'].dt.days, downcast='integer')
or
df['tdColumn'] = df['tdColumn'].dt.days.astype('int16')
This is very useful for custom ArrayAdapter
using. It is some kind of optimization. There setTag
used as reference to object that references on some parts of layout (that displaying in ListView
) instead of findViewById
.
static class ViewHolder {
TextView tvPost;
TextView tvDate;
ImageView thumb;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = myContext.getLayoutInflater();
convertView = inflater.inflate(R.layout.postitem, null);
ViewHolder vh = new ViewHolder();
vh.tvPost = (TextView)convertView.findViewById(R.id.postTitleLabel);
vh.tvDate = (TextView)convertView.findViewById(R.id.postDateLabel);
vh.thumb = (ImageView)convertView.findViewById(R.id.postThumb);
convertView.setTag(vh);
}
....................
}
You never give any value to your strings in main
so they are empty, and thus obviously the function returns an empty string.
Replace:
string str1, str2, str3;
with:
string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";
Also, you have several problems in your replaceSubstring
function:
int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
std::string::find
returns a std::string::size_type
(aka. size_t
) not an int
. Two differences: size_t
is unsigned, and it's not necessarily the same size as an int
depending on your platform (eg. on 64 bits Linux or Windows size_t
is unsigned 64 bits while int
is signed 32 bits).s2
is not part of s1
? I'll leave it up to you to find how to fix that. Hint: std::string::npos
;)As of Laravel 5.2, the documentation states that these kinds of event handlers should be registered in the AppServiceProvider:
<?php
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::deleting(function ($user) {
$user->photos()->delete();
});
}
I even suppose to move them to separate classes instead of closures for better application structure.
You can do a serialization-based deep clone using org.apache.commons.lang3.SerializationUtils.clone(T)
in Apache Commons Lang, but be careful—the performance is abysmal.
In general, it is best practice to write your own clone methods for each class of an object in the object graph needing cloning.
You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.
function outer() {
return (function inside(){
console.log("Inside inside function");
});
}
outer()();
Or
function outer2() {
let inside = function inside(){
console.log("Inside inside");
};
return inside;
}
outer2()();
ViewPager.setOnPageChangeListener
is deprecated now. You now need to use ViewPager.addOnPageChangeListener
instead.
for example,
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
The short answer is that scripting is unsupported in emails.
This is hardly surprising, given the obvious security risks involved with a script running inside an application that has all that personal information stored in it.
Webmail clients are mostly running the interface in JavaScript and are not keen on your email interfering with that, and desktop client filters often consider JavaScript to be an indicator of spam or phishing emails. Even in the cases where it might run, there really is little benefit to scripting in emails.
Keep your emails as straight HTML and CSS, and avoid the hassle. Here is what you can do in html emails: https://www.campaignmonitor.com/guides/coding/technologies/
Well its very simple in controller you have somthing like this:
-- Controller
ViewBag.Profile_Id = new SelectList(db.Profiles, "Id", "Name", model.Profile_Id);
--View (Option A)
@Html.DropDownList("Profile_Id")
--View (Option B) --> Send a null value to the list
@Html.DropDownList("Profile_Id", null, "-- Choose --", new { @class = "input-large" })
What works for me is using a specific color instead of the real ability of .png to represent transparency.
So, what you can do is take your background image, and paint the transparent area with a specific color (Magenta always seemed appropriate to me...).
Set the image as the Form's BackgrounImage
property, and set the color as the Form's TransparencyKey
. No need for changes in the Control's style, and no need for BackColor.
I've tryed it right now and it worked for me...
FIXED IT HAD THE EXACT ERROR, Just add this tools:replace="android:icon,android:theme"
into your application tag in your manifest, it works just fine,
import itertools
import collections
dictA = {'a':1, 'b':2, 'c':3}
dictB = {'b':3, 'c':4, 'd':5}
new_dict = collections.defaultdict(int)
# use dict.items() instead of dict.iteritems() for Python3
for k, v in itertools.chain(dictA.iteritems(), dictB.iteritems()):
new_dict[k] += v
print dict(new_dict)
# OUTPUT
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
OR
Alternative you can use Counter as @Martijn has mentioned above.
I would recommend you to have another class called File.
public class File
{
private string filename;
public File(string filename)
{
this.filename= filename;
}
public void download()
{
// download code using filename
}
}
And in your thread creation code, you instantiate a new file:
string filename = "my_file_name";
myFile = new File(filename);
ThreadStart threadDelegate = new ThreadStart(myFile.download);
Thread newThread = new Thread(threadDelegate);
I wanted to add my solution since the accepted one didn't quite work for me.
I needed to add a directive but also keep mine on the element.
In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.
angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
return {
priority: 1001,
controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
// controller code here
}],
compile: function(element, attributes){
var compile = false;
//check to see if the target directive was already added
if(!element.attr('ng-style')){
//add the target directive
element.attr('ng-style', "{'width':'200px'}");
compile = true;
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
if(compile){
$compile(iElement)(scope);
}
}
};
}
};
}]);
Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.
Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.
public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
List<Type> list = new List<Type>();
IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
while (enumerator.MoveNext()) {
try {
Type[] types = ((Assembly) enumerator.Current).GetTypes();
if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
IEnumerator enumerator2 = types.GetEnumerator();
while (enumerator2.MoveNext()) {
Type current = (Type) enumerator2.Current;
if (type.IsInterface) {
if (current.GetInterface(type.FullName) != null) {
list.Add(current);
}
} else if (current.IsSubclassOf(type)) {
list.Add(current);
}
}
}
} catch {
}
}
return list;
}
It's not pretty, I'll admit.
Easiest way to check for the existence of a constraint (and then do something such as drop it if it exists) is to use the OBJECT_ID() function...
IF OBJECT_ID('dbo.[CK_ConstraintName]', 'C') IS NOT NULL
ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
OBJECT_ID can be used without the second parameter ('C' for check constraints only) and that may also work, but if your constraint name matches the name of other objects in the database you may get unexpected results.
IF OBJECT_ID('dbo.[CK_ConstraintName]') IS NOT NULL
ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
OBJECT_ID can also be used with other "constraints" such as Foreign Key constraints or Primary Key constraints, etc. For best results, always include the appropriate object type as the second parameter for the OBJECT_ID function:
Constraint Object Types:
Also note that the schema is often required. The schema of constraints generally takes the schema of the parent table.
Failure to put your constraints (or whatever you are checking) in brackets when using this method may also cause a false negative -- if your object uses unusual characters (such as a .), the brackets are required.
According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:
So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.
Zookeeper is one of the best open source server and service that helps to reliably coordinates distributed processes. Zookeeper is a CP system (Refer CAP Theorem) that provides Consistency and Partition tolerance. Replication of Zookeeper state across all the nodes makes it an eventually consistent distributed service.
Moreover, any newly elected leader will update its followers with missing proposals or with a snapshot of the state, if the followers have many proposals missing.
Zookeeper also provides an API that is very easy to use. This blog post, Zookeeper Java API examples, has some examples if you are looking for examples.
So where do we use this? If your distributed service needs a centralized, reliable and consistent configuration management, locks, queues etc, you will find Zookeeper a reliable choice.
If you want to know the number of days (if any), the number of hours (if any), minutues (if any) and seconds, you can do the following:
$previousTimeStamp = strtotime("2011/07/01 21:12:34");
$lastTimeStamp = strtotime("2013/09/17 12:34:11");
$menos=$lastTimeStamp-$previousTimeStamp;
$mins=$menos/60;
if($mins<1){
$showing= $menos . " seconds ago";
}
else{
$minsfinal=floor($mins);
$secondsfinal=$menos-($minsfinal*60);
$hours=$minsfinal/60;
if($hours<1){
$showing= $minsfinal . " minutes and " . $secondsfinal. " seconds ago";
}
else{
$hoursfinal=floor($hours);
$minssuperfinal=$minsfinal-($hoursfinal*60);
$days=$hoursfinal/24;
if($days<1){
$showing= $hoursfinal . "hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";
}
else{
$daysfinal=floor($days);
$hourssuperfinal=$hoursfinal-($daysfinal*24);
$showing= $daysfinal. "days, " .$hourssuperfinal . " hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";
}}}
echo $showing;
You could use the same logic if you want to add months and years.
sys.argv
is a list.
This list is created by your command line, it's a list of your command line arguments.
For example:
in your command line you input something like this,
python3.2 file.py something
sys.argv
will become a list ['file.py', 'something']
In this case sys.argv[1] = 'something'
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
More simply in one line:
proxy=192.168.2.1:8080;curl -v example.com
eg. $proxy=192.168.2.1:8080;curl -v example.com
xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.
In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.
With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.
I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.
You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.
Sub deleteCol()
On Error Resume Next
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer
Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
End If
Next i
End Sub
With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.
EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare)
change the "1" in Cells(1, i)
to whatever row your headers are in.
EDIT 2: Changed the For
section of the code to account for completely empty columns.
The other option to try is a straightforward
<img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>
i.e. without {} but instead giving the direct image path
If you are in Jupyter notebook, you could run the following code to interactively display the dataframe in a well formatted table.
This answer builds on the to_html('temp.html') answer above, but instead of creating a file displays the well formatted table directly in the notebook:
from IPython.display import display, HTML
display(HTML(df.to_html()))
Credit for this code due to example at: Show DataFrame as table in iPython Notebook
In express 4.0 they got it right :)
res.sendStatus(statusCode)
// Sets the response HTTP status code to statusCode and send its string representation as the response body.
res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
//If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.
res.sendStatus(2000); // equivalent to res.status(2000).send('2000')
I've seen this error a few times too, and I've always been able to solve it by correctly identifying the project's module settings. In IntelliJ, right-click on the top level project -> "Open Module Settings". This should open up a window with the entire project structure and content identified as "Source Folders", "Test Source Folders", etc. Make sure these are correctly set. For the "Source Folders", ensure that the folder is your src/ or src/java (or whatever your source language is), as the case may be
You should use this:
>mysql -u user -h 192.168.1.2 -P 3306 -ppassword
or this:
>mysql -u user -h 192.168.1.2 -ppassword
...because 3306 is a default port number.
For example,
package main
import "fmt"
func main() {
type Map1 map[string]interface{}
type Map2 map[string]int
m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
//m = map[foo:map[first: 1] boo: map[second: 2]]
fmt.Println("m:", m)
for k, v := range m {
fmt.Println("k:", k, "v:", v)
}
}
Output:
m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]
This sort of approach should work.
var plugin_exists = true;
try {
// some code that requires that plugin here
} catch(err) {
plugin_exists = false;
}
Posting it from my project.
<select name="parent" id="parent"><option value="0">None</option>
<?php
$select="select=selected";
$allparent=mysql_query("select * from tbl_page_content where parent='0'");
while($parent=mysql_fetch_array($allparent))
{?>
<option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
<?php
}
?></select>
def sort_np_array(x, column=None, flip=False):
x = x[np.argsort(x[:, column])]
if flip:
x = np.flip(x, axis=0)
return x
Array in the original question:
a = np.array([[9, 2, 3],
[4, 5, 6],
[7, 0, 5]])
The result of the sort_np_array
function as expected by the author of the question:
sort_np_array(a, column=1, flip=False)
[2]: array([[7, 0, 5],
[9, 2, 3],
[4, 5, 6]])
@Schildmeijer is largely right, however port 7001 is still used when using TLS Encrypted Internode communication
So my complete list would be for current versions of Cassandra:
You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.
$.get('http://someurl.com',function(data,status) {
...parse the data...
},'html');
If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.
Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.
This will list Everything (including sub directories) from the directory you specify, in order, and with the attributes. I have spent days looking for something to do this, and I took parts from this entire discussion, and a little of my own, and put it together. ENJOY!!
#!/usr/bin/perl --
print qq~Content-type: text/html\n\n~;
print qq~<font face="arial" size="2">~;
use File::Find;
# find( \&wanted_tom, '/home/thomas/public_html'); # if you want just one website, uncomment this, and comment out the next line
find( \&wanted_tom, '/home');
exit;
sub wanted_tom {
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat ($_);
$mode = (stat($_))[2];
$mode = substr(sprintf("%03lo", $mode), -3);
if (-d $File::Find::name) {
print "<br><b>--DIR $File::Find::name --ATTR:$mode</b><br>";
} else {
print "$File::Find::name --ATTR:$mode<br>";
}
return;
}
My suggestion would be to use Unit Tests.
In your application do the following switches in Program.cs
:
#if DEBUG
public class Program
#else
class Program
#endif
and the same for static Main(string[] args)
.
Or alternatively use Friend Assemblies by adding
[assembly: InternalsVisibleTo("TestAssembly")]
to your AssemblyInfo.cs
.
Then create a unit test project and a test that looks a bit like so:
[TestClass]
public class TestApplication
{
[TestMethod]
public void TestMyArgument()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw); // this makes any Console.Writes etc go to sw
Program.Main(new[] { "argument" });
var result = sw.ToString();
Assert.AreEqual("expected", result);
}
}
}
This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.
It took me a while to find the answer to this question. Most people seem to be suggesting regex solutions. I strongly prefer to use code that is tried and tested as opposed to regex that I or someone else thought up on the fly.
I use the parseUri library available here: http://stevenlevithan.com/demo/parseuri/js/
It allows you to do exactly what you are asking for:
var uri = 'http://localhost/search.php?year=2008';
var year = uri.queryKey['year'];
// year = '2008'
I solved the problem by dropping the table and restoring it from backup.
Below are provided steps to fix your issue.
Using more_itertools.with_iter
, it is possible to open, read, close and assign an equivalent output
in one line (excluding the import statement):
import more_itertools as mit
output = "".join(line for line in mit.with_iter(open("pagehead.section.htm", "r")))
Although possible, I would look for another approach other than assigning the contents of a file to a variable, i.e. lazy iteration - this can be done using a traditional with
block or in the example above by removing join()
and iterating output
.
Use vanilla js, example
document.cookie = `referral_key=hello;max-age=604800;domain=example.com`
Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
if you want to fill all the column:
update 'column' set 'info' where keyID!=0;
Jackson has to know in what order to pass fields from a JSON object to the constructor. It is not possible to access parameter names in Java using reflection - that's why you have to repeat this information in annotations.
The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.
Create a list with as many list elements as you want. Then enclose the list in a div, setting style=column-width and style=column-gap, to match the information in your list elements. Do not set style=columns. Totally responsive list that adapts to screen size. No plugins required.
$('<div/>').text('This is fun & stuff').html(); // "This is fun & stuff"
Source: http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
LocalDate maxDate = dates.stream()
.max( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
LocalDate minDate = dates.stream()
.min( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
in Eike Thies's response above, if we use underscore.js, filter could be simplified to :
var app = angular.module('myApp', []).filter('object2Array', function() {
return function(input) {
return _.toArray(input);
}
});
To hide arrows and cross in a "time" input :
#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
-webkit-appearance: none;
margin: 0;
}
In case you need to nest more than one null coalescing operation such as:
model?.data()?.first()
This is not a problem easily solved with or
. It also cannot be solved with .get()
which requires a dictionary type or similar (and cannot be nested anyway) or getattr()
which will throw an exception when NoneType doesn't have the attribute.
The relevant pip considering adding null coalescing to the language is PEP 505 and the discussion relevant to the document is in the python-ideas thread.
Look for "Windows x86", it's the 32 bit version.
No. We cannot alter the constraint, only thing we can do is drop and recreate it
ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]
Foreign Key Constraint
Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade
Primary Key constraint
Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)
Open preferences windows (Command key + "," on Mac):
1.Tools
2.Python Integrated Tools
3.Default test runner
The default scope is "default". It's weird--see these references for more info.
Change it to this:
var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
This is a regular expression literal that is passed the i
flag which means to be case insensitive.
Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.
So I found my own solution to this problem in the end.
After searching through Microsoft documentation I managed to find a new IE11 only style msTextCombineHorizontal
In my test, I check for IE10 styles and if they are a positive match, then I check for the IE11 only style. If I find it, then it's IE11+, if I don't, then it's IE10.
Code Example: Detect IE10 and IE11 by CSS Capability Testing (JSFiddle)
I will update the code example with more styles when I discover them.
NOTE: This will almost certainly identify IE12 and IE13 as "IE11", as those styles will probably carry forward. I will add further tests as new versions roll out, and hopefully be able to rely again on Modernizr.
I'm using this test for fallback behavior. The fallback behavior is just less glamorous styling, it doesn't have reduced functionality.
TO answer your question: no, MySQL does not support Table-typed variables in the same manner that SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) provides. Oracle provides similar functionality but calls them Cursor types instead of table types (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm).
Depending your needs you can simulate table/cursor-typed variables in MySQL using temporary tables in a manner similar to what is provided by both Oracle and SQL Server.
However, there is an important difference between the temporary table approach and the table/cursor-typed variable approach and it has a lot of performance implications (this is the reason why Oracle and SQL Server provide this functionality over and above what is provided with temporary tables).
Specifically: table/cursor-typed variables allow the client to collate multiple rows of data on the client side and send them up to the server as input to a stored procedure or prepared statement. What this eliminates is the overhead of sending up each individual row and instead pay that overhead once for a batch of rows. This can have a significant impact on overall performance when you are trying to import larger quantities of data.
A possible work-around:
What you may want to try is creating a temporary table and then using a LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command to stream the data into the temporary table. You could then pass them name of the temporary table into your stored procedure. This will still result in two calls to the database server, but if you are moving enough rows there may be a savings there. Of course, this is really only beneficial if you are doing some kind of logic inside the stored procedure as you update the target table. If not, you may just want to LOAD DATA directly into the target table.
$('.cw2').change(function () {
if ($('input.cw2').filter(':checked').length >= 1) {
$('input.cw2').not(this).prop('checked', false);
}
});
$('td, input').prop(function (){
$(this).css({ 'background-color': '#DFD8D1' });
$(this).addClass('changed');
});
Use Array.BinarySearch(array,obj)
for finding the given object in array or not.
Example:
if (Array.BinarySearch(str, i) > -1)` ? true --exists
false --not exists
What I did was:
set a new environment variable in the top user section.
VARIABLE NAME: JAVA_HOME
VARIABLE VALUE: set it to the installation directory of your most recent JDK.
For me it was, C:\Program Files\Java\jdk1.7.0_13
. Run SDK Manager as administrator at least once. I use windows 7. This method worked for me after a lot of research.
What I dont understand is when using 'where java' in the command prompt it still references C:\Windows\System32\java.exe
. My SDK Manager now opens when I need it so I solved my problem.
using str.replace(regex, $1);
:
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
if (str.match(regex)) {
str = str.replace(regex, "$1" + "1" + "$2");
}
Edit: adaptation regarding the comment
None of these gave me a satisfactory answer so in the end I got what I wanted with the key
prop, useRef and some random id generator like shortid
.
Basically, I wanted some chat application to play itself out the first time someone opens the app. So, I needed full control over when and what the answers are updated with the ease of async await.
Example code:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// ... your JSX functional component, import shortid somewhere
const [render, rerender] = useState(shortid.generate())
const messageList = useRef([
new Message({id: 1, message: "Hi, let's get started!"})
])
useEffect(()=>{
await sleep(500)
messageList.current.push(new Message({id: 1, message: "What's your name?"}))
// ... more stuff
// now trigger the update
rerender(shortid.generate())
}, [])
// only the component with the right render key will update itself, the others will stay as is and won't rerender.
return <div key={render}>{messageList.current}</div>
In fact this also allowed me to roll something like a chat message with a rolling .
const waitChat = async (ms) => {
let text = "."
for (let i = 0; i < ms; i += 200) {
if (messageList.current[messageList.current.length - 1].id === 100) {
messageList.current = messageList.current.filter(({id}) => id !== 100)
}
messageList.current.push(new Message({
id: 100,
message: text
}))
if (text.length === 3) {
text = "."
} else {
text += "."
}
rerender(shortid.generate())
await sleep(200)
}
if (messageList.current[messageList.current.length - 1].id === 100) {
messageList.current = messageList.current.filter(({id}) => id !== 100)
}
}
Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))
SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));
See Math.Pow. The function takes a value and raises it to a specified power:
Math.Pow(100.00, 3.00); // 100.00 ^ 3.00
When constructing a BigInteger with a string, the string must be formatted as a decimal number. You cannot use letters, unless you specify a radix in the second argument, you can specify up to 36 in the radix. 36 will give you alphanumeric characters only [0-9,a-z], so if you use this, you will have no formatting. You can create: new BigInteger("ihavenospaces", 36) Then to convert back, use a .toString(36)
BUT TO KEEP FORMATTING: Use the byte[] method that a couple people mentioned. That will pack the data with formatting into the smallest size, and allow you to keep track of number of bytes easily
That should be perfect for an RSA public key crypto system example program, assuming you keep the number of bytes in the message smaller than the number of bytes of PQ
(I realize this thread is old)
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
Use the function removeAtIndex(i: String.Index) -> Character
:
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
You can either use a double backslash each time
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
or use the @ symbol
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
I've provide an example not sure if this is what you're after.
var completionHandler: (_ value: Float) -> ()
func printFloat(value: Float) {
print(value)
}
completionHandler = printFloat
completionHandler(5)
It simply prints 5 using the completionHandler
variable declared.
I prefer to use the FindItem method and use the value path for locating the item. Make sure your PathSeparator property on the menu matches what you're using in FindItem parameter.
protected void Page_Load(object sender, EventArgs e)
{
// remove manage user accounts menu item for non-admin users.
if (!Page.User.IsInRole("Admin"))
{
MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
item.Parent.ChildItems.Remove(item);
}
}
I used the solution Janusz posted, but I added padding to the last View since the top part of my layout was a ScrollView.
The ScrollView will be partly hidden as it grows with content. Using android:paddingBottom
on the last View helps show all the content in the ScrollView.
Basic qustion if you are using generics in your base control. If yes:
lets say we have control:
public class MyComboDropDown : ComboDropDownComon<MyType>
{
public MyComboDropDown() { }
}
MyComboDropDown will not allow to open designer on it and will be not shown in Toolbox. Why? Because base control is not already compiled - when MyComboDropDown is complied. You can modify to this:
public class MyComboDropDown : MyComboDropDownBase
{
public MyComboDropDown() { }
}
public class MyComboDropDownBase : ComboDropDownComon<MyType>
{
}
Than after rebuild, and reset toolbox it should be able to see MyComboDropDown in designer and also in Toolbox
Need to kill a Node.js server, and you don't have any other Node processes running, you can tell your machine to kill all processes named node.exe
. That would look like this:
taskkill /im node.exe
And if the processes still persist, you can force the processes to terminate by adding the /f
flag:
taskkill /f /im node.exe
If you need more fine-grained control and need to only kill a server that is running on a specific port, you can use netstat
to find the process ID, then send a kill signal to it. So in your case, where the port is 8080
, you could run the following:
C:\>netstat -ano | find "LISTENING" | find "8080"
The fifth column of the output is the process ID:
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 14828
TCP [::]:8080 [::]:0 LISTENING 14828
You could then kill the process with taskkill /pid 14828
. If the process refuses to exit, then just add the /f
(force) parameter to the command.
The process is almost identical. You could either kill all Node processes running on the machine (use -$SIGNAL
if SIGKILL
is insufficient):
killall node
Or also using netstat
, you can find the PID of a process listening on a port:
$ netstat -nlp | grep :8080
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 1073/node
The process ID in this case is the number before the process name in the sixth column, which you could then pass to the kill
command:
$ kill 1073
If the process refuses to exit, then just use the -9
flag, which is a SIGTERM
and cannot be ignored:
$ kill -9 1073
Encapsulation is important in any OO language, popularity has nothing to do with it. In dynamically typed languages, like PHP, it is especially useful because there is little ways to ensure a property is of a specific type without using setters.
In PHP, this works:
class Foo {
public $bar; // should be an integer
}
$foo = new Foo;
$foo->bar = "string";
In Java, it doesn't:
class Foo {
public int bar;
}
Foo myFoo = new Foo();
myFoo.bar = "string"; // error
Using magic methods (__get
and __set
) also works, but only when accessing a property that has lower visibility than the current scope can access. It can easily give you headaches when trying to debug, if it is not used properly.
np.newaxis
?The np.newaxis
is just an alias for the Python constant None
, which means that wherever you use np.newaxis
you could also use None
:
>>> np.newaxis is None
True
It's just more descriptive if you read code that uses np.newaxis
instead of None
.
np.newaxis
?The np.newaxis
is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis
represents where I want to add dimensions.
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)
In the first example I use all elements from the first dimension and add a second dimension:
>>> a[:, np.newaxis]
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
>>> a[:, np.newaxis].shape
(10, 1)
The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:
>>> a[np.newaxis, :] # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)
Similarly you can use multiple np.newaxis
to add multiple dimensions:
>>> a[np.newaxis, :, np.newaxis] # note the 3 [] pairs in the output
array([[[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)
np.newaxis
?There is another very similar functionality in NumPy: np.expand_dims
, which can also be used to insert one dimension:
>>> np.expand_dims(a, 1) # like a[:, np.newaxis]
>>> np.expand_dims(a, 0) # like a[np.newaxis, :]
But given that it just inserts 1
s in the shape
you could also reshape
the array to add these dimensions:
>>> a.reshape(a.shape + (1,)) # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape) # like a[np.newaxis, :]
Most of the times np.newaxis
is the easiest way to add dimensions, but it's good to know the alternatives.
np.newaxis
?In several contexts is adding dimensions useful:
If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow
to display a 1D array.
If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]
. This works because NumPy operations broadcast starting with the last dimension 1.
To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.
1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis
:
>>> a = np.array([0.0, 10.0, 20.0, 30.0]) >>> b = np.array([1.0, 2.0, 3.0]) >>> a[:, np.newaxis] + b array([[ 1., 2., 3.], [ 11., 12., 13.], [ 21., 22., 23.], [ 31., 32., 33.]])
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
The next approach work to me with Visual Studio 2013 Update 4 1- From Solution Explorer right click on References then select add references 2- Assemblies > Framework > System.Data.OracleClient > OK and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(@"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.
'Y' and 'N' also maps nicely when using (N)Hibernate.
It turns out it is because there was a mismatch between the postgre SQL version between my local and the server, installing the same version of PostgreSQL in my computer fixed the issue. Thanks!
I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.
select CONVERT(bigint,'60') as seconds
and it returns
60
This is implementation of methods after decompiling.
public static bool IsNullOrEmpty(String value)
{
return (value == null || value.Length == 0);
}
public static bool IsNullOrWhiteSpace(String value)
{
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
So it is obvious that IsNullOrWhiteSpace method also checks if value that is being passed contain white spaces.
Whitespaces refer : https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
That can be achieve in plain LaTeX without any specific package.
\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
\left\{
\begin{array}{l}
0\\
1
\end{array}
\right.
\end{math}
\end{document}
This code produces something which looks what you seems to need.
The same example as in the @Tombart can be obtained with similar code.
\documentclass{article}
\begin{document}
\begin{math}
f(x)=\left\{
\begin{array}{ll}
1, & \mbox{if $x<0$}.\\
0, & \mbox{otherwise}.
\end{array}
\right.
\end{math}
\end{document}
This code produces very similar results.
Here is another way to change timezone in datetime format (I know I wasted my energy on this but I didn't see this page so I don't know how) without min. and sec. cause I don't need it for my project:
def change_time_zone(year, month, day, hour):
hour = hour + 7 #<-- difference
if hour >= 24:
difference = hour - 24
hour = difference
day += 1
long_months = [1, 3, 5, 7, 8, 10, 12]
short_months = [4, 6, 9, 11]
if month in short_months:
if day >= 30:
day = 1
month += 1
if month > 12:
year += 1
elif month in long_months:
if day >= 31:
day = 1
month += 1
if month > 12:
year += 1
elif month == 2:
if not year%4==0:
if day >= 29:
day = 1
month += 1
if month > 12:
year += 1
else:
if day >= 28:
day = 1
month += 1
if month > 12:
year += 1
return datetime(int(year), int(month), int(day), int(hour), 00)
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
Current route properties are present in this.$route
, this.$router
is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query
A small addition to the answers already posted, here's a Venn's diagram to sum up the theory (from Prateek Joshi's beautiful explanation):
And an example (also from Prateek's website):
Class.forName(nameString).newInstance();
You can assign a variable inside of if
statement, but you must declare it first
The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.
First you define the type like this:
CREATE TYPE UserList AS TABLE ( UserID INT );
Then you use that type in the stored procedure:
create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)
So before you call that stored procedure, you fill a table variable:
DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)
And finally call the SP:
EXEC dbo.get_user_names @UL, @username OUTPUT;
I think, it should be like this:
class foo():
input = get_input(__qualname__)
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('ddd');
console.log(weekDayName);
Result: Wed
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
Result: Wednesday