Simplest way to replace (all files, directory, recursive)
find . -type f -not -path '*/\.*' -exec sed -i 's/foo/bar/g' {} +
Note: Sometimes you might need to ignore some hidden files i.e. .git
, you can use above command.
If you want to include hidden files use,
find . -type f -exec sed -i 's/foo/bar/g' {} +
In both case the string foo
will be replaced with new string bar
Please check: http://man7.org/linux/man-pages/man5/proc.5.html
address perms offset dev inode pathname
00400000-00452000 r-xp 00000000 08:02 173521 /usr/bin/dbus-daemon
The address field is the address space in the process that the mapping occupies.
The perms field is a set of permissions:
r = read
w = write
x = execute
s = shared
p = private (copy on write)
The offset field is the offset into the file/whatever;
dev is the device (major:minor);
inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).
The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).
Under Linux 2.0, there is no field giving pathname.
Alternatively you could update brew
by installing it again. (Think I did this as El Capitan changed something)
Note: this is a heavy handed approach that will remove all applications installed via brew!
Try to install brew a fresh and it will tell how to uninstall.
At original time of writing to uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Edit: As of 2020 to uninstall:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
>>> def func(a, *args, **kwargs):
... print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
...
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}
>>> def anotherfunct(beta, *args):
... print 'beta %s, args %s' % (beta, args)
...
>>> def func(a, *args, **kwargs):
... anotherfunct(a, *args)
...
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>>
I faced the same issue. When I tried to run the project from IDE, it was giving me same error. But when I tried running from the command prompt, the project was running fine. So it came to me that there should be some issue with the settings that makes the program to Run from IDE.
I solved the problem by changing some Project settings. I traced the error and came to the following part in my pom.xml file.
<execution>
<id>default-cli</id>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${java.home}/bin/java</executable>
<commandlineArgs>${runfx.args}</commandlineArgs>
</configuration>
</execution>
I went to my Project Properties > Actions Categories > Action: Run Project: then I Set Properties for Run Project Action as follows:
runfx.args=-jar "${project.build.directory}/${project.build.finalName}.jar"
Then, I rebuild the project and I was able to Run the Project. As you can see, the IDE(Netbeans in my case), was not able to find 'runfx.args' which is set in Project Properties.
If someone else needs a generic utility type to do this, I came up with the following solution:
/**
* Returns object T, but with T[K] overridden to type U.
* @example
* type MyObject = { a: number, b: string }
* OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
*/
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };
I needed this because in my case, the key to override was a generic itself.
If you don't have Omit
ready, see Exclude property from type.
BinaryFormatter
may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.
If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer
or XmlSerializer
.
Though I'm usually against it (though in this case it seems that you have a genuine reason), have you tried providing any query hints on the SP version of the query? If SQL Server is preparing a different execution plan in those two instances, can you use a hint to tell it what index to use, so that the plan matches the first one?
For some examples, you can go here.
EDIT: If you can post your query plan here, perhaps we can identify some difference between the plans that's telling.
SECOND: Updated the link to be SQL-2000 specific. You'll have to scroll down a ways, but there's a second titled "Table Hints" that's what you're looking for.
THIRD: The "Bad" query seems to be ignoring the [IX_Openers_SessionGUID] on the "Openers" table - any chance adding an INDEX hint to force it to use that index will change things?
It's a ProgressDialog, with setIndeterminate(true).
From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)
just do this:
select {
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNSIgaGVpZ2h0PSIyNSIgZmlsbD0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9IiNiYmIiPjxwYXRoIGQ9Ik02IDlsNiA2IDYtNiIvPjwvc3ZnPg==) !important;
background-repeat: no-repeat !important;
background-position-x: 100% !important;
background-position-y: 50% !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
}
select::-ms-expand {
display: none;
}
_x000D_
You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.
For convenience, you may use this extension function in Kotlin
/**
* Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
*/
fun <T> MutableList<T>.insert(index: Int, element: T) {
if (index <= size) {
add(index, element)
} else {
add(element)
}
}
Use Object#toString()
.
String string = map.toString();
That's after all also what System.out.println(object)
does under the hoods. The format for maps is described in AbstractMap#toString()
.
Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's
entrySet
view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as byString.valueOf(Object)
.
You need to have the pointer to point somewhere to use it.
Try this code:
char word[64];
scanf("%s", word);
This creates a character array of lenth 64 and reads input to it. Note that if the input is longer than 64 bytes the word array overflows and your program becomes unreliable.
As Jens pointed out, it would be better to not use scanf for reading strings. This would be safe solution.
char word[64]
fgets(word, 63, stdin);
word[63] = 0;
driver.get()
is used to navigate particular URL(website) and wait till page load.
driver.navigate()
is used to navigate to particular URL and does not wait to page load. It maintains browser history or cookies to navigate back or forward.
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
This may help:
This creates a node that takes a 2D List (list of list items) and pushes them into the excel spreadsheet. make sure the IN[]s are present or will throw and exception.
this is a re-write of the Revit excel dynamo node for excel 2013 as the default prepackaged node kept breaking. I also have a similar read node. The excel syntax in Python is touchy.
thnx @CodingNinja - updated : )
###Export Excel - intended to replace malfunctioning excel node
import clr
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
##Need to Verify interop for version 2015 is 15 and node attachemnt for it.
from Microsoft.Office.Interop import * ##Excel
################################Initialize FP and Sheet ID
##Same functionality as the excel node
strFileName = IN[0] ##Filename
sheetName = IN[1] ##Sheet
RowOffset= IN[2] ##RowOffset
ColOffset= IN[3] ##COL OFfset
Data=IN[4] ##Data
Overwrite=IN[5] ##Check for auto-overwtite
XLVisible = False #IN[6] ##XL Visible for operation or not?
RowOffset=0
if IN[2]>0:
RowOffset=IN[2] ##RowOffset
ColOffset=0
if IN[3]>0:
ColOffset=IN[3] ##COL OFfset
if IN[6]<>False:
XLVisible = True #IN[6] ##XL Visible for operation or not?
################################Initialize FP and Sheet ID
xlCellTypeLastCell = 11 #####define special sells value constant
################################
xls = Excel.ApplicationClass() ####Connect with application
xls.Visible = XLVisible ##VISIBLE YES/NO
xls.DisplayAlerts = False ### ALerts
import os.path
if os.path.isfile(strFileName):
wb = xls.Workbooks.Open(strFileName, False) ####Open the file
else:
wb = xls.Workbooks.add# ####Open the file
wb.SaveAs(strFileName)
wb.application.visible = XLVisible ####Show Excel
try:
ws = wb.Worksheets(sheetName) ####Get the sheet in the WB base
except:
ws = wb.sheets.add() ####If it doesn't exist- add it. use () for object method
ws.Name = sheetName
#################################
#lastRow for iterating rows
lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
#lastCol for iterating columns
lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column
#######################################################################
out=[] ###MESSAGE GATHERING
c=0
r=0
val=""
if Overwrite == False : ####Look ahead for non-empty cells to throw error
for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
if col.Value2 >"" :
OUT= "ERROR- Cannot overwrite"
raise ValueError("ERROR- Cannot overwrite")
##out.append(Data[0]) ##append mesage for error
############################################################################
for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__()
##run macro disbled for debugging excel macro
##xls.Application.Run("Align_data_and_Highlight_Issues")
A pre-commit hook is something that runs on the server, so this probably has nothing to do with your local setup. It could be that you changed something in a settings panel on myversioncontrol.com that is implemented using a pre-commit hook or the myversioncontrol people made an error and added a non-functioning hook.
This is a lexicographical ordering. It just puts things in dictionary order.
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
I had this problem just now and I tried the require_once trick, but it would just echo the CSS above all my php code without actually applying the styles.
What I did to fix it, though, was wrap all my php in their own plain HTML templates. Just type out html in the first line of the document and pick the suggestion html:5 to get the HTML boilerplate, like you would when you're just starting a plain HTML doc. Then cut the closing body and html tags and paste them all the way down at the bottom, below the closing php tag to wrap your php code without actually changing anything. Finally, you can just put your plain old link to your stylesheet into the head of your HTML. Works just fine.
I needed that as well. I found that on msdn:
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.activation.aspx
I think this delegate is for that.
To scroll to a specific element on your page, you can add a function into your jQuery(document).ready(function($){...})
as follows:
$("#fromTHIS").click(function () {
$("html, body").animate({ scrollTop: $("#toTHIS").offset().top }, 500);
return true;
});
It works like a charm in all browsers. Adjust the speed according to your need.
Dleh's answer is correct and explain how to get an instance of another controller without missing dependencies set up for IoC
However, we now need to call the method from this other controller.
Full answer would be :
var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);
//Call your method
ActionInvoker.InvokeAction(controller.ControllerContext, "MethodNameFromControllerB_ToCall");
You can use data:
URL in the src
:
var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';_x000D_
var iframe = document.querySelector('iframe');_x000D_
iframe.src = 'data:text/html,' + encodeURIComponent(html);
_x000D_
<iframe></iframe>
_x000D_
Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.
For Android 7, Galaxy S6 Edge:
If Developer Options is not available then
Now perform step 1. Now it should work, if its still not working then perform these steps. It worked for me.
Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.
Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.
//config.txt
//Input name = image1.png
//Num. of rows = 100
//Num. of cols = 150
std::string ipName;
int nR, nC;
std::ifstream fin("config.txt");
std::string line;
std::istringstream sin;
while (std::getline(fin, line)) {
sin.str(line.substr(line.find("=")+1));
if (line.find("Input name") != std::string::npos) {
std::cout<<"Input name "<<sin.str()<<std::endl;
sin >> ipName;
}
else if (line.find("Num. of rows") != std::string::npos) {
sin >> nR;
}
else if (line.find("Num. of cols") != std::string::npos) {
sin >> nC;
}
sin.clear();
}
(new Date().toString()).replace(/ \w+-\d+ \(.*\)$/,"")
This will have output: Tue Jul 10 2018 19:07:11
(new Date("2005-07-08T11:22:33+0000").toString()).replace(/ \w+-\d+ \(.*\)$/,"")
This will have output: Fri Jul 08 2005 04:22:33
Note: The time returned will depend on your local timezone
In Chrome, right click in the console and check 'preserve log on navigation'.
You could implement a custom pipe for this that leverages the sort
method of arrays:
import { Pipe } from "angular2/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
And use then this pipe as described below. Don't forget to specify your pipe into the pipes
attribute of the component:
@Component({
(...)
template: `
<li *ngFor="list | sort"> (...) </li>
`,
pipes: [ ArraySortPipe ]
})
(...)
It's a simple sample for arrays with string values but you can have some advanced sorting processing (based on object attributes in the case of object array, based on sorting parameters, ...).
Here is a plunkr for this: https://plnkr.co/edit/WbzqDDOqN1oAhvqMkQRQ?p=preview.
Hope it helps you, Thierry
You can use:
QString qs;
// do things
std::cout << qs.toStdString() << std::endl;
It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well. Here's reference documentation for QString
.
I think the problem is here:
[contains(text()='Some text')]
To break this down,
[]
are a conditional that operates on each individual node in
that node set -- each span node in your case. It matches if any of the individual nodes it operates
on match the conditions inside the brackets. text()
is a selector
that matches all of the text nodes that are children of the context
node -- it returns a node set. contains
is a function that operates
on a string. If it is passed a node set, the node set is converted
into a string by returning the string-value of the node in the
node-set that is first in document order.You should try to change this to
[text()[contains(.,'Some text')]]
The outer []
are a conditional that operates on each individual node
in that node set text()
is a selector that matches all of the text
nodes that are children of the context node -- it returns a node
set.
The inner []
are a conditional that operates on each node in that
node set.
contains
is a function that operates on a string. Here it is passed
an individual text node (.
).
Even though the CSS attribute {position:fixed;}
seems (mostly) working on newer iOS devices, it is possible to have the device quirk and fallback to {position:relative;}
on occasion and without cause or reason. Usually clearing the cache will help, until something happens and the quirk happens again.
Specifically, from Apple itself Preparing Your Web Content for iPad:
Safari on iPad and Safari on iPhone do not have resizable windows. In Safari on iPhone and iPad, the window size is set to the size of the screen (minus Safari user interface controls), and cannot be changed by the user. To move around a webpage, the user changes the zoom level and position of the viewport as they double tap or pinch to zoom in or out, or by touching and dragging to pan the page. As a user changes the zoom level and position of the viewport they are doing so within a viewable content area of fixed size (that is, the window). This means that webpage elements that have their position "fixed" to the viewport can end up outside the viewable content area, offscreen.
What is ironic, Android devices do not seem to have this issue. Also it is entirely possible to use {position:absolute;}
when in reference to the body tag and not have any issues.
I found the root cause of this quirk; that it is the scroll event not playing nice when used in conjunction with the HTML or BODY tag. Sometimes it does not like to fire the event, or you will have to wait until the scroll swing event is finished to receive the event. Specifically, the viewport is re-drawn at the end of this event and fixed elements can be re-positioned somewhere else in the viewport.
So this is what I do: (avoid using the viewport, and stick with the DOM!)
<html>
<style>
.fixed{
position:fixed;
/*you can set your other static attributes here too*/
/*like height and width, margin, etc.*/
}
.scrollableDiv{
position:relative;
overflow-y:scroll;
/*all children will scroll within this like the body normally would.*/
}
.viewportSizedBody{
position:relative;
overflow:hidden;
/*this will prevent the body page itself from scrolling.*/
}
</style>
<body class="viewportSizedBody">
<div id="myFixedContainer" class="fixed">
This part is fixed.
</div>
<div id="myScrollableBody" class="scrollableDiv">
This part is scrollable.
</div>
</body>
<script type="text/javascript" src="{your path to jquery}/jquery-1.7.2.min.js"></script>
<script>
var theViewportHeight=$(window).height();
$('.viewportSizedBody').css('height',theViewportHeight);
$('#myScrollableBody').css('height',theViewportHeight);
</script>
</html>
In essence this will cause the BODY to be the size of the viewport and non-scrollable. The scrollable DIV nested inside will scroll as the BODY normally would (minus the swing effect, so the scrolling does stop on touchend.) The fixed DIV stays fixed without interference.
As a side note, a high z-index
value on the fixed DIV is important to keep the scrollable DIV appear to be behind it. I normally add in window resize and scroll events also for cross-browser and alternate screen resolution compatibility.
If all else fails, the above code will also work with both the fixed and scrollable DIVs set to {position:absolute;}
.
Check out LiquiBase XML for keeping a changelog of updates. I had never used it until this year, but I found that it's very easy to learn and make DB revision control/migration/change management very foolproof. I work on a Groovy/Grails project, and Grails uses Hibernate underneath for all its ORM (called "GORM"). We use Liquibase to manage all SQL schema changes, which we do fairly often as our app evolves with new features.
Basically, you keep an XML file of changesets that you continue to add to as your application evolves. This file is kept in git (or whatever you are using) with the rest of your project. When your app is deployed, Liquibase checks it's changelog table in the DB you are connecting to so it will know what has already been applied, then it intelligently just applies whatever changesets have not been applied yet from the file. It works absolutely great in practice, and if you use it for all your schema changes, then you can be 100% confident that code you checkout and deploy will always be able to connect to a fully compatible database schema.
The awesome thing is that I can take a totally blank slate mysql database on my laptop, fire up the app, and right away the schema is set up for me. It also makes it easy to test schema changes by applying these to a local-dev or staging db first.
The easiest way to get started with it would probably be to take your existing DB and then use Liquibase to generate an initial baseline.xml file. Then in the future you can just append to it and let liquibase take over managing schema changes.
I took the JAXB.marshal implementation and added jaxb.fragment=true to remove the XML prolog. This method can handle objects even without the XmlRootElement annotation. This also throws the unchecked DataBindingException.
public static String toXmlString(Object o) {
try {
Class<?> clazz = o.getClass();
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove xml prolog
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // formatted output
final QName name = new QName(Introspector.decapitalize(clazz.getSimpleName()));
JAXBElement jaxbElement = new JAXBElement(name, clazz, o);
StringWriter sw = new StringWriter();
marshaller.marshal(jaxbElement, sw);
return sw.toString();
} catch (JAXBException e) {
throw new DataBindingException(e);
}
}
If the compiler warning bothers you, here's the templated, two parameter version.
public static <T> String toXmlString(T o, Class<T> clazz) {
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove xml prolog
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // formatted output
QName name = new QName(Introspector.decapitalize(clazz.getSimpleName()));
JAXBElement jaxbElement = new JAXBElement<>(name, clazz, o);
StringWriter sw = new StringWriter();
marshaller.marshal(jaxbElement, sw);
return sw.toString();
} catch (JAXBException e) {
throw new DataBindingException(e);
}
}
You can try this.
func convertToJSONString(value: AnyObject) -> String? {
if JSONSerialization.isValidJSONObject(value) {
do{
let data = try JSONSerialization.data(withJSONObject: value, options: [])
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch{
}
}
return nil
}
Use the Alter table statement.
Alter table TableName Alter Column ColumnName nvarchar(100)
Well So I was trying to fix this error. And none worked for me. I was not able to figure out solution. Scenario:
I was just going to made a Navigation Drawer Project
inside Android Studio 2.1.2
And when I try to change the default Android icon in nav_header_main.xml
I was getting some weird errors. I figured out that I was droping my PNG
logo into the ...\app\src\main\res\drawable-21
. When I try to put my PNG logo in ...\app\src\main\res\drawable
bam! All weird errors go away.
Following are some of stack trace when I was putting PNG into drawable-21
folder:
08-17 17:29:56.237 6644-6678/myAppName E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.Restarter.getActivities
08-17 17:30:01.674 6644-6644/myAppName E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{myAppName.MainActivity}: android.view.InflateException: Binary XML file line #16: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #16: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:613)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at edu.uswat.fwd82.findmedoc.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:5179)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at edu.uswat.fwd82.findmedoc.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:5179)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.support.design.internal.NavigationMenuPresenter.inflateHeaderView(NavigationMenuPresenter.java:189)
at android.support.design.widget.NavigationView.inflateHeaderView(NavigationView.java:262)
at android.support.design.widget.NavigationView.<init>(NavigationView.java:173)
at android.support.design.widget.NavigationView.<init>(NavigationView.java:95)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at edu.uswat.fwd82.findmedoc.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:5179)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3956)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.res.ResourcesEx.getThemeDrawable(ResourcesEx.java:459)
at android.content.res.ResourcesEx.loadDrawable(ResourcesEx.java:435)
at android.content.res.TypedArray.getDrawable(TypedArray.java:609)
at android.widget.ImageView.<init>(ImageView.java:120)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:57)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:53)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:980)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1039)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:
As you can see the above Stack Trace include:
android.support.design.widget.NavigationView.inflateHeaderView(NavigationView.java:262) at android.support.design.widget.NavigationView.(NavigationView.java:173) at android.support.design.widget.NavigationView.(NavigationView.java:95)
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
As @Quartz mentioned, you can do something like
stage('Tests') {
parallel(
'Unit Tests': {
container('node') {
sh("npm test --cat=unit")
}
},
'API Tests': {
container('node') {
sh("npm test --cat=acceptance")
}
}
)
}
I'm keeping the following list updated for a couple of years now:
1.0.0.0/24
1.1.1.0/24
1.2.3.0/24
8.6.48.0/21
8.8.8.0/24
8.35.192.0/21
8.35.200.0/21
8.34.216.0/21
8.34.208.0/21
23.236.48.0/20
23.251.128.0/19
63.161.156.0/24
63.166.17.128/25
64.9.224.0/19
64.18.0.0/20
64.233.160.0/19
64.233.171.0/24
65.167.144.64/28
65.170.13.0/28
65.171.1.144/28
66.102.0.0/20
66.102.14.0/24
66.249.64.0/19
66.249.92.0/24
66.249.86.0/23
70.32.128.0/19
72.14.192.0/18
74.125.0.0/16
89.207.224.0/21
104.154.0.0/15
104.132.0.0/14
107.167.160.0/19
107.178.192.0/18
108.59.80.0/20
108.170.192.0/18
108.177.0.0/17
130.211.0.0/16
142.250.0.0/15
144.188.128.0/24
146.148.0.0/17
162.216.148.0/22
162.222.176.0/21
172.253.0.0/16
173.194.0.0/16
173.255.112.0/20
192.158.28.0/22
193.142.125.0/28
199.192.112.0/22
199.223.232.0/21
206.160.135.240/24
207.126.144.0/20
208.21.209.0/24
209.85.128.0/17
216.239.32.0/19
For me a noop on table has been enough (was already InnoDB):
ALTER TABLE $tbl ENGINE=InnoDB;
Andy's solution does not work for me. Here I found another way:
git checkout `git rev-list -n 1 --before="2009-07-27 13:37" master`
I am beginner to iOS development so I would like to share whole info I got in this section.
First from image assets (images.xcassets) create image set .
According to Documentation here is all sizes need to create background image.
For iPhone 5:
640 x 1136
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
iPhone 4s (@2x)
640 x 960
iPad and iPad mini (@2x)
1536 x 2048 (portrait)
2048 x 1536 (landscape)
iPad 2 and iPad mini (@1x)
768 x 1024 (portrait)
1024 x 768 (landscape)
iPad Pro (@2x)
2048 x 2732 (portrait)
2732 x 2048 (landscape)
call the image background we can call image from image assets by using this method UIImage(named: "background")
here is full code example
override func viewDidLoad() {
super.viewDidLoad()
assignbackground()
// Do any additional setup after loading the view.
}
func assignbackground(){
let background = UIImage(named: "background")
var imageView : UIImageView!
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = background
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like Mathematica or Maple. Engineering departments, on the other hand, often rely on it and there are definitely useful things for some applied mathematicians. It's also used heavily in industry in some areas.
Something you have to realize about MATLAB is that it started off as a wrapper on Fortran libraries for linear algebra. For a long time, it had an attitude that "all the world is an array of doubles (floats)". As a language, it has grown very organically, and there are some flaws that are very much baked in, if you look at it just as a programming language.
However, if you look at it as an environment for doing certain types of research in, it has some real strengths. It's about as good as it gets for doing floating point linear algebra. The notation is simple and powerful, the implementation fast and trusted. It is very good at generating plots and other interactive tasks. There are a large number of `toolboxes' with good code for particular tasks, that are affordable. There is a large community of users that share numerical codes (Python + NumPy has nothing in the same league, at least yet)
Python, warts and all, is a much better programming language (as are many others). However, it's a decade or so behind in terms of the tools.
The key point is that the majority of people who use MATLAB are not programmers really, and don't want to be.
It's a lousy choice for a general programming language; it's quirky, slow for many tasks (you need to vectorize things to get efficient codes), and not easy to integrate with the outside world. On the other hand, for the things it is good at, it is very very good. Very few things compare. There's a company with reasonable support and who knows how many man-years put into it. This can matter in industry.
Strictly looking at your Python vs. MATLAB comparison, they are mostly different tools for different jobs. In the areas where they do overlap a bit, it's hard to say what the better route to go is (depends a lot on what you're trying to do). But mostly Python isn't all that good at MATLAB's core strengths, and vice versa.
In my case I had to redownload it, something was wrong with the one I downloaded. Its size was far much less than the one on the website.
map
creates a new list by applying a function to every element of the source:
xs = [1, 2, 3]
# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
ys.append(x * 2)
n-ary map
is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:
xs = [1, 2, 3]
ys = [2, 4, 6]
def f(x, y):
return (x * 2, y // 2)
# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
zs.append(f(x, y))
I've used zip
here, but map
behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None
.
The regular expression you are looking for is simply this:
[0-9]
You do not mention what language you are using. If your regular expression evaluator forces REs to be anchored, you need this:
.*[0-9].*
Some RE engines (modern ones!) also allow you to write the first as \d
(mnemonically: digit) and the second would then become .*\d.*
.
Use a different function, like VLOOKUP:
=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", VLOOKUP(A1,B:C,2,FALSE))
A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.
So for example assume you have a function:
float doMultiplication (float num1, float num2 ) {
return num1 * num2; }
then the following typedef:
typedef float(*pt2Func)(float, float);
can be used to point to this doMulitplication
function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func
. Note that pt2Func
can point to ANY function which returns a float and takes in 2 floats.
So you can create a pointer which points to the doMultiplication function as follows:
pt2Func *myFnPtr = &doMultiplication;
and you can invoke the function using this pointer as follows:
float result = (*myFnPtr)(2.0, 5.1);
This makes good reading: http://www.newty.de/fpt/index.html
Oracle SQL Developer 4.0.1.14 surely does support connections to PostgreSQL.
Tools ? Preferences
, Database ? Third Party JDBC Drivers
and add the jar file (see http://www.oracle.com/technetwork/products/migration/jdbc-migration-1923524.html for step by step example)Database Connection
and instead of Oracle
, select PostgreSQL
tabEdit:
If you have different user name and database name, one should specify in hostname: hostname/database?
(do not forget ?
) or hostname:port/database?
.
(thanks to @kinkajou and @Kloe2378231; more details on https://stackoverflow.com/a/28671213/565525).
I can't seem to replicate your trouble. Go ahead and run this native Ruby script. It generates the exact output your looking for, and Rails supports all of these methods. What sort of inputs are you having trouble with?
#!/usr/bin/ruby
def fixlistname(title)
title = title.lstrip
title += '...' unless title =~ /\.{3}$/
title[0] = title[0].capitalize
raise 'Title must start with "You know you..."' unless title =~ /^You know you/
title
end
DATA.each do |title|
puts fixlistname(title)
end
__END__
you know you something WITH dots ...
you know you something WITHOUT the dots
you know you something with LEADING whitespace...
you know you something with whitespace BUT NO DOTS
this generates error because it doesn't start with you know you
You know you something WITH dots ...
You know you something WITHOUT the dots...
You know you something with LEADING whitespace...
You know you something with whitespace BUT NO DOTS...
RuntimeError: Title must start with "You know you..."
Based on your edit, you can try something like this.
def fixlistname!
self.title = title.lstrip
self.title += '...' unless title.ends_with?('...')
self.title[0] = title[0].capitalize
errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end
This will do the trick
s = "i'm from New York"
s[0] = s[0].capitalize
#=> I'm from New York
When trying to use String#capitalize
on the whole string, you were seeing I'm from new york
because the method:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
You can't view the hashed password; the only thing you can do is reset it!
Stop MySQL:
sudo service mysql stop
or
$ sudo /usr/local/mysql/support-files/mysql.server stop
Start it in safe mode:
$ sudo mysqld_safe --skip-grant-tables
(above line is the whole command)
This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:
$ mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
MySQL 5.7 and over:
mysql> use mysql;
mysql> update user set authentication_string=password('password') where user='root';
Start MySQL:
sudo mysql start
or
sudo /usr/local/mysql/support-files/mysql.server start
Your new password is 'password'.
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
where entityManagerFactory
is an JPA EntityManagerFactory
.
Use below command to change log level while submitting application using spark-submit or spark-sql:
spark-submit \
--conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=file:<file path>/log4j.xml" \
--conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:<file path>/log4j.xml"
Note: replace <file path>
where log4j
config file is stored.
Log4j.properties:
log4j.rootLogger=ERROR, console
# set the log level for these components
log4j.logger.com.test=DEBUG
log4j.logger.org=ERROR
log4j.logger.org.apache.spark=ERROR
log4j.logger.org.spark-project=ERROR
log4j.logger.org.apache.hadoop=ERROR
log4j.logger.io.netty=ERROR
log4j.logger.org.apache.zookeeper=ERROR
# add a ConsoleAppender to the logger stdout to write to the console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# use a simple message format
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>_x000D_
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">_x000D_
_x000D_
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">_x000D_
<appender name="console" class="org.apache.log4j.ConsoleAppender">_x000D_
<param name="Target" value="System.out"/>_x000D_
<layout class="org.apache.log4j.PatternLayout">_x000D_
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />_x000D_
</layout>_x000D_
</appender>_x000D_
<logger name="org.apache.spark">_x000D_
<level value="error" />_x000D_
</logger>_x000D_
<logger name="org.spark-project">_x000D_
<level value="error" />_x000D_
</logger>_x000D_
<logger name="org.apache.hadoop">_x000D_
<level value="error" />_x000D_
</logger>_x000D_
<logger name="io.netty">_x000D_
<level value="error" />_x000D_
</logger>_x000D_
<logger name="org.apache.zookeeper">_x000D_
<level value="error" />_x000D_
</logger>_x000D_
<logger name="org">_x000D_
<level value="error" />_x000D_
</logger>_x000D_
<root>_x000D_
<priority value ="ERROR" />_x000D_
<appender-ref ref="console" />_x000D_
</root>_x000D_
</log4j:configuration>
_x000D_
Switch to FileAppender in log4j.xml if you want to write logs to file instead of console. LOG_DIR
is a variable for logs directory which you can supply using spark-submit --conf "spark.driver.extraJavaOptions=-D
.
<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">_x000D_
<param name="file" value="${LOG_DIR}"/>_x000D_
<param name="datePattern" value="'.'yyyy-MM-dd"/>_x000D_
<layout class="org.apache.log4j.PatternLayout">_x000D_
<param name="ConversionPattern" value="%d [%t] %-5p %c %x - %m%n"/>_x000D_
</layout>_x000D_
</appender>
_x000D_
Another important thing to understand here is, when job is launched in distributed mode ( deploy-mode cluster and master as yarn or mesos) the log4j configuration file should exist on driver and worker nodes (log4j.configuration=file:<file path>/log4j.xml
) else log4j init will complain-
log4j:ERROR Could not read configuration file [log4j.properties]. java.io.FileNotFoundException: log4j.properties (No such file or directory)
Hint on solving this problem-
Keep log4j config file in distributed file system(HDFS or mesos) and add external configuration using log4j PropertyConfigurator. or use sparkContext addFile to make it available on each node then use log4j PropertyConfigurator to reload configuration.
You can do following
<div id="circle"></div>
CSS
#circle {
width: 100px;
height: 100px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
Other shape SOURCE
Rather than writing
#define _USE_MATH_DEFINES
I would recommend using -D_USE_MATH_DEFINES
or /D_USE_MATH_DEFINES
depending on your compiler.
This way you are assured that even in the event of someone including the header before you do (and without the #define) you will still have the constants instead of an obscure compiler error that you will take ages to track down.
it should vary with the architecture because it represents the size of any object. So on a 32-bit system size_t
will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide.
You can use Case
expression for returning a boolean
in your select query like below.
@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")
Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
from scipy.optimize import fsolve
def double_solve(f1,f2,x0,y0):
func = lambda x: [f1(x[0], x[1]), f2(x[0], x[1])]
return fsolve(func,[x0,y0])
def n_solve(functions,variables):
func = lambda x: [ f(*x) for f in functions]
return fsolve(func, variables)
f1 = lambda x,y : x**2+y**2-1
f2 = lambda x,y : x-y
res = double_solve(f1,f2,1,0)
res = n_solve([f1,f2],[1.0,0.0])
You can use the following tag
<body oncontextmenu="return false"><!-- your page body hear--></body>
OR you can create your own menu when right click:
I have the same variant as the last ones which calculates segments of table data, table indexes and blob-fields:
CREATE OR REPLACE FUNCTION
SYS.RAZMER_TABLICY_RAW(pNazvanie in varchar, pOwner in varchar2)
return number
is
val number(16);
sz number(16);
begin
sz := 0;
--Calculate size of table data segments
select
sum(t.bytes) into val
from
sys.dba_segments t
where
t.segment_name = upper(pNazvanie)
and
t.owner = upper(pOwner);
sz := sz + nvl(val,0);
--Calculate size of table indexes segments
select
sum(s.bytes) into val
from
all_indexes t
inner join
dba_segments s
on
t.index_name = s.segment_name
where
t.table_name = upper(pNazvanie)
and
t.owner = upper(pOwner);
sz := sz + nvl(val,0);
--Calculate size of table blob segments
select
sum(s.bytes) into val
from
all_lobs t
inner join
dba_segments s on t.segment_name = s.segment_name
where
t.table_name = upper(pNazvanie)
and
t.owner = upper(pOwner);
sz := sz + nvl(val,0);
return sz;
end razmer_tablicy_raw;
Create Arraylist<Date>
of Date class. And use Collections.sort()
for ascending order.
Sorts the specified list into ascending order, according to the natural ordering of its elements.
For Sort it in descending order See Collections.reverseOrder()
Collections.sort(yourList, Collections.reverseOrder());
Answer if you only want to use for each loop ..
for (WebElement s : options) {
int i = options.indexOf(s);
System.out.println(options.get(i).getText());
}
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
On a 64-bit machine:
int: 4
long: 8
long long: 8
void*: 8
size_t: 8
if you have an array and array element is stdClass
item then this is the solution:
foreach($post_id as $key=>$item){
$post_id[$key] = (array)$item;
}
now the stdClass
has been replaced with an array inside the array as new array element
If you want to keep your line-height and force the placeholder to have the same, you can directly edit the placeholder CSS since the newer browser versions. That did the trick for me:
input::-webkit-input-placeholder { /* WebKit browsers */
line-height: 1.5em;
}
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
line-height: 1.5em;
}
input::-moz-placeholder { /* Mozilla Firefox 19+ */
line-height: 1.5em;
}
input:-ms-input-placeholder { /* Internet Explorer 10+ */
line-height: 1.5em;
}
According to HTTP terms, The PUT
request is just-like a database update statement.
PUT
- is used for modifying existing resource (Previously POSTED). On the other hand the PATCH
request is used to update some portion of existing resource.
For Example:
Customer Details:
// This is just a example.
firstName = "James";
lastName = "Anderson";
email = "[email protected]";
phoneNumber = "+92 1234567890";
//..
When we want to update to entire record ? we have to use Http
PUT
verb
for that.
such as:
// Customer Details Updated.
firstName = "James++++";
lastName = "Anderson++++";
email = "[email protected]";
phoneNumber = "+92 0987654321";
//..
On the other hand if we want to update only the portion of the record not the entire record then go for Http
PATCH
verb
.
such as:
// Only Customer firstName and lastName is Updated.
firstName = "Updated FirstName";
lastName = "Updated LastName";
//..
PUT VS POST:
When using PUT
request we have to send all parameter such as firstName, lastName, email, phoneNumber Where as In patch
request only send the parameters which one we want to update and it won't effecting or changing other data.
For more details please visit : https://fullstack-developer.academy/restful-api-design-post-vs-put-vs-patch/
Run docker login
Push the image to docker hub
Re-create pod
This solved the problem for me. Hope it helps.
That's a lot of questions.
Why EOF
is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"
any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF
is 0
when it's FALSE, meaning getchar()
returned EOF
.
in order to emulate EOF
when reading from stdin
press Ctrl+D
As described here input and output extension will detected by ffmpeg
so there is no need to worry about the formats, simply run this command:
ffmpeg -i inputFile.ogg outputFile.mp3
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
You could also do something as follow
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
or
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).
For the validation, I had to use Apache's EnumUtils
library since the type of enum is not known at compile time.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551
I like to avoid raising a new exception while handling an old one. It makes the error messages confusing to read.
For example, in my code, I originally wrote
try:
return tuple.__getitem__(self, i)(key)
except IndexError:
raise KeyError(key)
And I got this message.
>>> During handling of above exception, another exception occurred.
I wanted this:
try:
return tuple.__getitem__(self, i)(key)
except IndexError:
pass
raise KeyError(key)
It doesn't affect how exceptions are handled. In either block of code, a KeyError would have been caught. This is merely an issue of getting style points.
In Ubuntu (PHP-FPM,Nginx)
sudo apt-get install php5-mcrypt
After installing php5-mcrypt
you have to make a symlink to ini files in mods-available:
sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini
enable:
sudo php5enmod mcrypt
restart php5-fpm:
sudo service php5-fpm restart
Try this solution:
for m in ["a", "á", "à", "ã", "â"]:
try:
somelist.remove(m)
except:
pass
Just for your information. and
and or
operators are also using to return values. It is useful when you need to assign value to variable but you have some pre-requirements
operator or
returns first not null value
#init values
a,b,c,d = (1,2,3,None)
print(d or a or b or c)
#output value of a - 1
print(b or a or c or d)
#output value of b - 2
Operator and
returns last value in the sequence if any of the members don't have None
value or if they have at least one None value we get None
print(a and d and b and c)
#output: None
print(a or b or c)
#output value of c - 3
I experienced this condition when I had installed Oracle version 12 client 32 bit client connected to an Oracle 12 Server running on windows. Although both of Oracle-source and SqlServer-destination are NOT Unicode, I kept getting this message, as if the oracle columns were Unicode. I solved the problem inserting a data conversion box, and selecting type DT-STR (not unicode) for varchar2 fields and DT-WSTR (unicode) for numeric fields, then I've dropped the 'COPY OF' from the output field name. Note that I kept getting the error because I had connected the source box arrow with the conversion box BEFORE setting the convertion types. So I had to switch source box and this cleaned all the errors in the destination box.
If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.
From ElasticSearch Blog
No, that's pretty much it. In theory you could use visibility: collapse
on some <col>
?s to do it, but browser support isn't all there.
To improve what you've got slightly, you could use table-layout: fixed
on the <table>
to allow the browser to use the simpler, faster and more predictable fixed-table-layout algorithm. You could also drop the .show
rules as when a cell isn't made display: none
by a .hide
rule it will automatically be display: table-cell
. Allowing table display to revert to default rather than setting it explicitly avoids problems in IE<8, where the table display values are not supported.
function isVowel(char)
{
if (char.length == 1)
{
var vowels = "aeiou";
var isVowel = vowels.indexOf(char) >= 0 ? true : false;
return isVowel;
}
}
Basically it checks for the index of the character in the string of vowels. If it is a consonant, and not in the string, indexOf
will return -1.
Look at this article. The iterator object nditer from numpy package, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.
Example:
import random
import numpy as np
ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]])
for ptr in np.nditer(ptrs, op_flags=['readwrite']):
# apply random shift on 1 for each element of the matrix
ptr += random.choice([-1, 1])
print(ptrs)
d:\>python nditer.py
[[ -1 1]
[399 -1]
[ 1 399]
[399 401]]
On OSX, I used MacPorts to address the same problem when connecting to my siteground database. Siteground appears to be using 5.0.77mm0.1-log, but creating a new user account didn't fix the problem. This is what did
sudo port install php5-mysql -mysqlnd +mysql5
This downgrades the mysql driver that php will use.
Finally I got it to work. Steve's answer is right but not for all cases. It fails when that view is being executed from a third schema. For that to work you have to add the grant option:
GRANT SELECT ON [TABLE_NAME] TO [READ_USERNAME] WITH GRANT OPTION;
That way, [READ_USERNAME]
can also grant select privilege over the view to another schema
For those situations where you need a bit more customisation of the output (separator or decimal symbol), or who have large dataset (over 65k rows), I wrote the following:
Option Explicit
Sub rng2csv(rng As Range, fileName As String, Optional sep As String = ";", Optional decimalSign As String)
'export range data to a CSV file, allowing to chose the separator and decimal symbol
'can export using rng number formatting!
'by Patrick Honorez --- www.idevlop.com
Dim f As Integer, i As Long, c As Long, r
Dim ar, rowAr, sOut As String
Dim replaceDecimal As Boolean, oldDec As String
Dim a As Application: Set a = Application
ar = rng
f = FreeFile()
Open fileName For Output As #f
oldDec = Format(0, ".") 'current client's decimal symbol
replaceDecimal = (decimalSign <> "") And (decimalSign <> oldDec)
For Each r In rng.Rows
rowAr = a.Transpose(a.Transpose(r.Value))
If replaceDecimal Then
For c = 1 To UBound(rowAr)
'use isnumber() to avoid cells with numbers formatted as strings
If a.IsNumber(rowAr(c)) Then
'uncomment the next 3 lines to export numbers using source number formatting
' If r.cells(1, c).NumberFormat <> "General" Then
' rowAr(c) = Format$(rowAr(c), r.cells(1, c).NumberFormat)
' End If
rowAr(c) = Replace(rowAr(c), oldDec, decimalSign, 1, 1)
End If
Next c
End If
sOut = Join(rowAr, sep)
Print #f, sOut
Next r
Close #f
End Sub
Sub export()
Debug.Print Now, "Start export"
rng2csv shOutput.Range("a1").CurrentRegion, RemoveExt(ThisWorkbook.FullName) & ".csv", ";", "."
Debug.Print Now, "Export done"
End Sub
import java.io.*;
public class Code {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
Process process = builder.start();
StringBuilder out = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = null;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append("\n");
}
System.out.println(out);
}
}
}
Assuming the current directory is not in the path, the syntax is ./[name of the program]
.
For example ./a.out
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.
https://tools.percona.com/wizard
Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/
Everyone points to key_buffer_size
first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).
If you are on SQL Server 2008 or later version, you can use the ROLLUP()
GROUP BY function:
SELECT
Type = ISNULL(Type, 'Total'),
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;
This assumes that the Type
column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type
column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING()
function:
SELECT
Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;
Here's what I ended up using.
public class DataPoint<T1,T2>
{
public DataPoint(T1 x, T2 y)
{
X = x;
Y = y;
}
[JsonProperty("x")]
public T1 X { get; }
[JsonProperty("y")]
public T2 Y { get; }
}
public class Trendline
{
public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints)
{
int count = 0;
long sumX = 0;
long sumX2 = 0;
decimal sumY = 0;
decimal sumXY = 0;
foreach (var dataPoint in dataPoints)
{
count++;
sumX += dataPoint.X;
sumX2 += dataPoint.X * dataPoint.X;
sumY += dataPoint.Y;
sumXY += dataPoint.X * dataPoint.Y;
}
Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));
Intercept = (sumY / count) - (Slope * (sumX / count));
}
public decimal Slope { get; private set; }
public decimal Intercept { get; private set; }
public decimal Start { get; private set; }
public decimal End { get; private set; }
public decimal GetYValue(decimal xValue)
{
return Slope * xValue + Intercept;
}
}
My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance.
The fastest way i could find out is this :
var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));
Hope to be useful
Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
There is a function UTC()
that returns the milliseconds from the unix epoch.
None of the previous comments solve the issue on my Mac. I used the commands below and it worked.
$ brew services stop mysql
$ pkill mysqld
$ rm -rf /usr/local/var/mysql/ # NOTE: this will delete your existing database!!!
$ brew postinstall mysql
$ brew services restart mysql
$ mysql -u root
I don't know for sure if the following answer wasn't provided
but I decided to add some local optimizations to the allocation of 2d array
(e.g., a square matrix is done through only one allocation):
int** mat = new int*[n];
mat[0] = new int [n * n];
However, deletion goes like this because of linearity of the allocation above:
delete [] mat[0];
delete [] mat;
To summarize: there are at least five ways to split a string in Java:
String.split():
String[] parts ="10,20".split(",");
Pattern.compile(regexp).splitAsStream(input):
List<String> strings = Pattern.compile("\\|")
.splitAsStream("010|020202")
.collect(Collectors.toList());
StringTokenizer (legacy class):
StringTokenizer strings = new StringTokenizer("Welcome to EXPLAINJAVA.COM!", ".");
while(strings.hasMoreTokens()){
String substring = strings.nextToken();
System.out.println(substring);
}
Google Guava Splitter:
Iterable<String> result = Splitter.on(",").split("1,2,3,4");
Apache Commons StringUtils:
String[] strings = StringUtils.split("1,2,3,4", ",");
So you can choose the best option for you depending on what you need, e.g. return type (array, list, or iterable).
Here is a big overview of these methods and the most common examples (how to split by dot, slash, question mark, etc.)
I had the same problem for a long time. I just managed to resolve it.
So, you need to select your Path, like the others said above. What I did:
Open a command window. Write set path=C:\Python24 (put the location and the version for your python). Now type python, It should work.
The annoying part with this is that you have to type it every time you open the CMD.
I tried to do the permanent one (with the changes in the Environmental variables) but for me its not working.
If you want something that will be unique you can use something like this:
string = (Digest::MD5.hexdigest "#{ActiveSupport::SecureRandom.hex(10)}-#{DateTime.now.to_s}")
however this will generate string of 32 characters.
There is however other way:
require 'base64'
def after_create
update_attributes!(:token => Base64::encode64(id.to_s))
end
for example for id like 10000, generated token would be like "MTAwMDA=" (and you can easily decode it for id, just make
Base64::decode64(string)
Just add plt.pyplot.show()
, that would be fine.
The best solution is disabling SciView.
It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.
In Bootstrap 4, if you want to do something like this:
Mobile | Desktop
-----------------------------
A | A
C | B C
B | D
D |
You need to reverse the order of B then C then apply order-{breakpoint}-first
to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:
Smaller screens: 12 cols to B and 12 cols to C
Larger screens: 12 cols between the sum of them (B + C = 12)
Like this
<div class='row no-gutters'>
<div class='col-12'>
A
</div>
<div class='col-12'>
<div class='row no-gutters'>
<div class='col-12 col-md-6'>
C
</div>
<div class='col-12 col-md-6 order-md-first'>
B
</div>
</div>
</div>
<div class='col-12'>
D
</div>
</div>
AndroidStudioFrontScreenI simply double clicked the Android dmg install file that I saved on the hard drive and when the initial screen came up I dragged the icon for Android Studio into the Applications folder, now I know where it is!!! Also when you run it, be sure to right click the Android Studio while on the Dock and select "Options" -> "Keep on Dock". Everything else works. Dr. Roger Webster
Here is a simple context manager that prints to the console and writes the same output to an file. It also writes any exceptions to the file.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.
def left(aString, howMany):
if howMany <1:
return ''
else:
return aString[:howMany]
def right(aString, howMany):
if howMany <1:
return ''
else:
return aString[-howMany:]
def mid(aString, startChar, howMany):
if howMany < 1:
return ''
else:
return aString[startChar:startChar+howMany]
You're on the right track - the keyword you should be googling is Regular Expressions. R does support them in a more direct way than this using grep()
and a few other alternatives.
Here's a detailed discussion: http://www.regular-expressions.info/rlanguage.html
I do not believe there is a "per query" way to do this. (You can use the use
keyword to specify the database - not the schema - but that's technically a separate query as you have to issue the go
command afterward.)
Remember, in SQL server fully qualified table names are in the format:
[database].[schema].[table]
In SQL Server Management Studio you can configure all the defaults you're asking about.
You can set up the default database
on a per-user basis (or in your connection string):
Security > Logins > (right click) user > Properties > General
You can set up the default schema
on a per-user basis (but I do not believe you can configure it in your connection string, although if you use dbo
that is always the default):
Security > Logins > (right click) user > Properties > User Mapping > Default Schema
In short, if you use dbo
for your schema, you'll likely have the least amount of headaches.
Simply add libraryTarget: 'umd'
, like so
const webpackConfig = {
output: {
libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
}
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Or just use a regular for loop instead of foreach. A for loop is slightly faster (though you won't notice the difference except in very time critical code).
you can use LINQ
string abc = "abc";
char getresult = abc.Where((item, index) => index == 2).Single();
Here is yet another one-liner for you:
your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);
You should use querySelectorAll
. It returns NodeList, however querySelector
returns only the first found element:
var deleteLink = document.querySelectorAll('.delete');
Then you would loop:
for (var i = 0; i < deleteLink.length; i++) {
deleteLink[i].addEventListener('click', function(event) {
if (!confirm("sure u want to delete " + this.title)) {
event.preventDefault();
}
});
}
Also you should preventDefault only if confirm === false
.
It's also worth noting that return false/true
is only useful for event handlers bound with onclick = function() {...}
. For addEventListening
you should use event.preventDefault()
.
Demo: http://jsfiddle.net/Rc7jL/3/
ES6 version
You can make it a little cleaner (and safer closure-in-loop wise) by using Array.prototype.forEach iteration instead of for-loop:
var deleteLinks = document.querySelectorAll('.delete');
Array.from(deleteLinks).forEach(link => {
link.addEventListener('click', function(event) {
if (!confirm(`sure u want to delete ${this.title}`)) {
event.preventDefault();
}
});
});
Example above uses Array.from and template strings from ES2015 standard.
If you just want to know the mean, you can use
summary(results)
It will give you more information than expected.
ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.
Furthermore, If you want to get mean values of each column, you can simply use the method below.
mean(results$columnName, na.rm = TRUE)
That will return mean value. (you have to change 'columnName' to your variable name
From the Docs:
(function( $ ){
$.fn.myfunction = function() {
alert('hello world');
return this;
};
})( jQuery );
Then you do
$('#my_div').myfunction();
Of course you can use build in functions, but if you would like to create your own you can do something like this. The trick here is to use ~ operator that flip positive number to negative. For instance ~2 -> -3 and using negative in for list in Python will count items from the end. So if you have mid == 2 then it will take third element from beginning and third item from the end.
def median(data):
data.sort()
mid = len(data) // 2
return (data[mid] + data[~mid]) / 2
You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:
protected $fillable = ['name', 'created_at'];
Have you check your php.ini ?
I broken my post method once that I set post_max_size
the same with upload_max_filesize
.
I think that post_max_size
must less than upload_max_filesize
.
Tested with PHP 5.3.3 in RHEL 6.0
function getRangeDateString($timestamp) {
if ($timestamp) {
$currentTime=strtotime('today');
// Reset time to 00:00:00
$timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
$days=round(($timestamp-$currentTime)/86400);
switch($days) {
case '0';
return 'Today';
break;
case '-1';
return 'Yesterday';
break;
case '-2';
return 'Day before yesterday';
break;
case '1';
return 'Tomorrow';
break;
case '2';
return 'Day after tomorrow';
break;
default:
if ($days > 0) {
return 'In '.$days.' days';
} else {
return ($days*-1).' days ago';
}
break;
}
}
}
I know it's a very late answer but I'd like to share what I did as per this link:
I added the below code to the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
And this Advice Controller in order to get the version as model attribute:
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class CommonControllerAdvice
{
@Autowired
BuildProperties buildProperties;
@ModelAttribute("version")
public String getVersion() throws IOException
{
String version = buildProperties.getVersion();
return version;
}
}
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
The GetGenericArgument()
method has to be set on the Base Type of your instance
(whose class is a generic class myClass<T>
). Otherwise, it returns a type[0]
Example:
Myclass<T> instance = new Myclass<T>();
Type[] listTypes = typeof(instance).BaseType.GetGenericArguments();
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
To add to this - it seems important to define the width & height of the drawable as per this post:
(his code works)
I had this error for quite sometime now until I couldn't take it anymore so I have tried all possbile solutions above, but none worked for me. I noticed that the error only pops up on a certain project only (like what a user mentioned above) but not on other projects. Because of that, since nothing is working, I cloned my project again on a different folder and it started working again.
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
it.remove(); // avoids a ConcurrentModificationException
}
EDIT: So inside the while try this:
map.put(pairs.getKey(), pairs.getValue().add(number))
You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList
.
EDIT 2: Then put the following inside your while loop:
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
EDIT 3:
By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango
, and if it does add 18
, else create a new entry in the map with key mango
and value 18
.
So all you may need is the following, without the loop:
if(map.containsKey("mango"))
{
map.put("mango", map.get("mango).add(18));
}
else
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango", ints);
}
How about just a simple reset button?
<form>
<input type="text" id="textfield1" size="5">
<input type="text" id="textfield2" size="5">
<input type="reset" value="Reset">
</form>
To get a definitive reason, you'd need to ask the designer(s) of that API.
But one possible reason is that the intent of a (hypothetical) nextChar
would not fit into the scanning model very well.
If nextChar()
to behaved like read()
on a Reader
and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type>
methods. These skip over delimiter characters before they attempt to parse a value.
If nextChar()
to behaved like (say) nextInt
then:
the delimiter skipping would be "unexpected" for some folks, and
there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char
, or maybe even support escaping or something1.
No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.
1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.
I have observed one case when eclipse when in forced quit, or Alt-f2 xkill
ed in linux, an attempt to immediately open eclipse shows that error. Even the metadat/.lock file is not present in that case.
However it starts working after a span of about two minutes
I guess
@foo = ("aAa", "bbb");
@bar = grep(/^aaa/i, @foo);
print join ",",@bar;
would do the trick.
if you can load jQuery from your own server, then you can append this to your jQuery file:
jQuery(document).trigger('jquery.loaded');
then you can bind to that triggered event.
Short and Crisp single line command, that will take care of it.
kill -9 $(lsof -i tcp:3000 -t)
Set the listview adapter to "simple_list_item_multiple_choice"
ArrayAdapter<String> adapter;
List<String> values; // put values in this
//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice,
values);
setListAdapter(adapter);
A solution that does not ignore changes in directory properties
I tried to use the solution based on changelist
, but I have a couple of issues with it. First my repository has thousand of files, so the changelist to be committed is huge, and my svn status
output became way too long and needed to be parsed to be useful. Most important is that I wanted to commit changes that came from a merge, which means they include property changes. When committing a changelist, the svn properties attached to the directory are not committed, so I had to do an extra commit:
svn ci --cl work -m "this commits files from the work changelist only"
svn up
svn ci --depth empty DIR . -m "record merge properties"
You may have to do that for several directories (here I record the properties of DIR
and of the current dir .
), basically those with a M
in the second column when issuing the svn status
command.
Solution
I used patches and svn patch
. In pseudo-code:
svn diff $IGNORE_FILES > MYPATCH # get the mods to ignore
svn patch --reverse-diff MYPATCH # remove the mods
svn ci -m "message" # check-in files and directory properties
svn patch MYPATCH # re-apply the mods
Like other posters, I end up using a script to maintain the list of files to ignore:
#! /usr/bin/env bash
finish() {
svn patch MYPATCH # re-apply the mods
}
trap finish EXIT
IGNORE_FILES="\
sources/platform/ecmwf-cca-intel-mpi.xml \
runtime/classic/platform/ecmwf-cca.job.tmpl \
runtime/classic/platform/ecmwf-cca-intel.xml"
svn diff $IGNORE_FILES > MYPATCH # get the mods to ignore
svn patch --reverse-diff MYPATCH # remove the mods
svn "$@"
I typically used it with ci
and revert -R .
.
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
Look at this awesome new library which is available via gradle :)
build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
Usage:
new HttpRequestTask(
new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
@Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
When compiling with -std=c++11
, one can simply
const char *s = u8"\u0444";
cout << s << endl;
sep='\t'
is often used for Tab-delimited file.
Mathematica nowoadays also offers access to both current and historical stock prices, see http://reference.wolfram.com/mathematica/ref/FinancialData.html , if you happen to have a copy of it.
You have to convert string formate to required date format as following and then you can get your required result.
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2011-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1 3 13-10-2010 Low 6.0 261.54 0.04 Regular Air -213.25 38.94
80 483 10-07-2011 High 30.0 4965.7593 0.08 Regular Air 1198.97 195.99
97 613 17-06-2011 High 12.0 93.54 0.03 Regular Air -54.04 7.3
98 613 17-06-2011 High 22.0 905.08 0.09 Regular Air 127.7 42.76
103 643 24-03-2011 High 21.0 2781.82 0.07 Express Air -695.26 138.14
127 807 23-11-2010 Medium 45.0 196.85 0.01 Regular Air -166.85 4.28
128 807 23-11-2010 Medium 32.0 124.56 0.04 Regular Air -14.33 3.95
160 995 30-05-2011 Medium 46.0 1815.49 0.03 Regular Air 782.91 39.89
229 1539 09-03-2011 Low 33.0 511.83 0.1 Regular Air -172.88 15.99
230 1539 09-03-2011 Low 38.0 184.99 0.05 Regular Air -144.55 4.89
Time taken: 0.166 seconds, Fetched: 10 row(s)
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2010-12-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1 3 13-10-2010 Low 6.0 261.54 0.04 Regular Air -213.25 38.94
127 807 23-11-2010 Medium 45.0 196.85 0.01 Regular Air -166.85 4.28
128 807 23-11-2010 Medium 32.0 124.56 0.04 Regular Air -14.33 3.95
256 1792 08-11-2010 Low 28.0 370.48 0.04 Regular Air -5.45 13.48
381 2631 23-09-2010 Low 27.0 1078.49 0.08 Regular Air 252.66 40.96
656 4612 19-09-2010 Medium 9.0 89.55 0.06 Regular Air -375.64 4.48
769 5506 07-11-2010 Critical 22.0 129.62 0.05 Regular Air 4.41 5.88
1457 10499 16-11-2010 Not Specified 29.0 6250.936 0.01 Delivery Truck 31.21 262.11
1654 11911 10-11-2010 Critical 25.0 397.84 0.0 Regular Air -14.75 15.22
2323 16741 30-09-2010 Medium 6.0 157.97 0.01 Regular Air -42.38 22.84
Time taken: 0.17 seconds, Fetched: 10 row(s)
It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.
I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:
map(do_something, a_list_of_objects)
This replaces a bunch of code that looks like this:
do_something(a)
do_something(b)
do_something(c)
...
But can also be achieved with a pedestrian "for" loop:
for obj in a_list_of_objects:
do_something(obj)
The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.
You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):
[ do_something(x) for x in a_list_of_objects ]
For methods, I suppose either of these would work (with the same reservations):
map(lambda x: x.method_call(), a_list_of_objects)
or
[ x.method_call() for x in a_list_of_objects ]
So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.
orderby works on arrays that contain objects with immidiate values which can be used as filters, ie
controller.images = [{favs:1,name:"something"},{favs:0,name:"something else"}];
When the above array is repeated, you may use | orderBy:'favs' to refer to that value immidiately, or use a minus in front to order descending
<div class="timeline-image" ng-repeat="image in controller.images | orderBy:'-favs'">
<img ng-src="{{ images.name }}"/>
</div>
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
You can configure the output directory using the CONFIGURATION_BUILD_DIR
environment variable.
Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).
Long answer: here's a complete decision diagram (click to magnify).
From the threading
module documentation
There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.
There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be
join()
ed. They are never deleted, since it is impossible to detect the termination of alien threads.
So, to catch those two cases when you are not interested in keeping a list of the threads you create:
import threading as thrd
def alter_data(data, index):
data[index] *= 2
data = [0, 2, 6, 20]
for i, value in enumerate(data):
thrd.Thread(target=alter_data, args=[data, i]).start()
for thread in thrd.enumerate():
if thread.daemon:
continue
try:
thread.join()
except RuntimeError as err:
if 'cannot join current thread' in err.args[0]:
# catchs main thread
continue
else:
raise
Whereupon:
>>> print(data)
[0, 4, 12, 40]
The others got you the right answer, but I thought I'd demonstrate another neat thing you can do:
mkdir -p /tmp/a/{b,c}/d
Will create the following paths:
/tmp/a/b/d
/tmp/a/c/d
The braces allow you to create multiple directories at once on the same level of the hierarchy, whereas the -p
option means "create parent directories as needed".
Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance
f = open('{}.csv'.format(name), 'wb')
Another option - the f-string formatting (ref):
f = open(f"{name}.csv", 'wb')
The correct syntax for adding column into table is:
ALTER TABLE table_name
ADD column_name column-definition;
In your case it will be:
ALTER TABLE Employees
ADD EmployeeID int NOT NULL IDENTITY (1, 1)
To add multiple columns use brackets:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);
COLUMN
keyword in SQL SERVER is used only for altering:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
Here is the one liner i use, from terminal, to test the content of yml file(s):
$ ruby -r yaml -r pp -e 'pp YAML.load_file("/Users/za/project/application.yml")'
{"logging"=>
{"path"=>"/var/logs/",
"file"=>"TacoCloud.log",
"level"=>
{"root"=>"WARN", "org"=>{"springframework"=>{"security"=>"DEBUG"}}}}}
Since you've tagged your question 'php', I'll assume your running php on your server. Your best bet is if you control your own web server, then compile cURL into php. This will allow your web server to make requests to other web servers. This can be quite dangerous from a security point of view, so most basic web hosting providers won't have this option enabled.
Here's the php man page on using cURL. In the comments you can find an example which downloads and image file.
If you don't want to use libcurl, you could code something up using fsockopen. This is built into php (but may be disabled on your host), and can directly read and write to sockets. See Examples on the fsockopen man page.
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
From What's the Difference between WCF and Web Services?
WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use
XmlSerializer
. But WCF UsesDataContractSerializer
which is better in performance as compared toXmlSerializer
.
There's the trusty strip_tags function. It's not pretty though. It'll only sanitize. You could combine it with a string replace to get your fancy underscores.
<?php
// to strip all tags and wrap italics with underscore
strip_tags(str_replace(array("<i>", "</i>"), array("_", "_"), $text));
// to preserve anchors...
str_replace("|a", "<a", strip_tags(str_replace("<a", "|a", $text)));
?>
Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist()
on to turn them into a Python list. Alternatively you cast it with list(x)
.
import pandas as pd
data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data_dict)
print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")
col_one_list = df['one'].tolist()
col_one_arr = df['one'].to_numpy()
print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
Output:
DataFrame:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
column types:
one float64
two int64
dtype: object
col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>
col_one_arr:
[ 1. 2. 3. nan]
type:<class 'numpy.ndarray'>
if you added new target after creating Podfile, just delete Podfile, Podfile.lock , Pods folder and workspace then init pods ->then put your pods pod install
This method was posted by @lauthiamkok in the comments. I'm posting it here as an answer to call more attention to it.
Depending on your needs, you should consider using filter_var()
with the FILTER_VALIDATE_BOOLEAN
flag.
filter_var( true, FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'true', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 1, FILTER_VALIDATE_BOOLEAN); // true
filter_var( '1', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'on', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'yes', FILTER_VALIDATE_BOOLEAN); // true
filter_var( false, FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'false', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 0, FILTER_VALIDATE_BOOLEAN); // false
filter_var( '0', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'off', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('asdfasdf', FILTER_VALIDATE_BOOLEAN); // false
filter_var( '', FILTER_VALIDATE_BOOLEAN); // false
filter_var( null, FILTER_VALIDATE_BOOLEAN); // false
You can definitely try this way
.col-form-label{
display: inline-block;
width:200px;}
I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android
You can include it on your project only adding two lines into build.gradle
file thanks to jitpack.io service.
i did try this and its working in windows machine to run a sql file on a specific schema.
psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql
in 2021 to create .d.ts
file manually, you just need to do the following:
1- enter src folder
2- create global.d.ts
file
3-declare modules in it like:
declare module 'module-name';
i answred it here before and it was nice
the loginuser class uses a trait called AuthenticatesUsers
if you open that trait you will see the functions (this applies for other controllers)
Illuminate\Foundation\Auth\AuthenticatesUsers;
here is the trait code https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
sorry for the bad format, im using my phone
also Auth::routes()
it just calls a function that returns the auth routes thats it (i think)
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
you have to split the datetime and then store it with your desired format like dd/MM/yyyy. then you can use this query with between but i have objection using this becasue it will search every single data on your database,so i suggest you can use datediff.
Dim start = txtstartdate.Text.Trim()
Dim endday = txtenddate.Text.Trim()
Dim arr()
arr = Split(start, "/")
Dim dt As New DateTime
dt = New Date(Val(arr(2).ToString), Val(arr(1).ToString), Val(arr(0).ToString))
Dim arry()
arry = Split(endday, "/")
Dim dt2 As New DateTime
dt2 = New Date(Val(arry(2).ToString), Val(arry(1).ToString), Val(arry(0).ToString))
qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "
here i have used dd/MM/yyyy format.
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
Old question but adding answer so that one can get help
Its two step process:
Suppose, a table1
has a foreign key with column name fk_table2_id
, with constraint name fk_name
and table2
is referred table with key t2
(something like below in my diagram).
table1 [ fk_table2_id ] --> table2 [t2]
First step, DROP old CONSTRAINT: (reference)
ALTER TABLE `table1`
DROP FOREIGN KEY `fk_name`;
notice constraint is deleted, column is not deleted
Second step, ADD new CONSTRAINT:
ALTER TABLE `table1`
ADD CONSTRAINT `fk_name`
FOREIGN KEY (`fk_table2_id`) REFERENCES `table2` (`t2`) ON DELETE CASCADE;
adding constraint, column is already there
Example:
I have a UserDetails
table refers to Users
table:
mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`)
:
:
First step:
mysql> ALTER TABLE `UserDetails` DROP FOREIGN KEY `FK_User_id`;
Query OK, 1 row affected (0.07 sec)
Second step:
mysql> ALTER TABLE `UserDetails` ADD CONSTRAINT `FK_User_id`
-> FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`) ON DELETE CASCADE;
Query OK, 1 row affected (0.02 sec)
result:
mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES
`Users` (`User_id`) ON DELETE CASCADE
:
This works for me
/**
* Return an Object sorted by it's Key
*/
var sortObjectByKey = function(obj){
var keys = [];
var sorted_obj = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
keys.push(key);
}
}
// sort keys
keys.sort();
// create new array based on Sorted Keys
jQuery.each(keys, function(i, key){
sorted_obj[key] = obj[key];
});
return sorted_obj;
};
I combined a couple of different answers in SO into the following snippet, which should work on all, if not most, modern browsers I believe. All you have to do is add the CSS class .disable-scrollbars
onto the element you wish to apply this to.
.disable-scrollbars::-webkit-scrollbar {
width: 0px;
background: transparent; /* Chrome/Safari/Webkit */
}
.disable-scrollbars {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
}
And if you want to use SCSS/SASS:
.disable-scrollbars {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
&::-webkit-scrollbar {
width: 0px;
background: transparent; /* Chrome/Safari/Webkit */
}
}
function getStatusCode()
{
$url = 'example.com/test';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
}
print_r(getStatusCode());
Try this:
CSS:
.hidden{display:none;}
HTML:
<table id="table" class="hidden">
<tr>
<th>City</th>
<th>Status</th>
</tr>
</table>
JS:
$('#search').click(function() {
$.ajax({
type: 'POST',
url: 'cityResults.htm',
data: $('#cityDetails').serialize(),
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].city && data[i].cStatus){
txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});
Since MySQL 5.6.X you can do this:
ALTER TABLE `schema`.`users`
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
That way your column will be updated with the current timestamp when a new row is inserted, or updated.
If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
in the DEFAULT value field, like so:
http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html
I wonder why no one has mentioned this yet, but you can do an almost equivalent version using escape sequences in double quoted strings:
\x[0-9A-Fa-f]{1,2}
The sequence of characters matching the regular expression is a character in hexadecimal notation.
ASCII example:
<?php
echo("\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21");
?>
Hello World!
So for your case, all you need to do is $str = "\x30\xA2";
. But these are bytes, not characters. The byte representation of the Unicode codepoint coincides with UTF-16 big endian, so we could print it out directly as such:
<?php
header('content-type:text/html;charset=utf-16be');
echo("\x30\xA2");
?>
?
If you are using a different encoding, you'll need alter the bytes accordingly (mostly done with a library, though possible by hand too).
UTF-16 little endian example:
<?php
header('content-type:text/html;charset=utf-16le');
echo("\xA2\x30");
?>
?
UTF-8 example:
<?php
header('content-type:text/html;charset=utf-8');
echo("\xE3\x82\xA2");
?>
?
There is also the pack
function, but you can expect it to be slow.
Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!
no need to do a replacement. the regex will give you what u wanted directly:
"(?<=_)[^_]*\.jpg"
tested with grep:
echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg
("#tblEntAttributes tbody")
needs to be
$("#tblEntAttributes tbody")
.
You are not selecting the element with the correct syntax
Here's an example of both
$(newRowContent).appendTo($("#tblEntAttributes"));
and
$("#tblEntAttributes tbody").append(newRowContent);
working http://jsfiddle.net/xW4NZ/
I can handle this way:
select to_number(to_char(sysdate,'MI')) - to_number(to_char(*YOUR_DATA_VALUE*,'MI')),max(exp_time) from ...
Or if you want to the hour just change the MI;
select to_number(to_char(sysdate,'HH24')) - to_number(to_char(*YOUR_DATA_VALUE*,'HH24')),max(exp_time) from ...
the others don't work for me. Good luck.
You can setup your podfile to automatically match the deployment target of all the podfiles to your current project deployment target like this :
post_install do |pi|
pi.pods_project.targets.each do |t|
t.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'
end
end
end
Deleted the package-lock.json file & then ran
npm install
As RAND
produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND
to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)
So to produce the range you need:
SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users
The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:
[A]
JObject
isn't the elementary base type of everything in JSON.net, butJToken
is. So even though you could say,object i = new int[0];
in C#, you can't say,
JObject i = JObject.Parse("[0, 0, 0]");
in JSON.net.
What you want is JArray.Parse
, which will accept the array you're passing it (denoted by the opening [
in your API response). This is what the "StartArray" in the error message is telling you.
As for what happened when you used JArray
, you're using arr
instead of obj
:
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);
Swap that, and I believe it should work.
Although I'd be tempted to deserialize arr
directly as an IEnumerable<LocationData>
, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.
cut -d ' ' -f 2
Where 2 is the field number of the space-delimited field you want.
Or using the dplyr
library:
library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>%
group_by(ID) %>%
summarise(no_rows = length(ID))
Note the use of %>%
, which is similar to the use of pipes in bash. Effectively, the code above pipes dat
into group_by
, and the result of that operation is piped into summarise
.
The result is:
Source: local data frame [26 x 2]
ID no_rows
1 a 2
2 b 3
3 c 3
4 d 3
5 e 2
6 f 4
7 g 6
8 h 1
9 i 6
10 j 5
11 k 6
12 l 4
13 m 7
14 n 2
15 o 2
16 p 2
17 q 5
18 r 4
19 s 5
20 t 3
21 u 8
22 v 4
23 w 5
24 x 4
25 y 3
26 z 1
See the dplyr
introduction for some more context, and the documentation for details regarding the individual functions.
Thank you! This post is Very Helpful. You may also want to add
object-fit:cover;
To preserve the aspect ration for different window sizes
.carousel .item {
height: 500px;
}
.item img {
position: absolute;
object-fit:cover;
top: 0;
left: 0;
min-height: 500px;
}
For bootstrap 4 and above replace .item
with .carousel-item
.carousel .carousel-item {
height: 500px;
}
.carousel-item img {
position: absolute;
object-fit:cover;
top: 0;
left: 0;
min-height: 500px;
}
I was looking for that like crazy too and I just figured it out by trying different things :P... Well you can do it like that:
composite.something, composite.else
{
blblalba
}
It suddenly worked for me :)
we have to find label tag for attribute value based on that.we have replace label text.
Script:
<script type="text/javascript">
$(document).ready(function()
{
$("label[for*='test']").html("others");
});
</script>
Html
<label for="test_992918d5-a2f4-4962-b644-bd7294cbf2e6_FillInButton">others</label>
A binary search tree uses the definition: that for every node,the node to the left of it has a less value(key) and the node to the right of it has a greater value(key).
Where as the heap,being an implementation of a binary tree uses the following definition:
If A and B are nodes, where B is the child node of A,then the value(key) of A must be larger than or equal to the value(key) of B.That is, key(A) = key(B).
http://wiki.answers.com/Q/Difference_between_binary_search_tree_and_heap_tree
I ran in the same question today for my exam and I got it right. smile ... :)
var token = 'spo';
switch(token){
case ( (token.match(/spo/) )? token : undefined ) :
console.log('MATCHED')
break;;
default:
console.log('NO MATCH')
break;;
}
--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case
--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.
The ternary test can be anything for instance in your case
( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined
===========================================
(token.match(/spo/) )? token : undefined )
is a ternary expression.
The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).
If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).
Obviously token === token so the switch statement is matched and the case evaluated
It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.
In an Android app — for example, to allow JavaScript to have access to assets via file:///android_asset/
— use setAllowFileAccessFromFileURLs(true)
on the WebSettings
that you get from calling getSettings()
on the WebView
.
To disable next line:
// eslint-disable-next-line no-use-before-define
var thing = new Thing();
Or use the single line syntax:
var thing = new Thing(); // eslint-disable-line no-use-before-define
See the eslint docs
I believe that if you already have a package it installed, pip will not overwrite it with another version. Use -I
to ignore previous versions.
As IE6 doesn't understand attribute selectors, you can combine a script only seen by IE6 (with conditional comments) and jQuery or IE7.js by Dean Edwards.
IE7(.js) is a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6.
The choice of using classes or jQuery or IE7.js depends on your likes and dislikes and your other needs (maybe PNG-24 transparency throughout your site without having to rely on PNG-8 with complete transparency that fallbacks to 1-bit transparency on IE6 - only created by Fireworks and pngnq, etc)
from platform import python_version
print(python_version())
This will give you the exact version of python running your script. eg output:
3.6.5
As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.
The solution at my end was to explicitly add a JoinColumn annotation like this:
@JoinColumn(name="mapping_type_id")
The column name is usually the table name + "_id" if there is an id field. Additionally, keep in mind which field it should be based on the relationship, OneToMany or ManyToOne.
Hope this helps.
Many built-in operations like sum
and prod
are already able to operate across rows or columns, so you may be able to refactor the function you are applying to take advantage of this.
If that's not a viable option, one way to do it is to collect the rows or columns into cells using mat2cell
or num2cell
, then use cellfun
to operate on the resulting cell array.
As an example, let's say you want to sum the columns of a matrix M
. You can do this simply using sum
:
M = magic(10); %# A 10-by-10 matrix
columnSums = sum(M, 1); %# A 1-by-10 vector of sums for each column
And here is how you would do this using the more complicated num2cell
/cellfun
option:
M = magic(10); %# A 10-by-10 matrix
C = num2cell(M, 1); %# Collect the columns into cells
columnSums = cellfun(@sum, C); %# A 1-by-10 vector of sums for each cell