None of the following answers are right. All these methods just seem to be alike, but in practice do absolutely different things. It is hard to give short comments. Better to give a link to full documentation about these methods: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html
you can use the weight value specified in the Google Fonts.
body{
font-family: 'Heebo', sans-serif;
font-weight: 100;
}
Use the WebClient
class in System.Net
:
var json = new WebClient().DownloadString("url");
Keep in mind that WebClient
is IDisposable
, so you would probably add a using
statement to this in production code. This would look like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("url");
}
If you are not targeting 2.x versions you can set your minimum sdk version of 4.x and then create project. Appcompat V7 lib wont be created.
The result is same for all options. Redirect.
<meta>
in HTML:
window.location
in JS:
if (1 === 1) { window.location.href = 'http://example.com'; }
.header('Location:')
in PHP:
header()
must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingToParent {
//your code backView
}
}
The Java language specification says you can have return with no expression if your method returns void.
People will learn your interface from code completion in their IDE or in Javadoc, not from reading the source. So there's no point in putting "public" in the source - nobody's reading the source.
You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)
DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
SET @StartDate = NULL
SET @EndDate = NULL
IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL)
BEGIN
print 'yoyoyo'
END
IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2)
BEGIN
print 'Oh hey there'
END
adding to scotty's answer:
Option 1: Either include this in your JS file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
Option 2: or just use the URL to download 'angular-route.min.js' to your local.
and then (whatever option you choose) add this 'ngRoute' as dependency.
explained:
var app = angular.module('myapp', ['ngRoute']);
Cheers!!!
This relatively recent article provides a simple example with a limited Google Maps set of colored icons.
If you added a library to the project structure (rather than via maven, that would be different), be sure it is included as a dependency for the relevant module.
Project Structure -> Modules -> Dependencies
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false
.
SSH doesn't use the :
syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config
file and add:
Host git.host.de Port 4019
Then specify just git.host.de
without a port number.
You can clone your state object, loop through each one, and set it to undefined
. This method is not as good as the accepted answer, though.
const clonedState = this.state;
const keys = Object.keys(clonedState);
keys.forEach(key => (clonedState[key] = undefined));
this.setState(clonedState);
The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.
LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.
LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.
Key features of LXD are:
There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.
However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.
The OpenStack nclxd plugin a list of features supported include:
stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support
By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.
You can also force flush the buffer to a file programmatically with the flush()
method.
with open('out.log', 'w+') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
# some other work
f.write('done\n')
f.flush()
I have found this useful when tailing an output file with tail -f
.
Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id
.
For example, in a dogs
collection, a document would have manual references to external documents named like this:
{
name: 'fido',
owner_id: '5358e4249611f4a65e3068ab',
race_id: '5358ee549611f4a65e3068ac',
colour: 'yellow'
...
}
This follows the Mongo convention of naming _id
the identifier for every document.
function isEmpty(variable) {_x000D_
const type = typeof variable_x000D_
if (variable === null) return true_x000D_
if (type === 'undefined') return true_x000D_
if (type === 'boolean') return false_x000D_
if (type === 'string') return !variable_x000D_
if (type === 'number') return false_x000D_
if (Array.isArray(variable)) return !variable.length_x000D_
if (type === 'object') return !Object.keys(variable).length_x000D_
return !variable_x000D_
}
_x000D_
This is a working option.
public static String showDuration(LocalTime otherTime){
DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime now = LocalTime.now();
System.out.println("now: " + now);
System.out.println("otherTime: " + otherTime);
System.out.println("otherTime: " + otherTime.format(df));
Duration span = Duration.between(otherTime, now);
LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());
String output = fTime.format(df);
System.out.println(output);
return output;
}
Call the method with
System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));
Produces something like:
otherTime: 09:30
otherTime: 09:30:00
11:31:27.463
11:31:27.463
I think this is problem of Android studio 2 Update or Problem to solve please Update also Android sdk version also then work properly.
Related to the question, I ended up here when searching for:
How do I make a local repo aware of a changed default branch on GitHub
For completeness, adding the answer:
git remote set-head origin -a
The provided solutions for the Scala language (a little shorter):
def getMd5(content: Array[Byte]) =
try {
val md = MessageDigest.getInstance("MD5")
val bytes = md.digest(content)
bytes.map(b => Integer.toHexString((b + 0x100) % 0x100)).mkString
} catch {
case ex: Throwable => null
}
Safer is to use lift
so you can extract the value if it exists and fail gracefully if it does not.
data.lift(2)
This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None
Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.
Explanation:
This works because List's apply
(which sugars to just parentheses, e.g. l(index)
) is like a partial function that is defined wherever the list has an element. The List.lift
method turns the partial apply
function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.
I have a similar problem, and though I like portability, I only need gcc support. In gcc, execinfo.h and the backtrace calls are available. To demangle the function names, Mr. Bingmann has a nice piece of code. To dump a backtrace on an exception, I create an exception that prints the backtrace in the constructor. If I were expecting this to work with an exception thrown in a library, it might require rebuilding/linking so that the backtracing exception is used.
/******************************************
#Makefile with flags for printing backtrace with function names
# compile with symbols for backtrace
CXXFLAGS=-g
# add symbols to dynamic symbol table for backtrace
LDFLAGS=-rdynamic
turducken: turducken.cc
******************************************/
#include <cstdio>
#include <stdexcept>
#include <execinfo.h>
#include "stacktrace.h" /* https://panthema.net/2008/0901-stacktrace-demangled/ */
// simple exception that prints backtrace when constructed
class btoverflow_error: public std::overflow_error
{
public:
btoverflow_error( const std::string& arg ) :
std::overflow_error( arg )
{
print_stacktrace();
};
};
void chicken(void)
{
throw btoverflow_error( "too big" );
}
void duck(void)
{
chicken();
}
void turkey(void)
{
duck();
}
int main( int argc, char *argv[])
{
try
{
turkey();
}
catch( btoverflow_error e)
{
printf( "caught exception: %s\n", e.what() );
}
}
Compiling and running this with gcc 4.8.4 yields a backtrace with nicely unmangled C++ function names:
stack trace:
./turducken : btoverflow_error::btoverflow_error(std::string const&)+0x43
./turducken : chicken()+0x48
./turducken : duck()+0x9
./turducken : turkey()+0x9
./turducken : main()+0x15
/lib/x86_64-linux-gnu/libc.so.6 : __libc_start_main()+0xf5
./turducken() [0x401629]
Using this branch will hopefully solve the problem:
gem 'twitter-bootstrap-rails',
git: 'git://github.com/seyhunak/twitter-bootstrap-rails.git',
branch: 'bootstrap3'
You can also do it this way:
byte[] getBytes (File file)
{
FileInputStream input = null;
if (file.exists()) try
{
input = new FileInputStream (file);
int len = (int) file.length();
byte[] data = new byte[len];
int count, total = 0;
while ((count = input.read (data, total, len - total)) > 0) total += count;
return data;
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (input != null) try
{
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
there is indeed an xpath contains function it should look something like:
<xsl:for-each select="item">
<xsl:variable name="hhref" select="link" />
<xsl:variable name="pdate" select="pubDate" />
<xsl:if test="not(contains(hhref,'1234'))">
<li>
<a href="{$hhref}" title="{$pdate}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:if>
Horizontal centering is easy: text-align: center;
. Vertical centering of text inside an element can be done by setting line-height
equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.
Better is to set line-height
equal to font-size
(or slightly smaller) and use padding. You'll have to adjust your height to accomodate.
Here's a CSS-only, single <div>
solution that looks pretty iPhone-like. They expand with content.
Demo: http://jsfiddle.net/ThinkingStiff/mLW47/
Output:
CSS:
.badge {
background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
background-color: red;
border: 2px solid white;
border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
box-shadow: 1px 1px 1px black;
color: white;
font: bold 15px/13px Helvetica, Verdana, Tahoma;
height: 16px;
min-width: 14px;
padding: 4px 3px 0 3px;
text-align: center;
}
HTML:
<div class="badge">1</div>
<div class="badge">2</div>
<div class="badge">3</div>
<div class="badge">44</div>
<div class="badge">55</div>
<div class="badge">666</div>
<div class="badge">777</div>
<div class="badge">8888</div>
<div class="badge">9999</div>
I was trying to write in nodejs and finally came up with this:
db.collection('collectionName').mapReduce(
function() {
for (var key in this) {
emit(key, null);
}
},
function(key, stuff) {
return null;
}, {
"out": "allFieldNames"
},
function(err, results) {
var fields = db.collection('allFieldNames').distinct('_id');
fields
.then(function(data) {
var finalData = {
"status": "success",
"fields": data
};
res.send(finalData);
delteCollection(db, 'allFieldNames');
})
.catch(function(err) {
res.send(err);
delteCollection(db, 'allFieldNames');
});
});
After reading the newly created collection "allFieldNames", delete it.
db.collection("allFieldNames").remove({}, function (err,result) {
db.close();
return;
});
Your logic is flawed... basically, you need to:
You're not doing step 2.
Here's the code you want:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
List<String> categoryList = categoryMap.get((String) entry.getKey());
if (categoryList == null)
{
categoryList = new ArrayList<String>();
LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
}
categoryList.add((String) entry.getValue());
}
Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet()
.
Push is a defined stack behaviour; if you pushed A on to stack (B,C,D) you would get (A,B,C,D).
If you used python append, the resulting dataset would look like (B,C,D,A)
Edit: Wow, holy pedantry.
I would assume that it would be clear from my example which part of the list is the top, and which part is the bottom. Assuming that most of us here read from left to right, the first element of any list is always going to be on the left.
Is Ruby pass by reference or by value?
Ruby is pass-by-value. Always. No exceptions. No ifs. No buts.
Here is a simple program which demonstrates that fact:
def foo(bar)
bar = 'reference'
end
baz = 'value'
foo(baz)
puts "Ruby is pass-by-#{baz}"
# Ruby is pass-by-value
Many distinctions have already been mentioned. Here is one more:
Running npm install
at the top of your source directory will run various scripts: prepublish
, preinstall
, install
, postinstall
. Depending on what these scripts do, a npm install
may do considerably more work than just installing dependencies.
I've just had a use case where prepublish
would call make
and the Makefile
was designed to fetch dependencies if the package.json
got updated. Calling npm install
from within the Makefile
would have lead to an infinite recursion, while calling npm update
worked just fine, installing all dependencies so that the build could proceed even if make
was called directly.
I had the same issue (on Win XP), I updated the libcurl-4.dll file in my Git bin directory to the SSL version from http://www.paehl.com/open_source/?download=curl_DLL_ONLY.7z (renaming to libcurl4.dll). All working ok now.
I agree with Aamir that the submission arrow.m from Erik Johnson on the MathWorks File Exchange is a very nice option. You can use it to illustrate the different methods of vector addition like so:
Tip-to-tail method:
o = [0 0 0]; %# Origin
a = [2 3 5]; %# Vector 1
b = [1 1 0]; %# Vector 2
c = a+b; %# Resultant
arrowStarts = [o; a; o]; %# Starting points for arrows
arrowEnds = [a; c; c]; %# Ending points for arrows
arrow(arrowStarts,arrowEnds); %# Plot arrows
Parallelogram method:
o = [0 0 0]; %# Origin
a = [2 3 5]; %# Vector 1
b = [1 1 0]; %# Vector 2
c = a+b; %# Resultant
arrowStarts = [o; o; o]; %# Starting points for arrows
arrowEnds = [a; b; c]; %# Ending points for arrows
arrow(arrowStarts,arrowEnds); %# Plot arrows
hold on;
lineX = [a(1) b(1); c(1) c(1)]; %# X data for lines
lineY = [a(2) b(2); c(2) c(2)]; %# Y data for lines
lineZ = [a(3) b(3); c(3) c(3)]; %# Z data for lines
line(lineX,lineY,lineZ,'Color','k','LineStyle',':'); %# Plot lines
For Kotlin use KTX extension function:
(It uses TextWatcher
as previous answers)
yourEditText.doOnTextChanged { text, start, count, after ->
// action which will be invoked when the text is changing
}
import core-KTX
:
implementation "androidx.core:core-ktx:1.2.0"
Use implementation androidx.appcompat:appcompat:1.0.2
in gradle and then
change import android.support.annotation.Nullable;
to import androidx.annotation.NonNull;
in the classes imports
See the docs FAQ: "How can I see the raw SQL queries Django is running?"
django.db.connection.queries
contains a list of the SQL queries:
from django.db import connection
print(connection.queries)
Querysets also have a query
attribute containing the query to be executed:
print(MyModel.objects.filter(name="my name").query)
Note that the output of the query is not valid SQL, because:
"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."
From Django bug report #17741.
Because of that, you should not send query output directly to a database.
A much easier way to do this is using PowerShell, like so:
Get-Website yoursite | % { Join-Path ($_.logFile.Directory -replace '%SystemDrive%', $env:SystemDrive) "W3SVC$($_.id)" }
or simply
Get-Website yoursite | % { $_.logFile.Directory, $_.id }
if you just need the info for yourself and don't mind parsing the result in your brain :).
For bonus points, append | ii
to the first command to open in Explorer, or | gci
to list the contents of the folder.
You could use the TIMEDIFF()
and the TIME_TO_SEC()
functions as follows:
SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
You could also use the UNIX_TIMESTAMP()
function as @Amber suggested in an other answer:
SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') -
UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
If you are using the TIMESTAMP
data type, I guess that the UNIX_TIMESTAMP()
solution would be slightly faster, since TIMESTAMP
values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:
When
UNIX_TIMESTAMP()
is used on aTIMESTAMP
column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.Keep in mind that
TIMEDIFF()
return data type ofTIME
.TIME
values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)
@Future-searchers: you can use aspell to do the dictionary checks, it has bindings in ruby and python. It would make your job much simpler.
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
You can add setenv.sh in the the bin directory with:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
and it will dynamically change when you update your packages.
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
You have to tell your SQLCommand objects to use the transaction:
cmd1.Transaction = transaction;
or in the constructor:
SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);
Make sure to have the connectionsql object open, too.
But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.
I say "star-args" and Python people seem to know what i mean.
**
is trickier - I think just "qargs" since it is usually used as **kw
or **kwargs
In 2015 the only way I found to make it work for both Chrome and Firefox is to put all possible extensions you want to support, including variants (including the dot in front !):
accept=".jpeg, .jpg, .jpe, .jfif, .jif"
Problem with Firefox: Using the image/jpeg
mime type Firefox will only show .jpg
files, very strange as if the common .jpeg
was not ok...
Whatever you do, be sure to try with files having many different extensions.
Maybe it even depends on the OS ... I suppose accept
is case insensitive, but maybe not in every browser.
Here is the MDN docs about accept:
accept If the value of the type attribute is file, then this attribute will indicate the types of files that the server accepts, otherwise it will be ignored. The value must be a comma-separated list of unique content type specifiers:
A file extension starting with the STOP character (U+002E). (e.g. .jpg, .png, .doc). A valid MIME type with no extensions. audio/* representing sound files. HTML5 video/* representing video files. HTML5 image/* representing image files. HTML5
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
This was a lot easier to do if all you want to do is find a string in an array.
$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}
Try:
tr -s ' ' <text.txt | cut -d ' ' -f4
From the tr
man page:
-s, --squeeze-repeats replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character
The following should unlock a locked working copy (tested on svn client version 1.6.11 and elipse version: Mars.2 Release (4.5.2))
step 1: (go to working copy directory) $cd working_copy_dir
step 2: (connect to svn sqlite database) $sqlite3 .svn/wc.db
step 3: (delete all records from table WC_LOCK) sqlite> delete from WC_LOCK;
step 4: (disconnect from sqlite 3 database) sqlite>ctrl + d
step 5: (from eclipse) right click on your working copy, then click Team -> Refresh/Cleanup
There seems to be another (rather hacky) way to reuse the router-outlet in one template. This answer is intendend for informational purposes only and the techniques used here should probably not be used in production.
https://stackblitz.com/edit/router-outlet-twice-with-events
The router-outlet is wrapped by an ng-template. The template is updated by listening to events of the router. On every event the template is swapped and re-swapped with an empty placeholder. Without this "swapping" the template would not be updated.
This most definetly is not a recommended approach though, since the whole swapping of two templates seems a bit hacky.
in the controller:
ngOnInit() {
this.router.events.subscribe((routerEvent: Event) => {
console.log(routerEvent);
this.myTemplateRef = this.trigger;
setTimeout(() => {
this.myTemplateRef = this.template;
}, 0);
});
}
in the template:
<div class="would-be-visible-on-mobile-only">
This would be the mobile-layout with a router-outlet (inside a template):
<br>
<ng-container *ngTemplateOutlet="myTemplateRef"></ng-container>
</div>
<hr>
<div class="would-be-visible-on-desktop-only">
This would be the desktop-layout with a router-outlet (inside a template):
<br>
<ng-container *ngTemplateOutlet="myTemplateRef"></ng-container>
</div>
<ng-template #template>
<br>
This is my counter: {{counter}}
inside the template, the router-outlet should follow
<router-outlet>
</router-outlet>
</ng-template>
<ng-template #trigger>
template to trigger changes...
</ng-template>
The common way is to load the row to update:
$post = Post::find($id);
I your case
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
But in one step (just update) you can do this:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
You want to use an Alert. Unfortunately it's not as nice as with windows forms.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);
Similar to this question here: http://forums.asp.net/t/1461308.aspx/1
in the end of your Index.js need to add this Code:
import React from 'react';_x000D_
import ReactDOM from 'react-dom';_x000D_
import { BrowserRouter } from 'react-router-dom';_x000D_
_x000D_
import './index.css';_x000D_
import App from './App';_x000D_
_x000D_
import { Provider } from 'react-redux';_x000D_
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';_x000D_
import thunk from 'redux-thunk';_x000D_
_x000D_
///its your redux ex_x000D_
import productReducer from './redux/reducer/admin/product/produt.reducer.js'_x000D_
_x000D_
const rootReducer = combineReducers({_x000D_
adminProduct: productReducer_x000D_
_x000D_
})_x000D_
const composeEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_ || compose;_x000D_
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));_x000D_
_x000D_
_x000D_
const app = (_x000D_
<Provider store={store}>_x000D_
<BrowserRouter basename='/'>_x000D_
<App />_x000D_
</BrowserRouter >_x000D_
</Provider>_x000D_
);_x000D_
ReactDOM.render(app, document.getElementById('root'));
_x000D_
To clear the value you can always reset it to $Null. For example:
Set-Mailbox -Identity "username" -CustomAttribute1 $Null
Looks like you forgot the @ in variable declaration. Also I remember having problems with SET
in MySql a long time ago.
Try
DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);
update mypermits
set person = @FOO
where person = @oldFOO;
The only solution I've found is to first create the project in Android Studio, then close the project, then import the project. I searched all over and could not find the root cause and all other solutions people posted didn't work.
It probably means you've got carriage returns (different operating systems use different ways of signaling the end of line).
Use dos2unix
to fix the files or set the fileformats in vim:
set ffs=unix,dos
I believe concurrent programming refers to multithreaded programming which is about letting your program run multiple threads, abstracted from hardware details.
Parallel programming refers to specifically designing your program algorithms to take advantage of available parallel execution. For example, you can execute in parallel two branches of some algorithms in expectation that it will hit the result sooner (on average) than it would if you first checked the first then the second branch.
In Kotlin following works fine for me:
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv:
pip freeze | xargs pip uninstall -y
In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):
pip freeze | grep -v "^-e" | xargs pip uninstall -y
I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)
class CheckMailer:
def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
self.f = FileWriter(filename)
self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
self.inbox = self.outlook.Folders(folderindex)
def check(self):
#===============================================================================
# for i in xrange(1,100): #Uncomment this section if index 3 does not work for you
# try:
# self.inbox = self.outlook.Folders(i) # "6" refers to the index of inbox for Default User Mailbox
# print "%i %s" % (i,self.inbox) # "3" refers to the index of inbox for Another user's mailbox
# except:
# print "%i does not work"%i
#===============================================================================
self.f.pl(time.strftime("%H:%M:%S"))
tot = 0
messages = self.inbox.Items
message = messages.GetFirst()
while message:
self.f.pl (message.Subject)
message = messages.GetNext()
tot += 1
self.f.pl("Total Messages found: %i" % tot)
self.f.pl("-" * 80)
self.f.flush()
if __name__ == "__main__":
mail = CheckMailer()
for i in xrange(320): # this is 10.6 hours approximately
mail.check()
time.sleep(120.00)
For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.
class FileWriter(object):
'''
convenient file wrapper for writing to files
'''
def __init__(self, filename):
'''
Constructor
'''
self.file = open(filename, "w")
def pl(self, a_string):
str_uni = a_string.encode('utf-8')
self.file.write(str_uni)
self.file.write("\n")
def flush(self):
self.file.flush()
You might want to look into Eclim, an Eclipse server that allows you to use Eclipse functionality from within your favorite text editor. For python-related functionality, it uses Rope, PyFlakes, and PyLint under the hood.
For example we have some entity Group.
For this entity we create the repository GroupRepository.
public interface GroupRepository extends JpaRepository<Group, Long> {
}
Then we need to create a service layer with which we will use this repository.
public interface Service<T, ID> {
T save(T entity);
void deleteById(ID id);
List<T> findAll();
T getOne(ID id);
T editEntity(T entity);
Optional<T> findById(ID id);
}
public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {
private final R repository;
protected AbstractService(R repository) {
this.repository = repository;
}
@Override
public T save(T entity) {
return repository.save(entity);
}
@Override
public void deleteById(ID id) {
repository.deleteById(id);
}
@Override
public List<T> findAll() {
return repository.findAll();
}
@Override
public T getOne(ID id) {
return repository.getOne(id);
}
@Override
public Optional<T> findById(ID id) {
return repository.findById(id);
}
@Override
public T editEntity(T entity) {
return repository.saveAndFlush(entity);
}
}
@org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {
private final GroupRepository groupRepository;
@Autowired
protected GroupServiceImpl(GroupRepository repository) {
super(repository);
this.groupRepository = repository;
}
}
And in the controller we use this service.
@RestController
@RequestMapping("/api")
class GroupController {
private final Logger log = LoggerFactory.getLogger(GroupController.class);
private final GroupServiceImpl groupService;
@Autowired
public GroupController(GroupServiceImpl groupService) {
this.groupService = groupService;
}
@GetMapping("/groups")
Collection<Group> groups() {
return groupService.findAll();
}
@GetMapping("/group/{id}")
ResponseEntity<?> getGroup(@PathVariable Long id) {
Optional<Group> group = groupService.findById(id);
return group.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping("/group")
ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {
log.info("Request to create group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.created(new URI("/api/group/" + result.getId()))
.body(result);
}
@PutMapping("/group")
ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {
log.info("Request to update group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.ok().body(result);
}
@DeleteMapping("/group/{id}")
public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
log.info("Request to delete group: {}", id);
groupService.deleteById(id);
return ResponseEntity.ok().build();
}
}
In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.
According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.
You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
Before proceeding:
Install a proper mergetool. On Linux, I strongly suggest you to use meld:
sudo apt-get install meld
Configure your mergetool:
git config --global merge.tool meld
Then, iterate in the following way:
git cherry-pick ....
git mergetool
git cherry-pick --continue
Follow the below steps, and you shall get the needed answer
1- For both fragments, create a new abstract parent one.
2- Add a custom abstract method that should be implemented by both of them.
3- Call it from the current instance before replacing with the second one.
-> Testing the app with maximum number of user and input is defined as load testing. While testing the app with more than maximum number of user and input is defined as stress testing.
->In Load testing we measure the system performance based on a volume of users. While in Stress testing we measure the breakpoint of a system.
->Load Testing is testing the application for a given load requirements which may include any of the following criteria:
.Total number of users.
.Response Time
.Through Put
Some parameters to check State of servers/application.
-> While stress testing is testing the application for unexpected load. It includes
.Vusers
.Think-Time
Example:
If an app is build for 500 users, then for load testing we check up to 500 users and for stress testing we check greater than 500.
How about running the following from command line,
Devenv.exe /ResetSettings
You could also save those settings in to a file, like so,
Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"
The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.
This worked for me:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
var text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Use Costura.Fody.
You just have to install the nuget and then do a build. The final executable will be standalone.
Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.
Android code - Main.java
package test12.tt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test12Activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt1 = (TextView) findViewById(R.id.sm);
new Thread(new Runnable() {
public void run(){
txt1.setText("Thread!!");
}
}).start();
}
}
Android application xml - main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id = "@+id/sm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:
File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
<?php
$terms = get_the_terms($product->ID, 'product_cat');
foreach ($terms as $term) {
$product_cat = $term->name;
echo $product_cat;
break;
}
?>
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source
One word answer: MONEY :D
1 GB to store in US-East-1: (Updated at 2016.dec.20)
Further storage options, which may be used for temporary storing data while/before processing it:
The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services.
There are a lot more differences between these services:
EFS is:
EBS is:
S3 is:
Glacier is:
As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.)
Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction
IF you want Department and highest salary, use
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
if you want more columns in employee and department, use
select Department.Name , emp.Name, emp.Salary from Employee emp
inner join (select DeptID, max(salary) [salary] from employee group by DeptID) b
on emp.DeptID = b.DeptID and b.salary = emp.Salary
inner join Department on emp.DeptID = Department.id
order by Department.Name
if use salary in (select max(salary...)) like this, one person have same salary in another department then it will fail.
In Android Studio, open the Device Manager: Tools -> Android -> Android Device Monitor
In Eclipse open the Device Manager:
In the device manager you can add files to the SD Card here:
Hi All I also had this problem. I use C# with Xamarin
Just a slight note that I hope someone else as well.
I have tried multiple of the methods mentioned here.
edittext1.SetRawInputType(Android.Text.InputTypes.ClassNumber | Android.Text.InputTypes.NumberFlagDecimal);
was the closest but still did not work. As Ralf mentioned, you could use
edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
However in my C# I did not have this. instead you do it as follow:
edittext1.InputType = Android.Text.InputTypes.ClassNumber | Android.Text.InputTypes.NumberFlagDecimal;
Please note that the ORDER of these is important. If you put Decimal first, it will still allow you to type any Characters, where If Numer is first it is only numeric, but allows a decimal seperator!
If anyone is specifically getting Unexpected token <
, and your package.json is fine, check your npm-shrinkwrap.json file! I had unresolved merge issues in mine, and fixing that resolved everything.
Actually, the default directory where the mongod instance stores its data is
/data/db
on Linux and OS X,
\data\db
on Windows
To check the same, you can look for dbPath settings in mongodb configuration file.
/etc/mongod.conf
, if you have used package manager to install MongoDB.
Run the following command to check the specified directory:
grep dbpath /etc/mongodb.conf
<install directory>/bin/mongod.cfg
. Open mongod.cfg file and check for dbPath option./usr/local/etc/mongod.conf
when installing from MongoDB’s official Homebrew tap.The default mongod.conf configuration file included with package manager installations uses the following platform-specific default values for storage.dbPath
:
+--------------------------+-----------------+------------------------+
| Platform | Package Manager | Default storage.dbPath |
+--------------------------+-----------------+------------------------+
| RHEL / CentOS and Amazon | yum | /var/lib/mongo |
| SUSE | zypper | /var/lib/mongo |
| Ubuntu and Debian | apt | /var/lib/mongodb |
| macOS | brew | /usr/local/var/mongodb |
+--------------------------+-----------------+------------------------+
The storage.dbPath
setting in the configuration file is available only for mongod
.
The Linux package init scripts do not expect storage.dbPath
to change from the defaults. If you use the Linux packages and change storage.dbPath
, you will have to use your own init scripts and disable the built-in scripts.
If you do grouping by virtue of including GROUP BY
clause, any expression in SELECT
, which is not group function (or aggregate function or aggregated column) such as COUNT
, AVG
, MIN
, MAX
, SUM
and so on (List of Aggregate functions) should be present in GROUP BY
clause.
Example (correct way) (here employee_id
is not group function (non-aggregated column), so it must appear in GROUP BY
. By contrast, sum(salary) is a group function (aggregated column), so it is not required to appear in the GROUP BY
clause.
SELECT employee_id, sum(salary)
FROM employees
GROUP BY employee_id;
Example (wrong way) (here employee_id
is not group function and it does not appear in GROUP BY
clause, which will lead to the ORA-00979 Error .
SELECT employee_id, sum(salary)
FROM employees;
To correct you need to do one of the following :
SELECT
clause in the
GROUP BY
clauseSELECT
clause.CREATE TABLE #t
Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.
CREATE TABLE ##t
Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.
Use import scala.collection.mutable.MutableList or similar if you really need mutation.
import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)
Shorter variation of Dirk's answer:
# Create a Color Palette Dictionary
> color <- c('navy.blue', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')
> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
>
> color_palette
$navy.blue
[1] "#336A91"
$gold
[1] "#F3C117"
$dark.gray
[1] "#7F7F7F"
Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?
Its simpler than you think.
According to Microsoft:
The lock
keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
The lock
keyword calls Enter
at the start of the block and Exit
at the end of the block. lock
keyword actually handles Monitor
class at back end.
For example:
private static readonly Object obj = new Object();
lock (obj)
{
// critical section
}
In the above code, first the thread enters a critical section, and then it will lock obj
. When another thread tries to enter, it will also try to lock obj
, which is already locked by the first thread. Second thread will have to wait for the first thread to release obj
. When the first thread leaves, then another thread will lock obj
and will enter the critical section.
As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique()
might be what you are looking for.
Input:
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Result:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
Simply create it as new byte[100]
it will be initialized with 0 by default
string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"
With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.
$.getJSON
is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.
Alternatively you could use jQuery's $.when/.then(), similar to this:
var input = "netuetamundis"; var sID; $(document).ready(function () { $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () { obj = name; sID = obj.id; console.log(sID); })).then(function () { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) { console.log(stats); }); }); });
This would be more open for future modification and separates out the responsibility for the first call to know about the second call.
The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.
When using setAttribute
and getRequestDispatcher
on doGet
, make sure that you are accessing your pages with the urlPatterns ("/login" for example) defined for your servlet. If you do it with "/login.jsp" your doGet
won't get called so none of your attributes will be available.
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
Another option would be:
SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0
You can disable optimizations if you pass -O0 with the gcc command-line.
E.g. to turn a .C file into a .S file call:
gcc -O0 -S test.c
Beyond select(-one_of(drop.cols))
there are a couple other options for dropping columns using select()
that do not involve defining all the specific column names (using the dplyr starwars sample data for some more variety in column names):
starwars %>%
select(-(name:mass)) %>% # the range of columns from 'name' to 'mass'
select(-contains('color')) %>% # any column name that contains 'color'
select(-starts_with('bi')) %>% # any column name that starts with 'bi'
select(-ends_with('er')) %>% # any column name that ends with 'er'
select(-matches('^f.+s$')) %>% # any column name matching the regex pattern
select_if(~!is.list(.)) %>% # not by column name but by data type
head(2)
# A tibble: 2 x 2
homeworld species
<chr> <chr>
1 Tatooine Human
2 Tatooine Droid
background:url("img/content-bg.jpg") no-repeat;
background-position:center;
background-size:cover;
or
background-size:100%;
def random_items(array)
array.sample(1 + rand(array.count))
end
my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))
=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]
If you're an Android developer you can use android.util.Base64
class for this purpose.
There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.
Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data
is declared as
typedef struct my_data {
int a;
const char *name;
double x;
} my_data;
then your
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
is simply a more compact form of
my_data data[4]={
{ 0, "Peter", 0 },
{ 0, "James", 0 },
{ 0, "John", 0 },
{ 0, "Mike", 0 }
};
I hope you know what the latter does.
increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !
I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.
A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?
In your php.ini configuration file simply uncomment the extension:
;extension=php_pdo_mysql.dll
(You can find your php.ini file in the php folder where your stack server is installed.)
If you're on Windows make it: extension=php_pdo_mysql.dll
If you're on Linux make it: extension=pdo_mysql.so
And do a quick server restart.
If this isn't working for you, you may need to install pdo_mysql extension into your php library.
I solved this problem by using: chown -R etc/asterisk chown -R var/lib/asterisk
this is bacause, as said here, I wasn't running as administrator. So, I made my user as owner of the Asterisk directories.
When using dag
instead of thin
, the syntax below pointing to service name worked for me. The jdbc:thin
solutions above did not work.
jdbc:dag:oracle://HOSTNAME:1521;ServiceName=SERVICE_NAME
You have to run 'bibtex':
latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi
hashCode()
is used for bucketing in Hash
implementations like HashMap
, HashTable
, HashSet
, etc.
The value received from hashCode()
is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.
When you do contains()
it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals()
method to evaluate if the objects are equal, and then decide if contains()
is true or false, or decide if element could be added in the set or not.
The for
attribute of the <label>
tag should be equal to the id
attribute of the related element to bind them together.
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.
Use http://www.translate.google.com/translate_tts?tl=en&q=Hello%20World
note the www.translate.google.com
var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
var productId = match[1];
var shopId = match[2];
} else {
// no match
}
I finally understood what was going on.
When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.
When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.
My test now works just fine.
For a similar application I had to wrap my data
object with JSON.stringify()
like this:
data: JSON.stringify({
'foo': 'bar',
'ca$libri': 'no$libri'
}),
The API was working with a REST client but couldn't get it to function with jquery ajax in the browser. stringify was the solution.
On performance you keep focusing on select.
Shared does not block reads.
Shared lock blocks update.
If you have hundreds of shared locks it is going to take an update a while to get an exclusive lock as it must wait for shared locks to clear.
By default a select (read) takes a shared lock.
Shared (S) locks allow concurrent transactions to read (SELECT) a resource.
A shared lock as no effect on other selects (1 or a 1000).
The difference is how the nolock versus shared lock effects update or insert operation.
No other transactions can modify the data while shared (S) locks exist on the resource.
A shared lock blocks an update!
But nolock does not block an update.
This can have huge impacts on performance of updates. It also impact inserts.
Dirty read (nolock) just sounds dirty. You are never going to get partial data. If an update is changing John to Sally you are never going to get Jolly.
I use shared locks a lot for concurrency. Data is stale as soon as it is read. A read of John that changes to Sally the next millisecond is stale data. A read of Sally that gets rolled back John the next millisecond is stale data. That is on the millisecond level. I have a dataloader that take 20 hours to run if users are taking shared locks and 4 hours to run is users are taking no lock. Shared locks in this case cause data to be 16 hours stale.
Don't use nolocks wrong. But they do have a place. If you are going to cut a check when a byte is set to 1 and then set it to 2 when the check is cut - not a time for a nolock.
Xcode 8 and Swift 3.0
Using URLSession:
let url = URL(string:"Download URL")!
let req = NSMutableURLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()
URLSession Delegate call:
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
print("downloaded \(100*writ/exp)" as AnyObject)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
}
Using Block GET/POST/PUT/DELETE:
let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error)
} else {
print(httpResponse)
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
Working fine for me.. try it 100% result guarantee
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
Clearing the contents of storage/framework/cache
did the trick for me. Nothing else worked...
AFAIK there's no built in method in the framework that will allow you to do this. You could check this post for a suggestion on determining framework version by reading windows registry values.
The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor
(hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.
To do this you will need to generate a stack in an extended HttpClient
, so its not advisable to do this in a production environment.
/**
* Extended HttpClient that generates a stack trace on error when not in a production build.
*/
@Injectable()
export class TraceHttpClient extends HttpClient {
constructor(handler: HttpHandler) {
super(handler);
}
request(...args: [any]): Observable<any> {
const stack = environment.production ? null : Error().stack;
return super.request(...args).pipe(
catchError((err) => {
// tslint:disable-next-line:no-console
if (stack) console.error('HTTP Client error stack\n', stack);
return throwError(err);
})
);
}
}
Using regular expressions, you can represent any whitespace character with the metacharacter "\s"
Using forward declarations instead of a full #include
s is possible only when you are not intending on using the type itself (in this file's scope) but a pointer or reference to it.
To use the type itself, the compiler must know its size - hence its full declaration must be seen - hence a full #include
is needed.
However, the size of a pointer or reference is known to the compiler, regardless of the size of the pointee, so a forward declaration is sufficient - it declares a type identifier name.
Interestingly, when using pointer or reference to class
or struct
types, the compiler can handle incomplete types saving you the need to forward declare the pointee types as well:
// header.h
// Look Ma! No forward declarations!
typedef class A* APtr; // class A is an incomplete type - no fwd. decl. anywhere
typedef class A& ARef;
typedef struct B* BPtr; // struct B is an incomplete type - no fwd. decl. anywhere
typedef struct B& BRef;
// Using the name without the class/struct specifier requires fwd. decl. the type itself.
class C; // fwd. decl. type
typedef C* CPtr; // no class/struct specifier
typedef C& CRef; // no class/struct specifier
struct D; // fwd. decl. type
typedef D* DPtr; // no class/struct specifier
typedef D& DRef; // no class/struct specifier
If you look at the JarFile API you'll see that it's a subclass of the ZipFile class.
The jar-specific classes mostly just add jar-specific functionality, like direct support for manifest file attributes and so on.
It's OOP "in action"; since jar files are zip files, the jar classes can use zip functionality and provide additional utility.
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
In phpMyAdmin, click the table, and then click the Import tab at the top of the page.
Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:
Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto
Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.
Now click the Go button, and it should run successfully.
Two ways come to mind:
Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that
Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.
For me the problem was my regex expression. The below did the trick to get bootstrap working:
{
test: /\.(woff|ttf|eot|svg)(\?v=[a-z0-9]\.[a-z0-9]\.[a-z0-9])?$/,
loader: 'url-loader?limit=100000'
},
You can find the Team ID via this link: https://developer.apple.com/membercenter/index.action#accountSummary
Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable
using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
That approach is fine, but if you wanted it straight into a List Object:
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
All you have to do is append a .ToList() call to the end of the Query.
Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.
Using plyr
package:
library(plyr)
count(mydf$V1)
It will return you a frequency of each value.
Many of the answers here focus on the paths the compiler will search in order to find the file. While this is what most compilers do, a conforming compiler is allowed to be preprogrammed with the effects of the standard headers, and to treat, say, #include <list>
as a switch, and it need not exist as a file at all.
This is not purely hypothetical. There is at least one compiler that work that way. Using #include <xxx>
only with standard headers is recommended.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
mn=np.min(x)
mx=np.max(x)
x1=np.linspace(mn,mx,500)
y1=gradient*x1+intercept
plt.plot(x,y,'ob')
plt.plot(x1,y1,'-r')
plt.show()
USe this ..
Use Boost asynchronous input/output threads, sleep for x milliseconds;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
$array[0] = 1;
$array[2] = 2;
$arrayTxt = implode( ',', $array);
$sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"
If you want to save to a specific filename just ignore the provided extensions in Notepad/Word/whatever. Just set the filename.ext in " " and you're done. "Save as type" will be ignored.
Try this:
<input type="number" max="???" min="???" step="0.5" id="myInput"/>
$("#myInput").attr({
"max" : 10,
"min" : 2
});
Note:This will set max and min value only to single input
C++03's categories are too restricted to capture the introduction of rvalue references correctly into expression attributes.
With the introduction of them, it was said that an unnamed rvalue reference evaluates to an rvalue, such that overload resolution would prefer rvalue reference bindings, which would make it select move constructors over copy constructors. But it was found that this causes problems all around, for example with Dynamic Types and with qualifications.
To show this, consider
int const&& f();
int main() {
int &&i = f(); // disgusting!
}
On pre-xvalue drafts, this was allowed, because in C++03, rvalues of non-class types are never cv-qualified. But it is intended that const
applies in the rvalue-reference case, because here we do refer to objects (= memory!), and dropping const from non-class rvalues is mainly for the reason that there is no object around.
The issue for dynamic types is of similar nature. In C++03, rvalues of class type have a known dynamic type - it's the static type of that expression. Because to have it another way, you need references or dereferences, which evaluate to an lvalue. That isn't true with unnamed rvalue references, yet they can show polymorphic behavior. So to solve it,
unnamed rvalue references become xvalues. They can be qualified and potentially have their dynamic type different. They do, like intended, prefer rvalue references during overloading, and won't bind to non-const lvalue references.
What previously was an rvalue (literals, objects created by casts to non-reference types) now becomes an prvalue. They have the same preference as xvalues during overloading.
What previously was an lvalue stays an lvalue.
And two groupings are done to capture those that can be qualified and can have different dynamic types (glvalues) and those where overloading prefers rvalue reference binding (rvalues).
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).
As for wrappers, the best ones i've used (as previously suggested) are:
and
best of luck!
New version 4.100.x.xxxx
Try this:
More Apps > Android Settings > Accessibility > Auto-rotate screen = Enabled
The orange highlight effect is a style on the ListView. This article gives a good overview of how to override the listView style.
Essentially, you have a selector that specifies different style elements based on the current state.
see this for short and quick solution https://stackoverflow.com/a/12242564/185022
Google is my friend and it showed me this page:
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
FileInfo[] files = directoryInfo.GetFiles();
List<FileInfo> lastUpdatedFile = null;
DateTime lastUpdate = new DateTime(1, 0, 0);
foreach (FileInfo file in files)
{
if (file.LastAccessTime > lastUpdate)
{
lastUpdatedFile.Add(file);
lastUpdate = file.LastAccessTime;
}
}
return lastUpdatedFile;
}
You should use the as
operator combined with the ??
operator for default values. Value types will need to be read as nullable and given a default.
employee.FirstName = sqlreader[indexFirstName] as string;
employee.Age = sqlreader[indexAge] as int? ?? default(int);
The as
operator handles the casting including the check for DBNull.
If it is XAMPP, Do the following:
cd /opt/lampp/var/mysql;
sudo su;
rm -rf test;
Hope this helps.
The fact that primitives are signed in Java is irrelevant to how they're represented in memory / transit - a byte is merely 8 bits and whether you interpret that as a signed range or not is up to you. There is no magic flag to say "this is signed" or "this is unsigned".
As primitives are signed the Java compiler will prevent you from assigning a value higher than +127 to a byte (or lower than -128). However, there's nothing to stop you downcasting an int (or short) in order to achieve this:
int i = 200; // 0000 0000 0000 0000 0000 0000 1100 1000 (200)
byte b = (byte) 200; // 1100 1000 (-56 by Java specification, 200 by convention)
/*
* Will print a negative int -56 because upcasting byte to int does
* so called "sign extension" which yields those bits:
* 1111 1111 1111 1111 1111 1111 1100 1000 (-56)
*
* But you could still choose to interpret this as +200.
*/
System.out.println(b); // "-56"
/*
* Will print a positive int 200 because bitwise AND with 0xFF will
* zero all the 24 most significant bits that:
* a) were added during upcasting to int which took place silently
* just before evaluating the bitwise AND operator.
* So the `b & 0xFF` is equivalent with `((int) b) & 0xFF`.
* b) were set to 1s because of "sign extension" during the upcasting
*
* 1111 1111 1111 1111 1111 1111 1100 1000 (the int)
* &
* 0000 0000 0000 0000 0000 0000 1111 1111 (the 0xFF)
* =======================================
* 0000 0000 0000 0000 0000 0000 1100 1000 (200)
*/
System.out.println(b & 0xFF); // "200"
/*
* You would typically do this *within* the method that expected an
* unsigned byte and the advantage is you apply `0xFF` only once
* and than you use the `unsignedByte` variable in all your bitwise
* operations.
*
* You could use any integer type longer than `byte` for the `unsignedByte` variable,
* i.e. `short`, `int`, `long` and even `char`, but during bitwise operations
* it would get casted to `int` anyway.
*/
void printUnsignedByte(byte b) {
int unsignedByte = b & 0xFF;
System.out.println(unsignedByte); // "200"
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}
Another option is to use a destination wildcard. Note that this only works if the source and destination filenames will be the same, so while this doesn't solve the OP's specific example, I thought it was worth sharing.
For example:
xcopy /y "bin\development\whee.config.example" "TestConnectionExternal\bin\Debug\*"
will create a copy of the file "whee.config.example" in the destination directory without prompting for file or directory.
Update: As mentioned by @chapluck:
You can change "* "
to "[newFileName].*"
. It persists file extension but allows to rename. Or more hacky: "[newFileName].[newExt]*"
to change extension
In your php file enter:
$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";
and in your js file send an ajax with the data object
var data = {
bar : 'bar value',
time: calculatedTimeStamp,
hash: calculatedHash,
uid: userID,
sid: sessionID,
iid: itemID
};
$.ajax({
method: 'POST',
crossDomain: true,
dataType: 'json',
crossOrigin: true,
async: true,
contentType: 'application/json',
data: data,
headers: {
'Access-Control-Allow-Methods': '*',
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Access-Control-Allow-Origin": "*",
"Control-Allow-Origin": "*",
"cache-control": "no-cache",
'Content-Type': 'application/json'
},
url: 'https://yoururl.com/somephpfile.php',
success: function(response){
console.log("Respond was: ", response);
},
error: function (request, status, error) {
console.log("There was an error: ", request.responseText);
}
})
or keep it as is with the form-submit. You need this only, if you want to send a modified request with calculated additional content and not only some form-data, which is entered by the client. For example a hash, a timestamp, a userid, a sessionid and the like.
You can try replacing this line:
return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
By those:
DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();
Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;
This will work:
>>> t = [1,1,2,2,3,3,4,5]
>>> print list(set(t))
[1,2,3,4,5]
However, if you have used "list" or "set" as a variable name you will get the:
TypeError: 'set' object is not callable
eg:
>>> set = [1,1,2,2,3,3,4,5]
>>> print list(set(set))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Same error will occur if you have used "list" as a variable name.
Sqlite has officially list of converting tools.
Update 2018-04-11
Here's a Javascript-less, CSS-only solution. The image will dynamically be centered and resized to fit the window.
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
.imgbox {
display: grid;
height: 100%;
}
.center-fit {
max-width: 100%;
max-height: 100vh;
margin: auto;
}
</style>
</head>
<body>
<div class="imgbox">
<img class="center-fit" src='pic.png'>
</div>
</body>
</html>
The [other, old] solution, using JQuery, sets the height of the image container (body
in the example below) so that the max-height
property on the image works as expected. The image will also automatically resize when the client window is resized.
<!DOCTYPE html>
<html>
<head>
<style>
* {
padding: 0;
margin: 0;
}
.fit { /* set relative picture size */
max-width: 100%;
max-height: 100%;
}
.center {
display: block;
margin: auto;
}
</style>
</head>
<body>
<img class="center fit" src="pic.jpg" >
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
function set_body_height() { // set body height = window height
$('body').height($(window).height());
}
$(document).ready(function() {
$(window).bind('resize', set_body_height);
set_body_height();
});
</script>
</body>
</html>
Note: User gutierrezalex packaged a very similar solution as a JQuery plugin on this page.
Here is a way to handle duplicate tuple "keys":
# An example
l = [('A', 1), ('B', 2), ('C', 3), ('A', 5), ('D', 0), ('D', 9)]
# A solution
d = dict()
[d [t [0]].append(t [1]) if t [0] in list(d.keys())
else d.update({t [0]: [t [1]]}) for t in l]
d
OUTPUT: {'A': [1, 5], 'B': [2], 'C': [3], 'D': [0, 9]}
Jonathan Lonowski answered perfectly, but there is something that none of the answers mentioned here. Instead of File::extname
, you can directly use a '.*'
to get the file name.
File.basename("C:\\projects\\blah.dll", ".*") # => "C:\\projects\\blah"
But, if you want to get the base file name of any specific extension files, then you need to use File::extname
, otherwise not.
You can never get 100% isolation. Because a pod may have some shared dependencies and if you attempt to update your single pod, then it would update the dependencies of other pods as well. If that is ok then:
tl;dr use:
pod update podName
Why? Read below.
pod update
will NOT respect the podfile.lock
. It will override it — pertaining to that single podpod install
will respect the podfile.lock
, but will try installing every pod mentioned in the podfile based on the versions its locked to (in the Podfile.lock).This diagram helps better understand the differences:
The major problem comes from the ~>
aka optimistic operator.
Podfile
is not enoughSome might think that specifying exact versions of their pods in their Podfile
, like pod 'A', '1.0.0'
, is enough to guarantee that every user will have the same version as other people on the team.
Then they might even use pod update
, even when just adding a new pod, thinking it would never risk updating other pods because they are fixed to a specific version in the Podfile
.
But in fact, that is not enough to guarantee that user1 and user2 in our above scenario will always get the exact same version of all their pods.
One typical example is if the pod A
has a dependency on pod A2
— declared in A.podspec
as dependency 'A2', '~> 3.0'
. In such case, using pod 'A', '1.0.0'
in your Podfile will indeed force user1 and user2 to both always use version 1.0.0 of the pod A, but:
A2
in version 3.4
(because that was A2
's latest version at that time)pod install
when joining the project later, they might get pod A2
in version 3.5
(because the maintainer of A2
might have released a new version in the meantime).
That's why the only way to ensure every team member work with the same versions of all the pod on each's the computer is to use the Podfile.lock
and properly use pod install
vs. pod update
.The above excerpt was all derived from pod install vs. pod update
I also highly recommend watching what does a podfile.lock
do
FWIW, you probably want to look at F# instead of C# in the context of technical computing because F# is specifically designed for that purpose. However, I developed my own commercial plotting library because I was not satisfied with anything freely available on .NET.
When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.
three step for put background
1)you should choose your like picture. for example :enter image description here
2)Then you copy this picture in drawable. warning: you should choose types short for name picture.
3)you go to page xml Intended and write :
android:background="id picture" for example my picture id is @drawable/download.
finish.
Instead of calling /usr/bin/gcc
, use /usr/bin/c99
. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc
after having added the -std=c99
flag, which is precisely what you want.
I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));
if you have adapter to set. So you can follow this. Just call the getContext
adapter = new Adapter(getContext(), myModelList);
If you have Toast to show, use same thing above
Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();
Hope this will work.
HappyCoding
All the properties of your object are private. aka... not available outside their class's scope.
Use the new JsonSerializable
Interface to provide your own json representation to be used by json_encode
class Thing implements JsonSerializable {
...
public function jsonSerialize() {
return [
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
];
}
...
}
If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode()
on a data structure you create for this purpose.
class Thing {
...
public function to_json() {
return json_encode(array(
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
));
}
...
}
I tried using it and didn't work, guess it's just the modal versioin.
Although, it worked as this:
$("#myModal").on("hide.bs.modal", function () {
// put your default event here
});
Just to update the answer =)
Use the target
attribute on your anchor
tag with the _blank
value.
Example:
<a href="http://google.com" target="_blank">Click Me!</a>
Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -
def change
drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end
If your date needs to match DD.MM.YYYY and use AngularJS, use the following code:
$scope.validDate = function(value){
var matches = /^(\d{1,2})[.](\d{1,2})[.](\d{4})$/.exec(value);
if (matches == null) return false;
var d = matches[1];
var m = matches[2] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
};
console.log($scope.validDate('22.04.2001'));
console.log($scope.validDate('03.10.2001'));
console.log($scope.validDate('30.02.2001'));
console.log($scope.validDate('23.09.2016'));
console.log($scope.validDate('29.02.2016'));
console.log($scope.validDate('31.02.2016'));
More about the scope object can be found here. Without AngularJS, simply change the first line to:
ValidDate = new function(value) {
And call it using:
var MyDate= ValidDate('29.09.2016');
The SQLite command line utility has a .schema TABLENAME
command that shows you the create statements.
You need to use dynamic SQL to achieve this; something like:
DECLARE
TYPE cur_type IS REF CURSOR;
CURSOR client_cur IS
SELECT DISTING username
FROM all_users
WHERE length(username) = 3;
emails_cur cur_type;
l_cur_string VARCHAR2(128);
l_email_id <type>;
l_name <type>;
BEGIN
FOR client IN client_cur LOOP
dbms_output.put_line('Client is '|| client.username);
l_cur_string := 'SELECT id, name FROM '
|| client.username || '.org';
OPEN emails_cur FOR l_cur_string;
LOOP
FETCH emails_cur INTO l_email_id, l_name;
EXIT WHEN emails_cur%NOTFOUND;
dbms_output.put_line('Org id is ' || l_email_id
|| ' org name ' || l_name);
END LOOP;
CLOSE emails_cur;
END LOOP;
END;
/
Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR
and an example.
Edited to make the inner cursor query a string variable.
It depends on the size of your database.
SQL is based on the SET theory: there is no order inherently used when querying a table.
So if you were to run the first query, it would first order by product price and then product name, IF there were any duplicates in the price category, say $20 for example, it would then order those duplicates by their names, therefore always maintaining that when you run your query it will always return the same set of result in the same order.
If you were to run the second query, it would only order by the name, so if there were two products with the same name (for some odd reason) then they wouldn't have a guaranteed order after you run the query.
Both rebase
(and cherry-pick
) and merge
have their advantages and disadvantages. I argue for merge
here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase
is preferred.)
merge
is preferred over cherry-pick
and rebase
for a couple of reasons.
merge
workflow fairly easily. rebase
tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.Even with a merge-heavy workflow rebase
and cherry-pick
are still useful for particular cases:
merge
is cluttered history. rebase
prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase
code that you have shared with other repositories. Once a commit is push
ed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.cherry-pick
is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.
#form{
position:fixed;
top:50%;
left:50%;
width:250px;
}
You can adjust top & left depending on form size.
I found one solution for MYSQL its easy to add new column for SrNo or kind of tepropery auto increment column by following this query:
SELECT @ab:=@ab+1 as SrNo, tablename.* FROM tablename, (SELECT @ab:= 0)
AS ab
A possibility is using flash cookies:
You'll need to build a small (hidden) flash movie to read and write them.
Whatever route you pick, make sure your users opt IN to being tracked, otherwise you're invading their privacy and become one of the bad guys.
Below command helps to search for any files
1) Irrespective of case
2) Result Excluding folders without permission
3) Searching from the root or from the path you like. Change / with the path you prefer.
Syntax :
find -iname '' 2>&1 | grep -v "Permission denied"
Example
find / -iname 'C*.xml' 2>&1 | grep -v "Permission denied"
find / -iname '*C*.xml' 2>&1 | grep -v "Permission denied"
Here's another way of getting a Bash array with the example JSON given by @anubhava in his answer:
arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))
echo ${arr[0]} # 'Archiver-Version'
echo ${arr[1]} # 'Build-Id'
echo ${arr[2]} # 'Build-Jdk'
// Returns bottom offset value + or - from viewport top
function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom }
// Returns right offset value
function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right }
var bottom = offsetBottom('#logo');
var right = offsetRight('#logo');
This will find the distance from the top and left of your viewport to your element's exact edge and nothing beyond that. So say your logo was 350px and it had a left margin of 50px, variable 'right' will hold a value of 400 because that's the actual distance in pixels it took to get to the edge of your element, no matter if you have more padding or margin to the right of it.
If your box-sizing CSS property is set to border-box it will continue to work just as if it were set as the default content-box.
Since TypeScript 3.7 was released you can use optional chaining now.
Property example:
let x = foo?.bar.baz();
This is equvalent to:
let x = (foo === null || foo === undefined) ?
undefined :
foo.bar.baz();
Moreover you can call:
Optional Call
function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
otherFn will be called only if otherFn won't be equal to null or undefined
Usage optional chaining in IF statement
This:
if (someObj && someObj.someProperty) {
// ...
}
can be replaced now with this
if (someObj?.someProperty) {
// ...
}
Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
Since .NET Framework 4.5 and .NET Standard 1.0 you should use WebUtility.UrlEncode
. Advantages over alternatives:
It is part of .NET Framework 4.5+, .NET Core 1.0+, .NET Standard 1.0+, UWP 10.0+ and all Xamarin platforms as well. HttpUtility
, while being available in .NET Framework earlier (.NET Framework 1.1+), becomes available on other platforms much later (.NET Core 2.0+, .NET Standard 2.0+) and it still unavailable in UWP (see related question).
In .NET Framework, it resides in System.dll
, so it does not require any additional references, unlike HttpUtility
.
It properly escapes characters for URLs, unlike Uri.EscapeUriString
(see comments to drweb86's answer).
It does not have any limits on the length of the string, unlike Uri.EscapeDataString
(see related question), so it can be used for POST requests, for example.
There is an operator missing, likely a *
:
-3.7 need_something_here (prof[x])
The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7
(a float) as a function, which is not allowed.
The parenthesis are also not needed in this case, the following may be sufficient/correct:
-3.7 * prof[x]
As Legolas points out, there are other things which may need to be addressed:
2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
^-- op missing
extra parenthesis --^
valid but questionable float*tuple --^
expression yields 0.0 always --^
"Rounded" down as in your example. This will return a varchar value of the date.
DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'
SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15
expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:
if expr match "$LIST" "$SOURCE"; then
But I'm not really clear what SOURCE is supposed to represent.
It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?
I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.
You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.
Here is my solution:
<div class="form-group row">
<div class="col-xs-8">
<label class="control-label">My Label</label>
<div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
<input class="form-control" type="text" readonly="" value="12-02-2012">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
CSS changes in datepicker.css on lines 176-177:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 34:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
UPDATE
Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:
CSS changes in datepicker.css on lines 446-447:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 46:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;
Finally, the JavaScript to enable the datepicker (with some options):
$(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });
Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.
As mentioned before, [[NSDate date] timeIntervalSince1970] returns an NSTimeInterval, which is a duration in seconds, not milli-seconds.
You can visit https://currentmillis.com/ to see how you can get in the language you desire. Here is the list -
ActionScript (new Date()).time
C++ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()
C#.NET DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
Clojure (System/currentTimeMillis)
Excel / Google Sheets* = (NOW() - CELL_WITH_TIMEZONE_OFFSET_IN_HOURS/24 - DATE(1970,1,1)) * 86400000
Go / Golang time.Now().UnixNano() / 1000000
Hive* unix_timestamp() * 1000
Java / Groovy / Kotlin System.currentTimeMillis()
Javascript new Date().getTime()
MySQL* UNIX_TIMESTAMP() * 1000
Objective-C (long long)([[NSDate date] timeIntervalSince1970] * 1000.0)
OCaml (1000.0 *. Unix.gettimeofday ())
Oracle PL/SQL* SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
Perl use Time::HiRes qw(gettimeofday); print gettimeofday;
PHP round(microtime(true) * 1000)
PostgreSQL extract(epoch FROM now()) * 1000
Python int(round(time.time() * 1000))
Qt QDateTime::currentMSecsSinceEpoch()
R* as.numeric(Sys.time()) * 1000
Ruby (Time.now.to_f * 1000).floor
Scala val timestamp: Long = System.currentTimeMillis
SQL Server DATEDIFF(ms, '1970-01-01 00:00:00', GETUTCDATE())
SQLite* STRFTIME('%s', 'now') * 1000
Swift* let currentTime = NSDate().timeIntervalSince1970 * 1000
VBScript / ASP offsetInMillis = 60000 * GetTimeZoneOffset()
WScript.Echo DateDiff("s", "01/01/1970 00:00:00", Now()) * 1000 - offsetInMillis + Timer * 1000 mod 1000
For objective C I did something like below to print it -
long long mills = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
NSLog(@"Current date %lld", mills);
Hopw this helps.
This is for who are working custom cell with .xib
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let identifier = "Custom"
var cell: CustomCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCel
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: identifier)
cell =tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCell
}return cell}
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
Setting overflow: hidden
hides the scrollbar. Set overflow: scroll
to make sure the scrollbar appears all the time.
To use the ::webkit-scrollbar
property, simply target .scroll
before calling it.
.scroll {
width: 200px;
height: 400px;
background: red;
overflow: scroll;
}
.scroll::-webkit-scrollbar {
width: 12px;
}
.scroll::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
.scroll::-webkit-scrollbar-thumb {
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
?
See this live example
Simply use the base transpose function t
, wrapped with as.data.frame
:
final_df <- as.data.frame(t(starting_df))
final_df
A B C D
a 1 2 3 4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd
Above updated. As docendo discimus pointed out, t
returns a matrix. As Mark suggested wrapping it with as.data.frame
gets back a data frame instead of a matrix. Thanks!
SWIFT
Usually for normal transition we use,
let next:SecondViewController = SecondViewController()
self.presentViewController(next, animated: true, completion: nil)
But sometimes when using navigation controller, you might face a black screen. In that case, you need to use like,
let next:ThirdViewController = storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.navigationController?.pushViewController(next, animated: true)
Moreover none of the above solution preserves navigationbar when you call from storyboard or single xib to another xib. If you use nav bar and want to preserve it just like normal push, you have to use,
Let's say, "MyViewController" is identifier for MyViewController
let viewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)
There is also %s
that allows you to create any symbols, for example:
%s|some words| #Same as :'some words'
%s[other words] #Same as :'other words'
%s_last example_ #Same as :'last example'
Since Ruby 2.0.0 you also have:
%i( a b c ) # => [ :a, :b, :c ]
%i[ a b c ] # => [ :a, :b, :c ]
%i_ a b c _ # => [ :a, :b, :c ]
# etc...