int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) DetailView.this
.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText("" + yourMessage.toString());
Toast.makeText(AppCstVar.getAppContext(),
"" + getResources().getString(R.string.txt_copiedtoclipboard),
Toast.LENGTH_SHORT).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) DetailView.this
.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("message", "" + yourMessage.toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(AppCstVar.getAppContext(),
"" + getResources().getString(R.string.txt_copiedtoclipboard),
Toast.LENGTH_SHORT).show();
}
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.
int lower(int a)
{
return a | ' ';
}
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
These two classes can work together to schedule a periodic task:
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
You can also use an object-oriented path with pathlib
(available as a standard library as of Python 3.4):
from pathlib import Path
start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'
I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder.
Try
SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber
For more information see: Querying for version/edition info
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fields$str = "
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill";
echo str_replace(array("\n", "\r"), '', $str); // echo $str in a single line
Use & for this. Using & you can put as many variables as you want!
$url = "http://localhost/main.php?event_id=".$event_id."&email=".$email;
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
I meant in the template()
call..
You just need to pass the results as an object. So instead of calling
var html = template(data);
do
var html = template({apidata: data});
and use {{#each apidata}}
in your template code
demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if
code that crashed)
Best and easiest solution:
For each page you want your respective link to change color to until switched, put an internal style in EACH PAGE for the VISITED attribute and make each an individual class in order to differentiate between links so you don't apply the feature to all accidentally. We'll use white as an example:
<style type="text/css">
.link1 a:visited {color:#FFFFFF;text-decoration:none;}
</style>
For all other attributes such as LINK, ACTIVE and HOVER, you can keep those in your style.css. You'll want to include a VISITED there as well for the color you want the link to turn back to when you click a different link.
In my case I created an async test method which returned void
. Returning of Task
instead of void
solved the issue.
To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.
<select class="form-control glyphicon">
<option value="">− − − Hello</option>
<option value="glyphicon-list-alt"> Text</option>
</select>
Here's a list of the icons with their unicode:
If this is MS Sql Server then what you have should work fine... In fact, technically, you don;t need the Begin & End at all, snce there's only one statement in the begin-End Block... (I assume @Classes is a table variable ?)
If @Term = 3
INSERT INTO @Classes
SELECT XXXXXX
FROM XXXX blah blah blah
-- -----------------------------
-- This next should always run, if the first code did not throw an exception...
INSERT INTO @Classes
SELECT XXXXXXXX
FROM XXXXXX (more code)
MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…
SELECT * FROM `table` WHERE `column` = 'value'
The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY
operator, which forces a byte by byte comparison:
SELECT * FROM `table` WHERE BINARY `column` = 'value'
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
You could build your own replace function using strstr to find the substrings and strncpy to copy in parts to a new buffer.
Unless what you want to replace_with
is the same length as what you you want to replace
, then it's probably best to use a new buffer to copy the new string to.
What worked for me was:
I had a process called "mysqld" running even when MAMP had been quit. I force quit the process, restarted MAMP and it worked again.
setState()
has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:
// Form Input
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
this.findRoutes // here is where you put the callback
);
Notice the call to findRoutes
is now inside the setState()
call,
as the second parameter.
Without ()
because you are passing the function.
To begin with, this line of code:
while ((bytesRead = fis.read(byteArray)) != -1)
is equivalent to
while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)
So it's writing into the byteArray from offset 0, rather than from where you wrote to before.
You need something like this:
int offset = 0;
int bytesRead = 0;
while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
offset += bytesRead;
}
After you have read the data (bytes) in then, you can convert it to Base64.
There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.
I would ditch the byte array and go with something like this:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);
Or condense it further as Thilo has with FileUtils.
application/vnd.ms-excel
vnd class
/ vendor specificI encountered the same problem today. I did heroku run rake db:migrate
though I migrated the model before, and the app doesn't crash.
I just use for _ in range(n)
, it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.
You can use this for font
create a Class Name TypefaceTextView and extend the TextView
private static Map mTypefaces;
public TypefaceTextView(final Context context) {
this(context, null);
}
public TypefaceTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (mTypefaces == null) {
mTypefaces = new HashMap<String, Typeface>();
}
if (this.isInEditMode()) {
return;
}
final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
if (array != null) {
final String typefaceAssetPath = array.getString(
R.styleable.TypefaceTextView_customTypeface);
if (typefaceAssetPath != null) {
Typeface typeface = null;
if (mTypefaces.containsKey(typefaceAssetPath)) {
typeface = mTypefaces.get(typefaceAssetPath);
} else {
AssetManager assets = context.getAssets();
typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
mTypefaces.put(typefaceAssetPath, typeface);
}
setTypeface(typeface);
}
array.recycle();
}
}
paste the font in the fonts folder created in the asset folder
<packagename.TypefaceTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:text="TRENDING TURFS"
android:textColor="#000"
android:textSize="20sp"
app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**
Place the lines in the parent layout in the xml
xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"
As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea
has newline characters, at least on Windows.
I've change his answer slightly thus:
$(function() {
$("textarea[maxlength]").bind('input propertychange', function() {
var maxLength = $(this).attr('maxlength');
//I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
//Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
var newlines = ($(this).val().match(/\n/g) || []).length
if ($(this).val().length + newlines > maxLength) {
$(this).val($(this).val().substring(0, maxLength - newlines));
}
})
});
Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.
Even if this would seem super simple, sometimes it's really useful. If all you need is to see if two arrays have the same items and they are in the same order, try this:
[1, 2, 3].toString() == [1, 2, 3].toString()
true
[1, 2, 3,].toString() == [1, 2, 3].toString()
true
[1,2,3].toString() == [1, 2, 3].toString()
true
However, this doesn't work for mode advanced cases such as:
[[1,2],[3]].toString() == [[1],[2,3]].toString()
true
It depends what you need.
public static class EnumEx
{
public static T GetValueFromDescription<T>(string description) where T : Enum
{
foreach(var field in typeof(T).GetFields())
{
if (Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if (field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", nameof(description));
// Or return default(T);
}
}
Usage:
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
This has been discussed into spark mailing list, and please refer this mail.
You should use hadoop fs -put <localsrc> ... <dst>
copy the file into hdfs
:
${HADOOP_COMMON_HOME}/bin/hadoop fs -put /path/to/README.md README.md
Here is how I do it:
var hashTagActive = "";
$(".scroll").on("click touchstart" , function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().top;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
Then you just need to create your anchor like this:
<a class="scroll" href="#destination1">Destination 1</a>
You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/
Is that an actual compiler error or a Code Analysis error? Some times the code analysis can be a bit sketchy and report non-valid errors.
To turn off code analysis for the project, right click on your project in the Project Explorer, click on Properties, then go to the C/C++ General tab, then Code Analysis. Then click on "Use Project Settings" and disable the ones that you do not wish for.
Also, are you sure you are compiling with the C++11 compiler?
Hope this will fix your problem, i usually work with this when i need to execute forEach with asynchronous tasks inside.
foo = [a,b,c,d];
waiting = foo.length;
foo.forEach(function(entry){
doAsynchronousFunction(entry,finish) //call finish after each entry
}
function finish(){
waiting--;
if (waiting==0) {
//do your Job intended to be done after forEach is completed
}
}
with
function doAsynchronousFunction(entry,callback){
//asynchronousjob with entry
callback();
}
I got this working by editing my site's HTTP handlers. For my needs this works well and resolves my issue.
I simply added a new HTTP handler that looks for specific path criteria. If the request matches it is correctly sent to .NET for processing. I'm much happier with this solution that the URLRewrite hack or enabling RAMMFAR.
For example to have .NET process the URL www.example.com/people/michael.phelps add the following line to your site's web.config within the system.webServer / handlers
element:
<add name="ApiURIs-ISAPI-Integrated-4.0"
path="/people/*"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
Edit
There are other posts suggesting that the solution to this issue is RAMMFAR
or RunAllManagedModulesForAllRequests
. Enabling this option will enable all managed modules for all requests. That means static files such as images, PDFs and everything else will be processed by .NET when they don't need to be. This options is best left off unless you have a specific case for it.
In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.
Checking the install state for the product via MsiQueryProductState is pretty much equivalent to checking the registry directly, but you still need the GUID for the ProductCode.
As mentioned elsewhere, one drawback with these approaches is that each update has its own ProductCode!
Thankfully, MSI provides an UpgradeCode which identifies a 'family' of products. You can use orca to open up one of the MSIs to extract this information. For example, the UpgradeCode for VS2015's redistributable is {65E5BD06-6392-3027-8C26-853107D3CF1A}
You can use MsiEnumRelatedProducts to get all Product IDs for that UpgradeCode. In practice, since each redist update replaces the previous one, this will only yield one ProductCode - such as {B5FC62F5-A367-37A5-9FD2-A6E137C0096F}
for VS2015 Update 2 x86.
Regardless, you can then check the version via MsiGetProductInfo(productCode, INSTALLPROPERTY_VERSIONSTRING, ...) or similar functions to compare with the version you want, eg to check for an equivalent or later version.
Note that within a C++ application, you can also use _VC_CRT_MAJOR_VERSION
, _VC_CRT_MINOR_VERSION
, _VC_CRT_BUILD_VERSION
if you #include <crtversion.h>
-- this way you can determine calculate the CRT version that your binary was built with.
The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
I could not get the mount command to work without specifying the dev block to mount as /system
#cat /proc/mounts
returns ( only the system line here )
/dev/stl12 /system rfs ro,relatime,vfat,log_off,check=no,gid/uid/rwx,iocharset=utf8 0 0
so my working command is
mount -o rw,remount -t rfs /dev/stl12 /system
Current date time to formated string:
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a"
let convertedDate: String = dateFormatter.string(from: currentDate) //08/10/2016 01:42:22 AM
I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine
I also had this problem on Ubuntu 16.04.
Fixed by running sudo apt-get install graphviz
in addition to the pip install I had already performed.
Replacing localhost with 10.0.2.2 is correct, but you can alsor replace localhost with your physical machine's ip(it is better for debug purposes). Ofc, if ip is provided by dhcp you would have to change it each time...
Good luck!
myElement.innerText = myElement.textContent = "foo";
Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.
All of the answers here use the Class.forName("my.vandor.Driver");
line to load the driver.
As an (better) alternative you can use the DriverManager
helper class which provides you with a handful of methods to handle your JDBC driver/s.
You might want to
DriverManager.registerDriver(driverObject);
to register your driver to it's list of driversRegisters the given driver with the DriverManager. A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager. If the driver is currently registered, no action is taken
DriverManager.deregisterDriver(driverObject);
to remove it.Removes the specified driver from the DriverManager's list of registered drivers.
Example:
Driver driver = new oracle.jdbc.OracleDriver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
// ...
// and when you don't need anything else from the driver
DriverManager.deregisterDriver(driver);
or better yet, use a DataSource
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
I came across this as well, for me this has worked (covers most browsers):
myString.replace(/[\s\uFEFF\xA0]/g, ';');
Inspired by this trim polyfill after hitting some bumps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill
Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li>
elements with class="dropdown-menu"
. It automatically displays the proper caret indicator as well.
<head>
...
<script src=".../jquery.smartmenus.min.js"></script>
<script src=".../jquery.smartmenus.bootstrap.min.js"></script>
...
<link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
...
</head>
Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html
I set .navbar-brand { min-height: inherit }
which solved the issue for me (thanks @creimers for inspiration).
For small files, you may consider using more_itertools.seekable
- a third-party tool that offers resetting iterables.
Demo
import csv
import more_itertools as mit
filename = "data/iris.csv"
with open(filename, "r") as f:
reader = csv.DictReader(f)
iterable = mit.seekable(reader) # 1
print(next(iterable)) # 2
print(next(iterable))
print(next(iterable))
print("\nReset iterable\n--------------")
iterable.seek(0) # 3
print(next(iterable))
print(next(iterable))
print(next(iterable))
Output
{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}
Reset iterable
--------------
{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}
Here a DictReader
is wrapped in a seekable
object (1) and advanced (2). The seek()
method is used to reset/rewind the iterator to the 0th position (3).
Note: memory consumption grows with iteration, so be wary applying this tool to large files, as indicated in the docs.
For completeness, if "AllowOverride All" doesn't fix your problem, you could debug this problem using:
Run apachectl -S
and see if you have more than one namevhost. It might be that httpd is looking for .htaccess of another DocumentRoot.
Use strace -f apachectl -X
and look for where it's loading (or not loading) .htaccess from.
I've done it this way.
Added an event listener on document click
and in that handler checked if my container
contains event.target
, if not - hide the dropdown.
It would look like this.
@Component({})
class SomeComponent {
@ViewChild('container') container;
@ViewChild('dropdown') dropdown;
constructor() {
document.addEventListener('click', this.offClickHandler.bind(this)); // bind on doc
}
offClickHandler(event:any) {
if (!this.container.nativeElement.contains(event.target)) { // check click origin
this.dropdown.nativeElement.style.display = "none";
}
}
}
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
I never use "struct" in C++.
I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.
It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.
E.g.
class PublicInputData {
//data members
};
If you wish to load them by webpack you can simply use :src='require('path/to/file')'
Make sure you use :
otherwise it won't execute the require statement as Javascript.
In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"
Why the following is generally considered bad practice:
<template>
<div id="app">
<img src="./assets/logo.png">
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss">
</style>
When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static
folder and use: <img src="./static/logo.png">
Assuming timestamp is the index of the data frame, you can just do the following:
hours = sales.index.hour
If you want to add that to your sales data frame, just do:
import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)
Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:
hours = sales['date'].hour
Edit2:
If you want to adjust a column in your data frame you have to include dt
:
sales['datehour'] = sales['date'].dt.hour
React uses event delegation with a single event listener on document
for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation
on React's synthetic event is possible because React handles propagation of synthetic events internally.
Use Event.stopImmediatePropagation
to prevent your other (jQuery in this case) listeners on the root from being called. It is supported in IE9+ and modern browsers.
stopPropagation: function(e){
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
},
Your jQuery code uses event delegation as well, which means calling stopPropagation
in the handler is not stopping anything; the event has already propagated to document
, and React's listener will be triggered.
// Listener bound to `document`, event delegation
$(document).on('click', '.stop-propagation', function(e){
e.stopPropagation();
});
To prevent propagation beyond the element, the listener must be bound to the element itself:
// Listener bound to `.stop-propagation`, no delegation
$('.stop-propagation').on('click', function(e){
e.stopPropagation();
});
Edit (2016/01/14): Clarified that delegation is necessarily only used for events that bubble. For more details on event handling, React's source has descriptive comments: ReactBrowserEventEmitter.js.
The second is almost correct:
{
"foos" : [{
"prop1":"value1",
"prop2":"value2"
}, {
"prop1":"value3",
"prop2":"value4"
}]
}
You can also try this
First, install python-decouple
pip install python-decouple
import it in your file
from decouple import config
Then get the env variable
SECRET_KEY=config('SECRET_KEY')
Read more about the python library here
this condition chick all cases.
function del() {_x000D_
//chick if dom has this element _x000D_
//if not true condition means null or undifind or false ._x000D_
_x000D_
if (!document.querySelector("#ul_list ")===true){_x000D_
_x000D_
// msg to user_x000D_
alert("click btn load ");_x000D_
_x000D_
// if console chick for you and show null clear console._x000D_
console.clear();_x000D_
_x000D_
// the function will stop._x000D_
return false;_x000D_
}_x000D_
_x000D_
// if its true function will log delet ._x000D_
console.log("delet");_x000D_
_x000D_
}
_x000D_
cduruk's solution was quite effective, but caused problems on a few parts of my site. Because I was already using jQuery to add the CSS hover class, the easiest solution was to simply not add the CSS hover class on mobile devices (or more precisely, to ONLY add it when NOT on a mobile device).
Here was the general idea:
var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);
if (!(ios)) {
$(".portfolio-style").hover(
function(){
$(this).stop().animate({opacity: 1}, 100);
$(this).addClass("portfolio-red-text");
},
function(){
$(this).stop().animate({opacity: 0.85}, 100);
$(this).removeClass("portfolio-red-text");
}
);
}
*code reduced for illustrative purposes
I had this problem plaguing me, and upon further investigation (running rake db:setup
), I saw that rails was trying to connect to a previously used postgres instance - one which was stored in env variables as DATABASE_URL.
The fix: unset DATABASE_URL
Let's say you have the DLLs build for both platforms, and they are in the following location:
C:\whatever\x86\whatever.dll
C:\whatever\x64\whatever.dll
You simply need to edit your .csproj file from this:
<HintPath>C:\whatever\x86\whatever.dll</HintPath>
To this:
<HintPath>C:\whatever\$(Platform)\whatever.dll</HintPath>
You should then be able to build your project targeting both platforms, and MSBuild will look in the correct directory for the chosen platform.
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
It's crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say "default" because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.
When it comes to null
and blank
, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:
null=False
, blank=False
: This is the default configuration and means that the value is required in all circumstances.
null=True
, blank=True
: This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)
null=False
, blank=True
: This means that the form doesn't require a value but the database does. There are a number of use cases for this:
The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL
was also allowed you would end up with two different ways to indicate a missing value.
Another common situation is that you want to calculate one field automatically based on the value of another (in your save()
method, say). You don't want the user to provide the value in a form (hence blank=True
), but you do want the database to enforce that a value is always provided (null=False
).
Another use is when you want to indicate that a ManyToManyField
is optional. Because this field is implemented as a separate table rather than a database column, null
is meaningless. The value of blank
will still affect forms, though, controlling whether or not validation will succeed when there are no relations.
null=True
, blank=False
: This means that the form requires a value but the database doesn't. This may be the most infrequently used configuration, but there are some use cases for it:
It's perfectly reasonable to require your users to always include a value even if it's not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn't need the same stringent validation that you want to require of a human editor.
Another use case that I've seen is when you have a ForeignKey
for which you don't wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False
), but if the thing it points to happens to be deleted, you don't want this object to be deleted too. In that case you can use null=True
and on_delete=models.SET_NULL
to implement a simple kind of soft deletion.
There are two ways to resolve this error:
Include /etc/apache2/httpd.conf
Add the above line in file /etc/apache2/apache2.conf
Add this line at the end of the file /etc/apache2/apache2.conf:
ServerName localhost
I am using this script after I rename my iOS Project. It helps to change the directories name and make the names in sync.
http://github.com/ytbryan/rename
NOTE: you will need to manually change the scheme's name.
I struggled with this myself, and tried Tomik's answer. However, this didn't made the layout to full available width on start, only when you add something to the view.
You'll need to set the LayoutParams.FILL_PARENT
when adding the view:
//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout);
This way it completely fills the available space. (You may need to use Tomik's solution too).
You need to check whether the existing string plus the input is greater than 10.
func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
NSUInteger newLength = textField.text.length + string.length - range.length;
return !(newLength > 10)
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
Thanks to Damian...
TCP/IP Named Pipes ... both enabled
Web Config....(for localhost)
<add name="FooData" connectionString="Data Source=localhost\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.
The command line would be done this way:
c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt
and the java code accesses the value like this:
String context = System.getProperty("myvar");
See this question about argument passing in Java.
The link below, gives a very good tutorial, about playing mp3 files from a windows form with c#:
http://www.daniweb.com/software-development/csharp/threads/292695/playing-mp3-in-c
This link will lead you to a topic, which contains a lot information about how to play an mp3 song, using Windows forms. It also contains a lot of other projects, trying to achieve the same thing:
For example use this code for .mp3:
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "My MP3 file.mp3";
wplayer.Controls.Play();
Then only put the wplayer.Controls.Play(); in the Button_Click event.
For example use this code for .wav:
System.Media.SoundPlayer player = new System.Media.SoundPlayer();
player.SoundLocation = "Sound.wav";
player.Play();
Put the player.Play(); in the Button_Click event, and it will work.
You can use the @Qualifier annotation
From here
Fine-tuning annotation-based autowiring with qualifiers
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:
class Main {
private Country country;
@Autowired
@Qualifier("country")
public void setCountry(Country country) {
this.country = country;
}
}
This will use the UK add an id to USA bean and use that if you want the USA.
You also need to change the DataSource
of the connection string. KELVIN-PC
is the name of your local machine and the sql server is running on the default instance.
If you are sure the the server is running as the default instance, you can always use .
in the DataSource, eg.
connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"
otherwise, you need to specify the name of the instance of the server,
connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"
I think you are looking for this: RowHeaderMouseDoubleClick event
private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}
to get the row index:
int indice = e.RowIndex
I ran mine with Genymotion, probably the best for Flutter.
Setting up is less painful and
Make sure setting ADB under
--YOUR ANDROID SDK PATH --
Mine is C:\Users\user\AppData\Local\Android\Sdk
Note that dangerouslySetInnerHTML
can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.
It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.
Example:
import DOMPurify from 'dompurify'
const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
);
}
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
I had to run Xcode.app and agree to the License Agreement
Setup: Brand new MacBook with Mavericks, then brew install and other c/l type things 'just work'.
I suggest use the common way of import.
First I will explain the way it called "relative import" maybe this way cause of some error
Second I will explain the common way of import.
FIRST:
In go version >= 1.12 there is some new tips about import file and somethings changed.
1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"
2- You have to use uppercase when you want to import a file!
3- Use Uppercase for variables, structures and functions that you want to import in another files
Notice: There is no way to import the main.go in another file.
file directory is:
root
|_____main.go
|_____model
|_____example.go
this is a example.go:
package model
import (
"time"
)
var StartTime = time.Now()
and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase
package main
import (
Mod "./model"
"fmt"
)
func main() {
fmt.Println(Mod.StartTime)
}
NOTE!!!
NOTE: I don't recommend this this type of import!
SECOND:
(normal import)
the better way import file is:
your structure should be like this:
root
|_____github.com
|_________Your-account-name-in-github
| |__________Your-project-name
| |________main.go
| |________handlers
| |________models
|
|_________gorilla
|__________sessions
and this is a example:
package main
import (
"github.com/gorilla/sessions"
)
func main(){
//you can use sessions here
}
so you can import "github.com/gorilla/sessions" in every where that you want...just import it.
System.exit(0);
Is probably what you are looking for. It will close the entire application and take you to the home Screen.
you can follow this tutorial
http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/
it helped me to do a push notification; or you can follow this other tutorial
http://www.tutorialeshtml5.com/2013/10/tutorial-simple-de-gcm-traves-de-php.html
but it's in spanish but you can download the code.
I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.
Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.
If you did this:
SomeClass object = ...
String s = object.toString();
then the answer is that there is no simple way to turn s
back into an instance of SomeClass
. You couldn't do it even if the toString()
method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)
The only way you could turn the output of toString
back into an object would be to:
SomeClass.toString()
method so that included all relevant state for the object in the String it produced, andtoString()
method.This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.
If you did something like this:
SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();
then you could get the same Class
object back (i.e. the one that is in c
) as follows:
Class c2 = Class.forName(cn);
This gives you the Class
but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)
If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString()
method at all. Here are some alternatives that you can use:
Each of these approaches has advantages and disadvantages ... which I won't go into here.
var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );
This will set the value
of the checkbox to "true"
or "false"
(value property
is a string)
, depending whether it's unchecked
or checked
.
Works in jQuery >= 1.0
You can try this:
import subprocess
import sys
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
If you use readline instead of read, there will be some cases where the input message is not printed. Try it with a command the requires an inline input and see for yourself.
Okay. Answer for self hosted wordpress installations - you'll have to find the file yourself. For my WordPres site I use nginx with php7.3-fpm.
Running php -i | grep ini
from console gives me several lines including:
Loaded Configuration File => /etc/php/7.3/cli/php.ini
. This is ini configuration when running php
command from command line, a.k.a. cli.
Then looking around I see there is also a file: /etc/php/7.3/fpm/php.ini
I use FPM service so that is it! I edit it and THEN reload the service to apply my changes using: service php7.3-fpm reload
.
That was it. Now I can upload bigger files to my WordPress. Good luck
You'll definitely want to check out this positioning article from 'A List Apart'. Helped demystify CSS positioning (which seemed insane to me, prior to this article).
Change localhost:8080 to localhost:3306.
In my case I forgot it was packaging conflict jar vs pom. I forgot to write
<packaging>pom</packaging>
In every child pom.xml file
It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0
Try something like this:
pid_t pid;
pid = fork();
if (pid == 0)
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
else
printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );
I've found that the best way to debug is to use the microsoft tool called DTCPing
I've had my fare deal of problems in our old company network, and I've got a few tips:
In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.
Edit:
Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion
is 21 or higher, the multidex support library is not needed.
Modify your build.gradle
:
android {
compileSdkVersion 22
buildToolsVersion "23.0.0"
defaultConfig {
minSdkVersion 14 //lower than 14 doesn't support multidex
targetSdkVersion 22
// Enabling multidex support.
multiDexEnabled true
}
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
If you are running unit tests, you will want to include this in your Application
class:
public class YouApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
Or just make your application
class extend MultiDexApplication
public class Application extends MultiDexApplication {
}
For more info, this is a good guide.
For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0
Just use the . at the end of the git clone
command (being in that directory), like this:
cd your_dir_to_clone_in/
git clone [email protected]/somerepo/ .
If you already have python3 installed as well virtualenvwrapper the only thing you would need to do to use python3 with the virtual environment is creating an environment using:
which python3 #Output: /usr/bin/python3
mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment
Or, (at least on OSX using brew):
mkvirtualenv --python=`which python3` nameOfEnvironment
Start using the environment and you'll see that as soon as you type python you'll start using python3
One-liner using Java 8 Stream API:
map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue))
Among the benefits of this method is ability to pass a merge function, which will deal with values that have the same key, for example:
map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, Math::max))
I was able to unistall jdk 8 in mavericks successfully doing the following steps:
Run this command to just remove the JDK
sudo rm -rf /Library/Java/JavaVirtualMachines/jdk<version>.jdk
Run these commands if you want to remove plugins
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist
std::hex
is defined in <ios>
which is included by <iostream>
. But to use things like std::setprecision/std::setw/std::setfill
/etc you have to include <iomanip>
.
Inside your component class:
checkValue(event: any) {
this.userForm.patchValue({
state: event
})
}
Now in controls you have value A or B
git pull origin master
will fetch all the changes from the remote's master branch and will merge it into your local.We generally don't use git pull origin/master.We can do the same thing by git merge origin/master
.It will merge all the changes from "cached copy" of origin's master branch into your local branch.In my case git pull origin/master
is throwing the error.
Since you're using Ubuntu, and not Kubuntu, I assume you're using GNOME. You might be interested in Nautilus Subversion Integration described on that link.
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
Actually you don't have to create an image at all. drawImage()
will accept a Canvas
as well as an Image
object.
//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');
//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);
Way faster than using an ImageData
object or Image
element.
Note that sourceCanvas
can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas
.
Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element
The plugin Media File Manager advanced is amazing and allow you to create folders and subfolders very easily and move files with a simple drag & drop.
Check it at: http://wordpress.org/plugins/media-file-manager-advanced/
If you are using Outlook to send a static image with hyperlink, an easy way would be to use Word.
Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.
Check out this site.
Problem array:
array:2 [?
0 => array:3 [?
0 => array:4 [?
"id" => 8
"name" => "Veggie Burger"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [?
"id" => 9
"name" => "Veggie Pitta"
"image" => ""
"Category_type" => "product"
]
2 => array:4 [?
"id" => 10
"name" => "Veggie Wrap"
"image" => ""
"Category_type" => "product"
]
]
1 => array:2 [?
0 => array:4 [?
"id" => 18
"name" => "Cans 330ml"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [?
"id" => 19
"name" => "Bottles 1.5 Ltr"
"image" => ""
"Category_type" => "product"
]
]
]
Solution array:
array:5 [?
0 => array:4 [?
"id" => 8
"name" => "Veggie Burger"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [?
"id" => 9
"name" => "Veggie Pitta"
"image" => ""
"Category_type" => "product"
]
2 => array:4 [?
"id" => 10
"name" => "Veggie Wrap"
"image" => ""
"Category_type" => "product"
]
3 => array:4 [?
"id" => 18
"name" => "Cans 330ml"
"image" => ""
"Category_type" => "product"
]
4 => array:4 [?
"id" => 19
"name" => "Bottles 1.5 Ltr"
"image" => ""
"Category_type" => "product"
]
]
Write this code and get your solution , $subcate
is your multi dimensional array.
$singleArrayForCategory = array_reduce($subcate, 'array_merge', array());
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
If you need to call is asynchronously then use
var request = HttpWebRequest.Create("http://www.maplegraphservices.com/tokkri/webservices/updateProfile.php?oldEmailID=" + App.currentUser.email) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/json";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Create the post data
string postData = JsonConvert.SerializeObject(edit).ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
//Start the web request
request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);
}
void GetResponceStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
stat.Text = result;
}
}
Something like...
DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);
Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());
Which outputs
1
24
1440
or
System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());
Which is probably more what you're after
You can use mosquitto_sub
(which is part of the mosquitto-clients
package) and subscribe to the wildcard topic #
:
mosquitto_sub -v -h broker_ip -p 1883 -t '#'
Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Relative answer: Deploying website: 500 - Internal server error
By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.
I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.
I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:
adb server is out of date. killing...
cannot bind 'tcp:5037'
ADB server didn't ACK
*failed to start daemon*
error:
So I tried adb connect [ip]
as suggested here, but I didn't work either, the same error came up.
What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices
will give me the error above, but /yourdownloadpath/adb devices
works just fine for me.
Hope it helped.
The shortest:
command || exit /b
If you need, you can set the exit code:
command || exit /b 666
And you can also log:
command || echo ERROR && exit /b
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
DATEADD (datepart , number , date )
declare @num_hours int;
set @num_hours = 5;
select dateadd(HOUR, @num_hours, getdate()) as time_added,
getdate() as curr_date
If you are running local using spring i'd suggest use:
@Bean
public AmazonDynamoDB amazonDynamoDB() throws IOException {
return AmazonDynamoDBClientBuilder.standard()
.withCredentials(
new AWSStaticCredentialsProvider(
new BasicAWSCredentials("fake", "credencial")
)
)
.withClientConfiguration(new ClientConfigurationFactory().getConfig().withProtocol(Protocol.HTTP))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("localhost:8443", "central"))
.build();
}
It works for me using unit test.
Hope it's help!
Here has an easy way to solve this.
<?php
$date = "2015-11-17";
echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>
Output will be:
2015-11-22
Solution has found from here - How to Add Days to Date in PHP
From the manual:
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule
on your ObjectMapper
.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
For custom serialization/de-serialization of DateTime
, you need to implement your own StdScalarSerializer
and StdScalarDeserializer
; it's pretty convoluted, but anyway.
For example, here's a DateTime
serializer that uses the ISODateFormat
with the UTC time zone:
public class DateTimeSerializer extends StdScalarSerializer<DateTime> {
public DateTimeSerializer() {
super(DateTime.class);
}
@Override
public void serialize(DateTime dateTime,
JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonGenerationException {
String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
jsonGenerator.writeString(dateTimeAsString);
}
}
And the corresponding de-serializer:
public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {
public DateTimeDesrializer() {
super(DateTime.class);
}
@Override
public DateTime deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
JsonToken currentToken = jsonParser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
String dateTimeAsString = jsonParser.getText().trim();
return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
}
} finally {
throw deserializationContext.mappingException(getValueClass());
}
}
Then tie these together with a module:
public class DateTimeModule extends SimpleModule {
public DateTimeModule() {
super();
addSerializer(DateTime.class, new DateTimeSerializer());
addDeserializer(DateTime.class, new DateTimeDeserializer());
}
}
Then register the module on your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());
The following code is something I use extensively. I found the script in a forum, but modified and expanded it to accommodate my needs:
<script type="text/javascript">
// Restrict user input in a text field
// create as many regular expressions here as you need:
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;
var usernameOnly = /[0-9A-Za-z\._-]/g;
function restrictInput(myfield, e, restrictionType, checkdot){
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if user pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if the user presses other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
if(checkdot == "checkdot"){
return !isNaN(myfield.value.toString() + character);
} else {
return true;
}
} else {
return false;
}
}
}
</script>
Different usage methods would be:
<!-- To accept only alphabets -->
<input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
<!-- To accept only numbers without dot -->
<input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
<!-- To accept only numbers and dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
<!-- To accept only numbers and only one dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
<!-- To accept only characters for a username field -->
<input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">
Static methods (in fact all methods) as well as static variables are stored in the PermGen
section of the heap, since they are part of the reflection data (class related data, not instance related).
Update for clarification:
Note that only the variables and their technical values (primitives or references) are stored in PermGen space.
If your static variable is a reference to an object that object itself is stored in the normal sections of the heap (young/old generation or survivor space). Those objects (unless they are internal objects like classes etc.) are not stored in PermGen space.
Example:
static int i = 1; //the value 1 is stored in the PermGen section
static Object o = new SomeObject(); //the reference(pointer/memory address) is stored in the PermGen section, the object itself is not.
A word on garbage collection:
Do not rely on finalize()
as it's not guaranteed to run. It is totally up to the JVM to decide when to run the garbage collector and what to collect, even if an object is eligible for garbage collection.
Of course you can set a static variable to null and thus remove the reference to the object on the heap but that doesn't mean the garbage collector will collect it (even if there are no more references).
Additionally finalize()
is run only once, so you have to make sure it doesn't throw exceptions or otherwise prevent the object to be collected. If you halt finalization through some exception, finalize()
won't be invoked on the same object a second time.
A final note: how code, runtime data etc. are stored depends on the JVM which is used, i.e. HotSpot might do it differently than JRockit and this might even differ between versions of the same JVM. The above is based on HotSpot for Java 5 and 6 (those are basically the same) since at the time of answering I'd say that most people used those JVMs. Due to major changes in the memory model as of Java 8, the statements above might not be true for Java 8 HotSpot - and I didn't check the changes of Java 7 HotSpot, so I guess the above is still true for that version, but I'm not sure here.
In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code goes here
2 * 2
# etc
# etc
})})
```
The code will run, but the output will not be printed to the HTML document
In my opinion it depends, it can be seen from the needs of your application, why decide to deploy to Docker because Docker breaks the application into small parts according to its function, this becomes effective because when one application / function is an error it has no effect on other applications , in contrast to using full vm, it will be slower and more complex in configuration, but in some ways safer than docker
You can use the latest version of the jQuery library by any of the following.
Google Ajax API CDN (also supports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2"></script>
/jquery.min.js
Microsoft CDN (also aupports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
Ajax CDN Announcement, Microsoft Ajax CDN Documentation
jQuery CDN (via Media Temple)
<script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
** Minified version
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
** Development (Full) version
Assign position:relative
to .outside
, and then position:absolute; bottom:0;
to your .inside
.
Like so:
.outside {
position:relative;
}
.inside {
position: absolute;
bottom: 0;
}
@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
return "Response!";
}
@ResponseBody
?It's telling that the method returns some text and not to interpret it as a view etc.
produces="text/plain"
?It's just a good practice as it tells what will be returned from the method :)
The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.
Combination of Dasha's and MMT solutions:
Ext.getCmp('yourGridId').getView().ds.reload();
Still surprised that no one proposed the shortest solution with align-center justify-center
to center content vertically and horizontally. Check this CodeSandbox and code below:
<v-container fluid fill-height>
<v-layout align-center justify-center>
<v-flex>
<!-- Some HTML elements... -->
</v-flex>
</v-layout>
</v-container>
The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing
has changed:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install
You could use dict.fromkeys as follows:
dict.fromkeys([1, 2, 3, 4], list())
This will create a list object for each key. If you change value for any specific key it won't affect other keys (as most people would want, I presume).
Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.
It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.
Removing the range select before the copy worked for me. Thanks for the posts.
The props vs state summary I like best is here: react-guide Big hat tip to those guys. Below is an edited version of that page:
tl;dr If a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.
Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.
The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.
A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.
props state Can get initial value from parent Component? Yes Yes Can be changed by parent Component? Yes No Can set default values inside Component?* Yes Yes Can change inside Component? No Yes Can set initial value for child Components? Yes Yes Can change in child Components? Yes No
State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can't do without state in an interactive app, you should avoid having too many Stateful Components.
Stateless Component Only props, no state. There's not much going on besides the render() function. Their logic revolves around the props they receive. This makes them very easy to follow, and to test.
Stateful Component Both props and state. These are used when your component must retain some state. This is a good place for client-server communication (XHR, web sockets, etc.), processing data and responding to user events. These sort of logistics should be encapsulated in a moderate number of Stateful Components, while all visualization and formatting logic should move downstream into many Stateless Components.
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
Remove your file or your path using before execute the command do a bk of your changes
sudo rm -r /path/to/dir/
after :
svn up and commit or delete
For Laravel 2020. Ok, an example:
<form class="modal-content animate" action="{{ url('login_kun') }}" method="post">
@csrf // !!! attention - this string is a must
....
</form>
And then in web.php:
Route::post("/login_kun", "LoginController@login");
And one more in new created LoginController:
public function login(Request $request){
dd($request->all());
}
and you are done my friend.
It is said that objects state is referred with respect to the fields in it and it would become ambiguous if too many classes were inherited. Here is the link
http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
I am using folllowing script to retreive all defaults (sp_binddefaults) and all default constraint with following scripts:
SELECT
t.name AS TableName, c.name AS ColumnName, SC.COLUMN_DEFAULT AS DefaultValue, dc.name AS DefaultConstraintName
FROM
sys.all_columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.schemas s ON t.schema_id = s.schema_id
LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
LEFT JOIN INFORMATION_SCHEMA.COLUMNS SC ON (SC.TABLE_NAME = t.name AND SC.COLUMN_NAME = c.name)
WHERE
SC.COLUMN_DEFAULT IS NOT NULL
--WHERE t.name = '' and c.name = ''
border-color: transparent; border: 1px solid red;
I realized that I wasn't passing $objPage into page_properties(). It works fine now.
Python Unittest, Bat process Error Codes:
if __name__ == "__main__":
test_suite = unittest.TestSuite()
test_suite.addTest(RunTestCases("test_aggregationCount_001"))
runner = unittest.TextTestRunner()
result = runner.run(test_suite)
# result = unittest.TextTestRunner().run(test_suite)
if result.wasSuccessful():
print("############### Test Successful! ###############")
sys.exit(1)
else:
print("############### Test Failed! ###############")
sys.exit()
Bat codes:
@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
echo Error found. Waiting here...
pause
) || (
echo This time of test is ok.
)
)
With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for @property
and source='field'
raise an error.
class Foo(models.Model):
. . .
def foo(self):
return 'stuff'
. . .
class FooSerializer(ModelSerializer):
foo = serializers.ReadOnlyField()
class Meta:
model = Foo
fields = ('foo',)
You can also try renaming the document you don't want people to be able to access. You could rename it to 47d8498d3w.php for instance. Just make something up that people most likely won't type as a http-request. If you include the file with SSI or PHP, the user won't be able to see the name of the document anyway.
I am heavily using fast_cgi_finish_request()
In combination with a closure and register_shutdown_function()
$message ='job executed';
$backgroundJob = function() use ($message) {
//do some work here
echo $message;
}
Then register this closure to be executed before shutdown.
register_shutdown_function($backgroundJob);
Finally when the response was sent to the client you can close the connection to the client and continue working with the PHP process:
fast_cgi_finish_request();
The closure will be executed after fast_cgi_finish_request.
The $message will not be visible at any time. And you can register as much closures as you want, but take care about script execution time. This will only work if PHP is running as a Fast CGI module (was that right?!)
Casting or converting to VARCHAR(MAX)
or anything else did not work for me using large integers (in float fields) such as 167382981, which always came out '1.67383e+008'.
What did work was STR()
.
on Debian 10
I start mysql from ./opt/lampp/xampp start
I do strace ./opt/lampp/sbin/mysqld
and see that my.cnf is there:
stat("/opt/lampp/etc/my.cnf", {st_mode=S_IFREG|0644, st_size=5050, ...}) = 0
openat(AT_FDCWD, "/opt/lampp/etc/my.cnf", O_RDONLY|O_CLOEXEC) = 3
hence, I add sql_mode config to /opt/lampp/etc/my.cnf
instead of /etc/mysql/my.cnf
Apple changed the canOpenURL method on iOS 9. Apps which are checking for URL Schemes on iOS 9 and iOS 10 have to declare these Schemes as it is submitted to Apple.
If you installed Node.js using Homebrew, npm binaries can be found in /usr/local/share/npm/bin
. You should make sure this directory is in your PATH environment variable. So, in your ~/.zshrc
file add export PATH=/usr/local/share/npm/bin:$PATH
.
Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:
"test".match( /t(e)st/ );
alert( RegExp.$1 );
will alert "e"
But also here it's not "magic" but simply part of the properties name
long startTime = System.currentTimeMillis();
// code goes here
long finishTime = System.currentTimeMillis();
long elapsedTime = finishTime - startTime; // elapsed time in milliseconds
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
Don't use array_values
on your $row
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
array_push($res_arr_values, $row);
}
Also, the preferred way to add a value to an array is writing $array[] = $value;
, not using array_push
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC)
but to use mysql_fetch_assoc($result)
directly.
$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
{
$res_arr_values[] = $row;
}
You have to run a web server (e.g. Apache) and browse to your localhost, mostly likely on port 80.
What you really ought to do is install an all-in-one package like XAMPP, it bundles Apache, MySQL PHP, and Perl (if you were so inclined) as well as a few other tools that work with Apache and MySQL - plus it's cross platform (that's what the 'X' in 'XAMPP' stands for).
Once you install XAMPP (and there is an installer, so it shouldn't be hard) open up the control panel for XAMPP and then click the "Start" button next to Apache - note that on applications that require a database, you'll also need to start MySQL (and you'll be able to interface with it through phpMyAdmin). Once you've started Apache, you can browse to http://localhost.
Again, regardless of whether or not you choose XAMPP (which I would recommend), you should just have to start Apache.
If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.
You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start()
without even using a local variable:
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:
Thread t = new Thread() {
public void run() {
System.out.println("blah");
}
};
t.start();
You can use the below code to submit the form using JavaScript:
document.getElementById('FormID').submit();
https://stackoverflow.com/a/48531811/9609776
This is ok but do not split the updateResources into different versions, just use the solution below (kotlin). Key is in "Configuration(context.resources.configuration)" it makes deep copy.
100% solution for API 21+. I have not tested for lower ones, but should work.
private fun updateResources(context: Context, language: String): Context {
return Configuration(context.resources.configuration).run {
Locale.setDefault(Locale(language).also { locale ->
setLocale(locale)
}).let {
context.createConfigurationContext(this)
}
}
}
The object returned by range()
is actually a range
object. This object implements the iterator interface so you can iterate over its values sequentially, just like a generator, list, or tuple.
But it also implements the __contains__
interface which is actually what gets called when an object appears on the right hand side of the in
operator. The __contains__()
method returns a bool
of whether or not the item on the left-hand-side of the in
is in the object. Since range
objects know their bounds and stride, this is very easy to implement in O(1).
++i
is slightly more efficient due to its semantics:
++i; // Fetch i, increment it, and return it
i++; // Fetch i, copy it, increment i, return copy
For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).
As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):
std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
vec.push_back(i);
}
That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.
You should note that this is not necessarily the best design pattern. From the looks of it, you are essentially using your App Delegate to store what amounts to a global variable.
Matt Gallagher covered the issue of globals well in his Cocoa with Love article at http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html. In all likelyhood, your ClassA should be a singleton rather than a global in the AppDelegate, although its possible you intent ClassA to be more general purpose and not simply a singleton. In that case, you'd probably be better off with either a class method to return a pre-configured instance of Class A, something like:
+ (ClassA*) applicationClassA
{
static ClassA* appClassA = nil;
if ( !appClassA ) {
appClassA = [[ClassA alloc] init];
appClassA.downloadURL = @"http://www.abc.com/";
}
return appClassA;
}
Or alternatively (since that would add application specific stuff to what is possibly a general purpose class), create a new class whose sole purpose is to contain that class method.
The point is that application globals do not need to be part of the AppDelegate. Just because the AppDelegate is a known singleton, does not mean every other app global should be mixed in with it even if they have nothing conceptually to do with handling the NSApplication delegate methods.
you can use attribute data-html="true"
:
<a href="#" id="example" rel="popover"
data-content="<div>This <b>is</b> your div content</div>"
data-html="true" data-original-title="A Title">popover</a>
1.
To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE
is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...
SQL> select sysdate from dual;
SYSDATE
---------
26-SEP-12
Which means my session's setting is DD-Mon-YY
SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;
TO_CHAR(SY
----------
09/26/2012
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;
TO_DATE(T
---------
26-SEP-12
2.
More importantly, Why are you converting to char and then to date, instead of directly comparing
MaxDate = REP_DATE
If you want to ignore the time component in MaxDate before comparision, you should use..
trunc(MaxDate ) = rep_date
instead.
==Update : based on updated question.
Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00
I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.
If it is a running system and you have no control over repdate, you could try this.
trunc(rep_date) = trunc(maxdate) and
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')
Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.
json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}
.
But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.
Create a method similar to String.format()
of Java
StringJoin=(s, r=[])=>{
r.map((v,i)=>{
s = s.replace('%'+(i+1),v)
})
return s
}
use
console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
Your string may contain non Latin1 characters, which leads to undefined data. It depends of what you mean by "it deosn't seem to work".
The answer is to place the root dir to the location directives:
root /srv/www/ducklington.org/public_html;
Per the official guide, use of
pylab
is no longer recommended.matplotlib.pyplot
should be used directly instead.
Globally setting font sizes via rcParams
should be done with
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16
# or
params = {'axes.labelsize': 16,
'axes.titlesize': 16}
plt.rcParams.update(params)
# or
import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)
# or
axes = {'labelsize': 16,
'titlesize': 16}
mpl.rc('axes', **axes)
The defaults can be restored using
plt.rcParams.update(plt.rcParamsDefault)
You can also do this by creating a style sheet in the stylelib
directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()
). The style sheet format is
axes.labelsize: 16
axes.titlesize: 16
If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle
then you can use it via
plt.style.use('mystyle')
# or, for a single section
with plt.style.context('mystyle'):
# ...
You can also create (or modify) a matplotlibrc file which shares the format
axes.labelsize = 16
axes.titlesize = 16
Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.
A complete list of the rcParams
keys can be retrieved via plt.rcParams.keys()
, but for adjusting font sizes you have (italics quoted from here)
axes.labelsize
- Fontsize of the x and y labelsaxes.titlesize
- Fontsize of the axes titlefigure.titlesize
- Size of the figure title (Figure.suptitle()
)xtick.labelsize
- Fontsize of the tick labelsytick.labelsize
- Fontsize of the tick labelslegend.fontsize
- Fontsize for legends (plt.legend()
, fig.legend()
)legend.title_fontsize
- Fontsize for legend titles, None
sets to the same as the default axes. See this answer for usage example.all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'}
or a float
in pt
. The string sizes are defined relative to the default font size which is specified by
font.size
- the default font size for text, given in pts. 10 pt is the standard valueAdditionally, the weight can be specified (though only for the default it appears) by
font.weight
- The default weight of the font used by text.Text
. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900}
or 'normal'
(400), 'bold'
(700), 'lighter'
, and 'bolder'
(relative with respect to current weight).First of all, %d is for a int
So %1.16lld
makes no sense, because %d is an integer
That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.
What you want to use is the type double
, for calculating pi
and then using %f
or %1.16f
.
If wanting to extract text from a table, I've found tabula to be easily implemented, accurate, and fast:
to get a pandas dataframe:
import tabula
df = tabula.read_pdf('your.pdf')
df
By default, it ignores page content outside of the table. So far, I've only tested on a single-page, single-table file, but there are kwargs to accommodate multiple pages and/or multiple tables.
install via:
pip install tabula-py
# or
conda install -c conda-forge tabula-py
In terms of straight-up text extraction see: https://stackoverflow.com/a/63190886/9249533
I like the concept of container_of
used for example in lists. Basically, you do not need to specify next
and last
fields for each structure which will be in the list. Instead, you append the list structure header to actual linked items.
Have a look on include/linux/list.h
for real-life examples.
Gradle version;
configurations.all {
exclude module: 'slf4j-log4j12'
}
On Fedora 26 and probably many other versions, you may encounter an error after moving your base folder location as described above. This is particularly true if you are moving it to somewhere under /home. This is because SeLinux kicks in and prevents the docker container from running many of its programs from under this location.
The short solution is to remove the --enable-selinux option when you add the -g parameter.
You can use whereIn
which accepts an array as second paramter.
DB:table('table')
->whereIn('column', [value, value, value])
->get()
You can chain where multiple times.
DB:table('table')->where('column', 'operator', 'value')
->where('column', 'operator', 'value')
->where('column', 'operator', 'value')
->get();
This will use AND
operator. if you need OR
you can use orWhere
method.
For advanced where
statements
DB::table('table')
->where('column', 'operator', 'value')
->orWhere(function($query)
{
$query->where('column', 'operator', 'value')
->where('column', 'operator', 'value');
})
->get();
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.
A simpler approach, which I have been using (assuming you want to move 4 commits):
git format-patch HEAD~4
(Look in the directory from which you executed the last command for the 4 .patch
files)
git reset HEAD~4 --hard
git checkout -b tmp/my-new-branch
Then:
git apply /path/to/patch.patch
In whatever order you wanted.
Edit php.ini
Find this line:
max_execution_time
Change its value to 300:
max_execution_time = 300
300 means 5 minutes of execution time for the http request.
It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.
If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add _CRT_SECURE_NO_WARNINGS
symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".
Also you can define it just before you include a header file which generates this warning. You should add something like this
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy_s instead of strcpy.
avd manager has an option "ideal size of system partition", try setting that to 1024MB, or use the commandline launch option that does the same.
fyi, I only encountered this problem with the 4.0 emulator image.
There are several helpful bits of code for this.
Place your cursor in a merged cell and ask these questions in the Immidiate Window:
Is the activecell a merged cell?
? Activecell.Mergecells
True
How many cells are merged?
? Activecell.MergeArea.Cells.Count
2
How many columns are merged?
? Activecell.MergeArea.Columns.Count
2
How many rows are merged?
? Activecell.MergeArea.Rows.Count
1
What's the merged range address?
? activecell.MergeArea.Address
$F$2:$F$3
the format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO. - How to Add a Favicon to your Site - QA @ W3C
There is an extension for that, but I have no usage experience yet:
http://ipython.scipy.org/ipython/ipython/attachment/ticket/154/ipy_autoreload.py
No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.
I am using ubuntu 14.04.
The correct way in my system should be date +%s
.
The output of date +%T
is like 12:25:25
.
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
See if /?|find /V ""
for details.
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token) {
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld) {
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
}
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
}
Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
In your case, run the SQL query using only the username:
$sql_script = 'SELECT * FROM USERS WHERE username=?';
And do the password validation in PHP using a code that is similar to the example above.
The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.
I tried adding dynamically created ListItem and assigning the selected value.
foreach(var item in yourListFromDB)
{
ListItem listItem = new ListItem();
listItem.Text = item.name;
listItem.Value = Convert.ToString(item.value);
listItem.Selected=item.isSelected;
checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();
avoid using binding the DataSource as it will not bind the checked/unchecked from DB.
I think the easiest way to make it done is :
std::vector<std::vector<int>>v(10,std::vector<int>(11,100));
10 is the size of the outer or global vector, which is the main one, and 11 is the size of inner vector of type int, and initial values are initialized to 100! That's my first help on stack, i think it helps someone.
You Can Use MYSQL Administrator Tool its free http://dev.mysql.com/downloads/gui-tools/5.0.html
you'll find many options to export ur MYSQL DataBase
The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:
function find_closest_marker( lat1, lon1 ) {
var pi = Math.PI;
var R = 6371; //equatorial radius
var distances = [];
var closest = -1;
for( i=0;i<markers.length; i++ ) {
var lat2 = markers[i].position.lat();
var lon2 = markers[i].position.lng();
var chLat = lat2-lat1;
var chLon = lon2-lon1;
var dLat = chLat*(pi/180);
var dLon = chLon*(pi/180);
var rLat1 = lat1*(pi/180);
var rLat2 = lat2*(pi/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
// (debug) The closest marker is:
console.log(markers[closest]);
}
No. But you should really use console.log()
instead of alert()
for debugging.
In Chrome it even has the advantage of being able to print out entire objects (not just toString()
).
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>