SET SQL_SAFE_UPDATES=0;
OR
Go to Edit --> Preferences
Click SQL Queries
tab and uncheck Safe Updates
check box
Query --> Reconnect to Server
Now execute your sql query
android only use linux kernel, that means the GNU tool chain like gcc as are not implemented in android, so if you want run a linux app in android, you need recompile it with google's tool chain( NDK ).
I think it massively clutters up the source code.
It also doesn't gain you much in a strongly typed language. If you do any form of type mismatch tomfoolery, the compiler will tell you about it.
A good explanation of how BFS computes shortest paths, accompanied by the most efficient simple BFS algorithm of which I'm aware and also by working code, is provided in the following peer-reviewed paper:
https://queue.acm.org/detail.cfm?id=3424304
The paper explains how BFS computes a shortest-paths tree represented by per-vertex parent pointers, and how to recover a particular shortest path between any two vertices from the parent pointers. The explanation of BFS takes three forms: prose, pseudocode, and a working C program.
The paper also describes "Efficient BFS" (E-BFS), a simple variant of classic textbook BFS that improves its efficiency. In the asymptotic analysis, running time improves from Theta(V+E) to Omega(V). In words: classic BFS always runs in time proportional to the number of vertices plus the number of edges, whereas E-BFS sometimes runs in time proportional to the number of vertices alone, which can be much smaller. In practice E-BFS can be much faster, depending on the input graph. E-BFS sometimes offers no advantage over classic BFS but it's never much slower.
Remarkably, despites its simplicity E-BFS appears not to be widely known.
The first argument in sys will be the current file name so this will work
import sys
print sys.argv[0] # will print the file name
try {
String text = "Hello, Admin sir";// Replace with your message.
String toNumber = "xxxxxxxxxxxx"; // Replace with mobile phone number without +Sign or leading zeros, but with country code
//Suppose your country is India and your phone number is “xxxxxxxxxx”, then you need to send “91xxxxxxxxxx”.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + toNumber + "&text=" + text));
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
Notice that this doesn't work in Windows.
The module pxssh does exactly what you want:
For example, to run 'ls -l' and to print the output, you need to do something like that :
from pexpect import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
print "SSH session failed on login."
print str(s)
else:
print "SSH session login successful"
s.sendline ('ls -l')
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.logout()
Some links :
Pxssh docs : http://dsnra.jpl.nasa.gov/software/Python/site-packages/Contrib/pxssh.html
Pexpect (pxssh is based on pexpect) : http://pexpect.readthedocs.io/en/stable/
<div>
<img src="whatever it is" class="image-crop">
</div>
/*mobile code*/
.image-crop{
width:100%;
max-height: auto;
}
/*desktop code*/
@media screen and (min-width: 640px) {
.image-crop{
width:100%;
max-height: 140px;
}
If you're using Rails and ActiveAdmin, this is going to be your problem: https://github.com/seyhunak/twitter-bootstrap-rails/issues/450 Basically, a conflict with active_admin.js
This is the solution: https://stackoverflow.com/a/11745446/264084 (Karen's answer) tldr: Move active_admin assets into the "vendor" directory.
Try this :
for match in re.finditer(r"\[P[^\]]*\](.*?)\[/P\]", subject):
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
STEP 1: FIRST OPEN THE COMMAND PROMPT WHERE YOUR FILE IS LOCATED. (right click while pressing shift)
STEP 2: THEN USE THE FOLLOWING COMMANDS TO EXECUTE.
(lets say the file and class name to be executed is named as Student.java)The example program is in the picture background.
javac Student.java
java Student
Most likely, the userdata()
function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.
You need pow();
function from math.h
header.
syntax
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y
.
usage
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
And make sure you include math.h
to avoid warning ("incompatible implicit declaration of built in function 'pow'
").
Link math library by using -lm
while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
You can write your own Extension method for type String :-
public static string NonBlankValueOf(this string source)
{
return (string.IsNullOrEmpty(source)) ? "0" : source;
}
Now you can use it like with any string type
FooTextBox.Text = strFoo.NonBlankValueOf();
Slightly more "Angular way" would be to use the straightforward limitTo
filter, as natively provided by Angular:
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
app.controller('PhoneListCtrl', function($scope, $http) {
$http.get('phones.json').then(
function(phones){
$scope.phones = phones.data;
}
);
$scope.orderProp = 'age';
$scope.quantity = 5;
}
);
Might be, more safe alternative to "_ORACLE_SCRIPT"=true
is to change "_common_user_prefix"
from C##
to an empty string. When it's null - any name can be used for common user. Found there.
During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).
So for me worked that:
alter system set _common_user_prefix = ''; scope=spfile;
The iPhone6/6s/6+ are NOT designed to read passive NFC tags (aka Discovery Mode). There's a lot of misinformation on this topic, so I thought to provide some tangible info for developers to consider. The lack of NFC tag read support is not because of software but because of hardware. To understand why, you need to understand how NFC works. NFC works by way of Load Modulation. That means that the interrogator (PCD) emits a carrier magnetic field that energizes the passive target (PICC). With the potential generated by this carrier field, the target then is able to demodulate data coming from the interrogator and respond by modulating data over top of this very same field. The key here is that the target never creates a field of its own.
If you look at the iPhone6 teardown and parts list you will see the presence of a very small NFC loop antenna as well as the use of the AS3923 booster IC. This design was intended for custom microSD or SIM cards to enable mobile phones of old to do payments. This is the type of application where the mobile phone presents a Card Emulated credential to a high power contactless POS terminal. The POS terminal acts as the reader, energizing the iPhone6 with help from the AS3923 chip. The AS3923 block diagram clearly shows how the RX and TX modulation is boosted from a signal presented by a reader device. In other words the iPhone6 is not meant to provide a field, only to react to one. That's why it's design is only meant for NFC Card Emulation and perhaps Peer-2-Peer, but definitely not tag Discovery.
There are some alternatives to achieving tag Discovery with an iPhone6 using HW accessories. I talk about these integrations and how developers can architect solutions in this blog post. Our low power reader designs open interesting opportunities for mobile engagement that few developers are thinking about.
Disclosure: I'm the founder of Flomio, Inc., a TechStars company that delivers proximity ID hardware, software, and services for applications ranging from access control to payments.
Update: This rumor, if true, would open up the possibility for the iPhone to practically support NFC tag Discovery mode. An all glass design would not interfere with the NFC antenna as does the metal back of the current iPhone. We've attempted this design approach --albeit with cheaper materials-- on some of our custom reader designs with success so looking forward to this improvement.
Update: iOS11 has announced support for "NFC reader mode" for iPhone7/7+. Details here. API only supports reading NDEF messages (no ISO7816 APDUs) while an app is in the foreground (no background detection). Due out in the Fall, 2017... check the screenshot from WWDC keynote:
You can use javascript
ctl.attachEvent('onkeydown', function(event) {
try {
if (event.keyCode == 13) {
FieldValueChanged(ctl.id, ctl.value);
}
false;
} catch (e) { };
return true
})
You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:
Old page: http://something.com/profile.php?id=a&abc=1
New page: http://something.com/profile/?id=a&abc=1
If you are not satisfied leave a comment for complicated methods.
As it was mentioned by Davos you can use the IDLEX
It happens that I'm using Linux version and from all extensions I needed only LineNumbers. So I've downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python's lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is ~/.idlerc/config-extensions.cfg:
[LineNumbers]
enable = 1
enable_shell = 0
visible = True
[LineNumbers_cfgBindings]
linenumbers-show =
Updated 2020
Here's an updated answer for the latest Bootstrap 4.0.0. This version has classes that will help you create a sticky or fixed sidebar without the extra CSS....
Use sticky-top
:
<div class="container">
<div class="row py-3">
<div class="col-3 order-2" id="sticky-sidebar">
<div class="sticky-top">
...
</div>
</div>
<div class="col" id="main">
<h1>Main Area</h1>
...
</div>
</div>
</div>
Demo: https://codeply.com/go/O9GMYBer4l
or, use position-fixed
:
<div class="container-fluid">
<div class="row">
<div class="col-3 px-1 bg-dark position-fixed" id="sticky-sidebar">
...
</div>
<div class="col offset-3" id="main">
<h1>Main Area</h1>
...
</div>
</div>
</div>
Demo: https://codeply.com/p/0Co95QlZsH
Also see:
Fixed and scrollable column in Bootstrap 4 flexbox
Bootstrap col fixed position
How to use CSS position sticky to keep a sidebar visible with Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
You can also call GetSchemaTable() on your DataReader if you want the list of columns and you don't want to have to get an exception...
Maybe your forgot to run git fetch? it's required to fetch data from the remote repo! Try running git fetch remote/branch
I have modified the solution of @yogi. The addition is that when the file is of incorrect format I reset the input element value.
function checkFile(sender, validExts) {
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0 && fileExt != "") {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
$(sender).val("");
return false;
}
else return true;
}
I have custom verification buildin, because in open file window the user can still choose the options "All files ('*')", regardless if I explicitly set the accept attribute in input element.
logical data model
A logical data model describes the data in as much detail as possible, without regard to how they will be physical implemented in the database. Features of a logical data model include: · Includes all entities and relationships among them. · All attributes for each entity are specified. · The primary key for each entity is specified. · Foreign keys (keys identifying the relationship between different entities) are specified. · Normalization occurs at this level. conceptual data model
A conceptual data model identifies the highest-level relationships between the different entities. Features of conceptual data model include: · Includes the important entities and the relationships among them. · No attribute is specified. · No primary key is specified.
I think the simplest way is to use awk. Example:
$ echo "11383 pts/1 00:00:00 bash" | awk '{ print $4; }'
bash
This is an easy way to prevent the click event from moving forward to the next component and then call your yourFunction.
<Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button>
You forgot to add the global operator. Use this:
var s = "04.07.2012";_x000D_
alert(s.replace(new RegExp("[0-9]","g"), "X"));
_x000D_
To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -
Hibernate Object States
Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.
Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.
Detached - A detached instance is an object that has been persistent, but its Session has been closed.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview
Transaction Write-Behind
The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.
- To perform batch inserts and updates.
- To propagate only the last change. If an object is updated more than once, it still fires only one update statement.
http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html
First Level Cache
Hibernate has something called 'First Level Cache'. Whenever you pass an object to save()
, update()
or saveOrUpdate()
, and whenever you retrieve an object using load()
, get()
, list()
, iterate()
or scroll()
, that object is added to the internal cache of the Session. This is where it tracks changes to various objects.
Hibernate Intercepters and Object Lifecycle Listeners -
The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069
This section Updated
Cascading
Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete'
from parent to child association will result in deletion of all children when a parent is deleted.
So, why are these important.
To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached
and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.
That's why hibernate (sometimes) issues a 'SELECT'
statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.
Why does hibernate issue the 'SELECT' statement only sometimes?
Hibernate issues a 'SELECT'
statement to determine what state the object is in. If the select statement returns an object, the object is in detached
state and if it does not return an object, the object is in transient
state.
Coming to your scenario -
Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached
and then re-attches it to the session and processes delete lifecycle.
Update - Since you are explicitly calling 'Update'
instead of 'SaveOrUpdate'
, hibernate blindly assumes that the object is in detached
state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.
SaveOrUpdate - If you call 'SaveOrUpdate'
, hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached
state. If the object is in transient
state, it processes the 'insert'
lifecycle and if the object is in detached
state, it processes the 'Update'
lifecycle.
Thanks to Seb33300 I got this working. However, an important part seems to be missing. At least in Bootstrap version 3.1.1.
My problem was that the navbar collapsed accordingly at the correct width, but the menu button didn't work. I couldn't expand and collapse the menu.
This is because the collapse.in class is overrided by the !important in .navbar-collapse.collapse, and can be solved by also adding the "collapse.in". Seb33300's example completed below:
@media (max-width: 991px) {
.navbar-header {
float: none;
}
.navbar-toggle {
display: block;
}
.navbar-collapse {
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
}
.navbar-collapse.collapse {
display: none!important;
}
.navbar-collapse.collapse.in {
display: block!important;
}
.navbar-nav {
float: none!important;
margin: 7.5px -15px;
}
.navbar-nav>li {
float: none;
}
.navbar-nav>li>a {
padding-top: 10px;
padding-bottom: 10px;
}
}
I recently hit this problem. In my case, I have NuGet packages on different assemblies. What I had was different versions of the same NuGet packages associated with my own assemblies.
My solution was to use the NuGet package manager upon the Solution, as opposed to the individual projects. This enables a "consolidation" option, where you can upgrade your NuGet packages across as many projects as you want - so they all reference the same version of the assembly.
When I did the consolidations, the build failure disappeared.
for decimal values greater than zero, HTML5 works as follows:
<input id="txtMyDecimal" min="0" step="any" type="number">
Assuming that obj
is a pre-constructed object (and not a JSON string), you can achieve this with the following:
Object.keys(obj).forEach(function(key){
console.log(key + '=' + obj[key]);
});
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
@Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.
DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
The problem is that your REGX pattern will only match the input "0-9".
To meet your requirement (0-9999999), you should rewrite your regx pattern:
ng-pattern="/^[0-9]{1,7}$/"
My example:
HTML:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field"
ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<span ng-show="myForm.price_field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>
JS:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
Here is a jsFiddle demo.
Based upon which, IIS 7.5 Application Pool's identity use one of the following.
IIS AppPool\AppPoolName
and grant it Full control
. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS
)Update based upon @Phil Hale comment:
Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.
The answers above are incorrect, they will all run weather or not the submission is successful... You need to write an error component that will receive any errors then check if there are errors in state, if there are not then clear the form....
use .then()
example:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
setTicketData({
ticketType: "IT",
ticketSubject: "",
ticketDescription: "",
itHelpType: "",
ticketPriority: ""
})
})
};
You should take a look at how the guys at getdropbox.com do it for their client software, including Linux. It's quite tricky to crack and requires some quite creative disassembly to get past the protection mechanisms.
TypeScript 0.9+ has a specification for enums:
enum AnimationType {
BOUNCE,
DROP,
}
The final comma is optional.
In PHP
$unix_time = 1256571985;
echo date("Y-m-d H:i:s",$unix_time)
If the cube is directly inside the container:
#container:hover > #cube { background-color: yellow; }
If cube is next to (after containers closing tag) the container:
#container:hover + #cube { background-color: yellow; }
If the cube is somewhere inside the container:
#container:hover #cube { background-color: yellow; }
If the cube is a sibling of the container:
#container:hover ~ #cube { background-color: yellow; }
Nowadays (2016) in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.
getEventListeners(document.querySelector('your-element-selector'));
This topic may be old, but here's a quick fix
ul {list-style:outside none square;}
or
ul {list-style:outside none disc;}
, etc...
then add left padding to list element
ul li{line-height: 1.4;padding-bottom: 6px;}
Couldn't get bootstrap datepicker to work until I wrap the textbox with position relative element as shown here:
<span style="position: relative">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</span>
There is a NuGet package Microsoft Experimental Collections that contains a class MultiValueDictionary
which does exactly what you need.
Here is a blog post of the creator of the package that describes it further.
Here is another blog post if you're feeling curious.
Example Usage:
MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
The following worked for me:
Registry Editor
(press windows key, type regedit
and hit Enter
) .HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
and clear the values.HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
.STL has a max_elements function. Here is an example: http://www.cplusplus.com/reference/algorithm/max_element/
Solaris has the pstack command, which was also copied into Linux.
I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code
import {JsonObject1name, JsonObject2name} from 'your Json file path';
Now you can access JsonObject1,2 names in data section of export default part as below:
data: () => ({
schema: JsonObject1name,
schema1: JsonObject2name,
model: {}
}),
Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :
<SchemaForm id="unique name representing your Json object1" class="form" v-model="model" :schema="schema" :components="components">
</SchemaForm>
<SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
</SchemaForm>
SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.
I hope this answer helps someone. I can help if there are any questions.
After building the project right click on the project Debug > “Debug Configurations”, as shown below
In the “debugger” tab, ensure the “GDB command file” now points to your “.gdbinit” file. Else, input the path to your “.gdbinit” configuration file :
Click “Apply” and “Debug”. A native DOS command line should be launched as shown below
UPDATE: Ruby 1.9.3 Kernel#rand
also accepts ranges
rand(a..b)
http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
Converting to array may be too expensive, and it's unnecessary.
(a..b).to_a.sample
Or
[*a..b].sample
Standard in Ruby 1.8.7+.
Note: was named #choice in 1.8.7 and renamed in later versions.
But anyway, generating array need resources, and solution you already wrote is the best, you can do.
Be careful, d
is the list.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
The vue-router
uses hash-mode
, in simple words it is something that you would normally expect from an achor tag like this.
<a href="#some_section">link<a>
To make the hash disappear
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
] // Routes Array
const router = new VueRouter({
mode: 'history', // Add this line
routes
})
Warning
: If you do not have a properly configured server or you are using a client-side SPA user may get a 404 Error
if they try to access https://website.com/posts/3
directly from their browser.
Vue Router Docs
i think this is really quick
document.querySelectorAll('body,body *').forEach(function(e) {
My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.
function isString(x) {
return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}
See: http://jsfiddle.net/x75uy0o6/
I'd like to know if this method has flaws, but it has served me well for years.
You could use PHP's json_decode function:
$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
SELECT 1, 2, 3
UNION ALL SELECT 4, 5, 6
UNION ALL SELECT 7, 8, 9
Updated answer now that xyo.net has been bought and shut down.
appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!
Outdated answer:
Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!
From number to currency string is easy through Number.prototype.toLocaleString. However the reverse seems to be a common problem. The thousands separator and decimal point may not be obtained in the JS standard.
In this particular question the thousands separator is a white space " "
but in many cases it can be a period "."
and decimal point can be a comma ","
. Such as in 1 000 000,00
or 1.000.000,00
. Then this is how i convert it into a proper floating point number.
var price = "1 000.000,99",
value = +price.replace(/(\.|\s)|(\,)/g,(m,p1,p2) => p1 ? "" : ".");
console.log(value);
_x000D_
So the replacer callback takes "1.000.000,00"
and converts it into "1000000.00"
. After that +
in the front of the resulting string coerces it into a number.
This function is actually quite handy. For instance if you replace the p1 = ""
part with p1 = ","
in the callback function, an input of 1.000.000,00
would result 1,000,000.00
Adding to answer by @Sasxa,
In Injectables
you can use class
normally that is putting initial code in constructor
instead of using ngOnInit()
, it works fine.
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
For anyone going through these issues and uneasy about disabling a whole set of checks, there is a way to pass your own custom signatures to Intelephense.
Copied from Intelephese repo's comment (by @KapitanOczywisty):
https://github.com/bmewburn/vscode-intelephense/issues/892#issuecomment-565852100
For single workspace it is very simple, you have to create
.php
file with all signatures and intelephense will index them.If you want add stubs globally, you still can, but I'm not sure if it's intended feature. Even if
intelephense.stubs
throws warning about incorrect value you can in fact put there any folder name.{ "intelephense.stubs": [ // ... "/path/to/your/stub" ] }
Note: stubs are refreshed with this setting change.
You can take a look at build-in stubs here: https://github.com/JetBrains/phpstorm-stubs
In my case, I needed dspec's describe
, beforeEach
, it
... to don't be highlighted as errors, so I just included the file with the signatures /directories_and_paths/app/vendor/bin/dspec
in my VSCode's workspace settings, which had the function declarations I needed:
function describe($description = null, \Closure $closure = null) {
}
function it($description, \Closure $closure) {
}
// ... and so on
To summarize what was mentioned by Breno above
Say you have a variable with a path to a file
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)
returns the string 'myfile.py'
and
os.path.dirname(path)
returns the string '/home/User/Desktop'
(without a trailing slash '/')
These functions are used when you have to get the filename/directory name given a full path name.
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'
you just have myfile.py
), os.path.dirname(path)
returns an empty string.
See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% else %}
No athletes.
{% endif %}
Example of all method
First : string.charAt(index)
Return the caract at the index
index
var str = "Stack overflow";_x000D_
_x000D_
console.log(str.charAt(0));
_x000D_
Second : string.substring(start,length);
Return the substring in the string who start at the index
start
and stop after the lengthlength
Here you only want the first caract so : start = 0
and length = 1
var str = "Stack overflow";_x000D_
_x000D_
console.log(str.substring(0,1));
_x000D_
Alternative : string[index]
A string is an array of caract. So you can get the first caract like the first cell of an array.
Return the caract at the index
index
of the string
var str = "Stack overflow";_x000D_
_x000D_
console.log(str[0]);
_x000D_
If you are using the fixed pipeline (OpenGL < 3.3) or the compatibility profile you can use
//Turn on wireframe mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//Draw the scene with polygons as lines (wireframe)
renderScene();
//Turn off wireframe mode
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
In this case you can change the line width by calling glLineWidth
Otherwise you need to change the polygon mode inside your draw method (glDrawElements, glDrawArrays, etc) and you may end up with some rough results because your vertex data is for triangles and you are outputting lines. For best results consider using a Geometry shader or creating new data for the wireframe.
That's because your first code snippet is not performing initialization, but assignment:
char myarray[4] = "abc"; // Initialization.
myarray = "abc"; // Assignment.
And arrays are not directly assignable in C.
The name myarray
actually resolves to the address of its first element (&myarray[0]
), which is not an lvalue, and as such cannot be the target of an assignment.
If you just don't want to waste your time on cross-domain issues during development and testing of your app you can use addon Force CORS for FF.
UPDATE: It seems that this addon no longer exists. But there is another option - this Chrome extension
I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.
SELECT wpoi.order_id As No_Commande
FROM wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id
AND wpp.meta_key = '_shipping_first_name'
WHERE wpoi.order_id =2198
Thanks for your question. I'am using wamp 3 now. And I find an simple answer to do this under your question. But that answer should change a little on wamp 3. The steps are as following:
add the onclick attribute
<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>
To get the cursor to change use css's cursor rule.
div[onclick] {
cursor: pointer;
}
The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.
Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap
'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.
Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.
The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.
body {_x000D_
font-family: sans-serif;_x000D_
margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
padding: 10px;_x000D_
background: lightgray;_x000D_
}_x000D_
ul {_x000D_
list-style: none;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
padding: 0;/* just to reset */_x000D_
padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
flex: 1 1 auto;_x000D_
margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
<li>a lacinia purus porttitor eget</li>_x000D_
<li>donec ut nunc lorem</li>_x000D_
<li>duis in est dictum</li>_x000D_
<li>tempor metus non</li>_x000D_
<li>dapibus sapien</li>_x000D_
<li>phasellus bibendum tincidunt</li>_x000D_
<li>quam vitae accumsan</li>_x000D_
<li>ut interdum eget nisl in eleifend</li>_x000D_
<li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc()
, or CSS preprocessors which only work when the units are the same, etc.
First, you need to call the owl.autoplay.js.
this code works for me : owl.trigger('play.owl.autoplay',[1000]);
you can also hide the gridline on yAxis as:
yAxis:{
gridLineWidth: 0,
minorGridLineWidth: 0
}
window.location.hash is a string
, so do this:
var page_number: number = 3;
window.location.hash = String(page_number);
I resolved this of following way:
here the code:
var deferred = $q.defer(),
self = this,
onConnect = function(status){
if (status === Strophe.Status.CONNECTING) {
deferred.notify({status: 'connecting'});
} else if (status === Strophe.Status.CONNFAIL) {
self.connected = false;
deferred.notify({status: 'fail'});
} else if (status === Strophe.Status.DISCONNECTING) {
deferred.notify({status: 'disconnecting'});
} else if (status === Strophe.Status.DISCONNECTED) {
self.connected = false;
deferred.notify({status: 'disconnected'});
} else if (status === Strophe.Status.CONNECTED) {
self.connection.send($pres().tree());
self.connected = true;
deferred.resolve({status: 'connected'});
} else if (status === Strophe.Status.ATTACHED) {
deferred.resolve({status: 'attached'});
self.connected = true;
}
},
output = function(data){
if (self.connected){
var rid = $(data).attr('rid'),
sid = $(data).attr('sid'),
storage = {};
if (localStorageService.cookie.get('day_bind')){
storage = localStorageService.cookie.get('day_bind');
}else{
storage = {};
}
storage[$window.name] = sid + '-' + rid;
localStorageService.cookie.set('day_bind', angular.toJson(storage));
}
};
if ($window.name){
var storage = localStorageService.cookie.get('day_bind'),
value = storage[$window.name].split('-')
sid = value[0],
rid = value[1];
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.attach('bosh@' + BoshDomain + '/' + $window.name, sid, parseInt(rid, 10) + 1, onConnect);
}else{
$window.name = 'web_' + (new Date()).getTime();
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.connect('bosh@' + BoshDomain + '/' + $window.name, '123456', onConnect);
}
I hope help you
None of those worked for me. Try this.
console.log($(canvasjQueryElement)[0].width)
Do I really have to create an NSString for "Wrong"?
No, why not just do:
if([statusString isEqualToString:@"Wrong"]){
//doSomething;
}
Using @""
simply creates a string literal, which is a valid NSString
.
Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?
Yes, you can do something like:
UILabel *label = ...;
if([someString isEqualToString:label.text]) {
// Do stuff here
}
Not sure if this is efficient or not, but strings in PowerShell can be referred to using array index syntax, in a similar fashion to Python.
It's not completely intuitive because of the fact the first letter is referred to by index = 0
, but it does:
Here are some examples:
PS > 'Hello World'[0..2]
Yields the result (index values included for clarity - not generated in output):
H [0]
e [1]
l [2]
Which can be made more useful by passing -join ''
:
PS > 'Hello World'[0..2] -join ''
Hel
There are some interesting effects you can obtain by using different indices:
Forwards
Use a first index value that is less than the second and the substring will be extracted in the forwards direction as you would expect. This time the second index value is far in excess of the string length but there is no error:
PS > 'Hello World'[3..300] -join ''
lo World
Unlike:
PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.
Backwards
If you supply a second index value that is lower than the first, the string is returned in reverse:
PS > 'Hello World'[4..0] -join ''
olleH
From End
If you use negative numbers you can refer to a position from the end of the string. To extract 'World'
, the last 5 letters, we use:
PS > 'Hello World'[-5..-1] -join ''
World
I'd refrain from using floats for this sort of thing; I'd rather use inline-block
.
Some more points to consider:
<head>
and <body>
doctype
Here's a better way to format your document:
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
<div id="left">Left Side Menu</div>
<div id="middle">Random Content</div>
<div id="right">Right Side Menu</div>
</div>
</body>
</html>
Here's a jsFiddle for good measure.
Make sure to check the python version you are working on if it is 2 then only pip install works If it is 3. something then make sure to use pip3 install
I'm not sure whether I got your problem but maybe it helps if you store the source using a UTF-8 encoding.
I'm also using \usepackage[utf8]{inputenc}
in my LaTeX sources and by storing the files as UTF-8 files everything works just peachy.
One possible solution is to encode the data in your app and use decoding at runtime (when you want to use that data). I also recommend to use progaurd to make it hard to read and understand the decompiled source code of your app . for example I put a encoded key in the app and then used a decode method in my app to decode my secret keys at runtime:
// "the real string is: "mypassword" ";
//encoded 2 times with an algorithm or you can encode with other algorithms too
public String getClientSecret() {
return Utils.decode(Utils
.decode("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
Decompiled source code of a proguarded app is this:
public String c()
{
return com.myrpoject.mypackage.g.h.a(com.myrpoject.mypackage.g.h.a("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
At least it's complicated enough for me. this is the way I do when I have no choice but store a value in my application. Of course we all know It's not the best way but it works for me.
/**
* @param input
* @return decoded string
*/
public static String decode(String input) {
// Receiving side
String text = "";
try {
byte[] data = Decoder.decode(input);
text = new String(data, "UTF-8");
return text;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error";
}
Decompiled version:
public static String a(String paramString)
{
try
{
str = new String(a.a(paramString), "UTF-8");
return str;
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
while (true)
{
localUnsupportedEncodingException.printStackTrace();
String str = "Error";
}
}
}
and you can find so many encryptor classes with a little search in google.
Just look at this solution, make sure you've turned access on to less secure apps on your google account :javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25
If you just want the anchor color to stay the same as the anchor's parent element you can leverage inherit:
a, a:visited, a:hover, a:active {
color: inherit;
}
Notice there is no need to repeat the rule for each selector; just use a comma separated list of selectors (order matters for anchor pseudo elements). Also, you can apply the pseudo selectors to a class if you want to selectively disable the special anchor colors:
.special-link, .special-link:visited, .special-link:hover, .special-link:active {
color: inherit;
}
Your question only asks about the visited state, but I assumed you meant all of the states. You can remove the other selectors if you want to allow color changes on all but visited.
radian can also be converted to degree by using numpy
print(np.rad2deg(1))
57.29577951308232
if needed to roundoff ( I did with 6 digits after decimal below), then
print(np.round(np.rad2deg(1), 6)
57.29578
In Java this would be System.in.read()
Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.
IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
ALTER TABLE Person
ADD ColumnName VARCHAR(MAX) NOT NULL
END
I also noticed yours is looking for where table does exist that is obviously just this
if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null
I often do it like that
enum EMyEnum
{
E_First,
E_Orange = E_First,
E_Green,
E_White,
E_Blue,
E_Last
}
for (EMyEnum i = E_First; i < E_Last; i = EMyEnum(i + 1))
{}
or if not successive, but with regular step (e.g. bit flags)
enum EAnimalCaps
{
E_First,
E_None = E_First,
E_CanFly = 0x1,
E_CanWalk = 0x2
E_CanSwim = 0x4,
E_Last
}
class MyAnimal
{
EAnimalCaps m_Caps;
}
class Frog
{
Frog() :
m_Caps(EAnimalCaps(E_CanWalk | E_CanSwim))
{}
}
for (EAnimalCaps= E_First; i < E_Last; i = EAnimalCaps(i << 1))
{}
The Connection for controluser as defined in your configuration failed, right after:
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'you_password';
You can achieve it but will required bit of work.
public enum Test : int { [StringValue("a")] Foo = 1, [StringValue("b")] Something = 2 }
Refer : Enum With String Values In C#
After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept
not being found, which apparently was not installed in /usr/include
with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile
file:
export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1
Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -
, gcc was looking in the old location for these headers (without the /c++/v1
), but not the new location, so adding that to CFLAGS fixed it.
I've experienced the same problem. The thing is that I forgot to start the apache and mysql in xampp... :S
It is very straight forward
HTML
<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>
jQuery
$(document).ready(function(){
$('.button').css( 'cursor', 'pointer' );
// for old IE browsers
$('.button').css( 'cursor', 'hand' );
});
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('ddd');
console.log(weekDayName);
Result: Wed
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
Result: Wednesday
A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.
node.exe --inspect www.js
Open chrome://inspect/#devices
in chrome and click Open dedicated DevTools for Node
Now every logged object is available in inspector like regular JS running in chrome.
There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.
export default
is used to export a single class, function or primitive from a script file.
The export can also be written as
export default function SafeString(string) {
this.string = string;
}
SafeString.prototype.toString = function() {
return "" + this.string;
};
This is used to import this function in another script file
Say in app.js, you can
import SafeString from './handlebars/safe-string';
As the name says, it's used to export functions, objects, classes or expressions from script files or modules
Utiliites.js
export function cube(x) {
return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;
This can be imported and used as
App.js
import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
Or
import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo); // 4.555806215962888
When export default is used, this is much simpler. Script files just exports one thing. cube.js
export default function cube(x) {
return x * x * x;
};
and used as App.js
import Cube from 'cube';
console.log(Cube(3)); // 27
The class you apply on the div can be used to as a reference point to style elements with that div, for example.
<div class="area1">
<table>
<tr>
<td class="item">Text Text Text</td>
<td class="item">Text Text Text</td>
</tr>
</table>
</div>
.area1 { border:1px solid black; }
.area1 td { color:red; } /* This will effect any TD within .area1 */
To be super semantic you should move the class onto the table.
<table class="area1">
<tr>
<td>Text Text Text</td>
<td>Text Text Text</td>
</tr>
</table>
If you really want a bruteforce algorithm, don't save any big list in the memory of your computer, unless you want a slow algorithm that crashes with a MemoryError.
You could try to use itertools.product like this :
from string import ascii_lowercase
from itertools import product
charset = ascii_lowercase # abcdefghijklmnopqrstuvwxyz
maxrange = 10
def solve_password(password, maxrange):
for i in range(maxrange+1):
for attempt in product(charset, repeat=i):
if ''.join(attempt) == password:
return ''.join(attempt)
solved = solve_password('solve', maxrange) # This worked for me in 2.51 sec
itertools.product(*iterables)
returns the cartesian products of the iterables you entered.
[i for i in product('bar', (42,))]
returns e.g. [('b', 42), ('a', 42), ('r', 42)]
The repeat
parameter allows you to make exactly what you asked :
[i for i in product('abc', repeat=2)]
Returns
[('a', 'a'),
('a', 'b'),
('a', 'c'),
('b', 'a'),
('b', 'b'),
('b', 'c'),
('c', 'a'),
('c', 'b'),
('c', 'c')]
Note:
You wanted a brute-force algorithm so I gave it to you. Now, it is a very long method when the password starts to get bigger because it grows exponentially (it took 62 sec to find the word 'solved').
Tools -> Options ->Environment -> General
Or use new Quick Launch to open Options
For more themes, download Microsoft Visual Studio 2012 Color Theme Editor for more themes including good old VS2010 theme.
Look at this video for a demo.
An additional option is to apply absolute positioning via styling, setting the hidden component in out-of-screen coordinates:
<TextInput
onFocus={this.showCancel()}
onChangeText={(text) => this.doSearch({input: text})}
style={this.state.hide ? {position: 'absolute', top: -200} : {}}
/>
Unlike in some of the previous suggestions, this would hide your component from view BUT will also render it (keep it in the DOM), thus making it truly invisible.
are you writing java code for android? in that case you should write maybe
if (90 >= angle && angle <= 180) {
updating the code to a nicer style (like some suggested) you would get:
if (angle <= 90 && angle <= 180) {
now you see that the second check is unnecessary or maybe you mixed up <
and >
signs in the first check and wanted actually to have
if (angle >= 90 && angle <= 180) {
There are three different concepts there:
is
- for example if(obj is int) {...}
TryParse()
ToString()
might give something that looks like a number, then call ToString()
and treat it as a stringIn both the first two cases, you'll probably have to handle separately each numeric type you want to support (double
/decimal
/int
) - each have different ranges and accuracy, for example.
You could also look at regex for a quick rough check.
I have wondered about this in the past and came to the conclusion that it was not actually a valid test case for my code. I don't think your application code can actually tell the difference between somebody declining notifications the first time or later disabling it from the iPhone notification settings. It is true that the user experience is different but that is hidden inside the call to registerForRemoteNotificationTypes.
Calling unregisterForRemoteNotifications does not completely remove the application from the notifications settings - though it does remove the contents of the settings for that application. So this still will not cause the dialog to be presented a second time to the user the next time the app runs (at least not on v3.1.3 that I am currently testing with). But as I say above you probably should not be worrying about that.
I recently wrote on this topic, though this post it old, I thought it will be helpful to someone who wants to know how to implement BaseAdapter.notifyDataSetChanged()
step by step and in a correct way.
Please follow How to correctly implement BaseAdapter.notifyDataSetChanged() in Android or the newer blog BaseAdapter.notifyDataSetChanged().
This does exactly what you are asking, checks the rows, and inserts a blank empty row at each change in column A:
sub AddBlankRows()
'
dim iRow as integer, iCol as integer
dim oRng as range
set oRng=range("a1")
irow=oRng.row
icol=oRng.column
do
'
if cells(irow+1, iCol)<>cells(irow,iCol) then
cells(irow+1,iCol).entirerow.insert shift:=xldown
irow=irow+2
else
irow=irow+1
end if
'
loop while not cells (irow,iCol).text=""
'
end sub
I hope that gets you started, let us know!
Philip
You can modify the Product Name
without changing your Project Name
(especially the directory).
Build Settings > search the keyword "product name" > update values
In my case with jquery slider with 2 handles only following way worked.
$('#Slider').slider('option',{values: [0.15, 0.6]});
This is the best one that I tried:
$(document).ready(function() {
if (location.hash) {
$("a[href='" + location.hash + "']").tab("show");
}
$(document.body).on("click", "a[data-toggle='tab']", function(event) {
location.hash = this.getAttribute("href");
});
});
$(window).on("popstate", function() {
var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
$("a[href='" + anchor + "']").tab("show");
});
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float
instead of int
. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.
As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.
Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.
You can do that by using "Narrowing or Explicit type conversion", double ? long ? int. I hope it will work.
double d = 100.04;
long l = (long)d; // Explicit type casting required
int i = (int)l; // Explicit type casting required
PS: It will give 0 as double has all the decimal values and nothing on the left side. In case of 0.58, it will narrow it down to 0. But for others it will do the magic.
Use nested dictionaries. Take a look:
INI File: example.ini
[Section]
Key = Value
Code:
class IniOpen:
def __init__(self, file):
self.parse = {}
self.file = file
self.open = open(file, "r")
self.f_read = self.open.read()
split_content = self.f_read.split("\n")
section = ""
pairs = ""
for i in range(len(split_content)):
if split_content[i].find("[") != -1:
section = split_content[i]
section = string_between(section, "[", "]") # define your own function
self.parse.update({section: {}})
elif split_content[i].find("[") == -1 and split_content[i].find("="):
pairs = split_content[i]
split_pairs = pairs.split("=")
key = split_pairs[0].trim()
value = split_pairs[1].trim()
self.parse[section].update({key: value})
def read(self, section, key):
try:
return self.parse[section][key]
except KeyError:
return "Sepcified Key Not Found!"
def write(self, section, key, value):
if self.parse.get(section) is None:
self.parse.update({section: {}})
elif self.parse.get(section) is not None:
if self.parse[section].get(key) is None:
self.parse[section].update({key: value})
elif self.parse[section].get(key) is not None:
return "Content Already Exists"
Apply code like so:
ini_file = IniOpen("example.ini")
print(ini_file.parse) # prints the entire nested dictionary
print(ini_file.read("Section", "Key") # >> Returns Value
ini_file.write("NewSection", "NewKey", "New Value"
This is work for my project, source https://gist.github.com/artem-zinnatullin/7749076
Create fonts directory inside Asset Folder and then copy your custom font to fonts directory, example I am using trebuchet.ttf;
Create a class TypefaceUtil.java;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
try {
final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
defaultFontTypefaceField.setAccessible(true);
defaultFontTypefaceField.set(null, customFontTypeface);
} catch (Exception e) {
}
}
}
Edit theme in styles.xml add below
<item name="android:typeface">serif</item>
Example in My styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:typeface">serif</item><!-- Add here -->
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowFullscreen">true</item>
</style>
</resources>
Finally, in Activity or Fragment onCreate call TypefaceUtil.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TypefaceUtil.overrideFont(getContext(), "SERIF", "fonts/trebuchet.ttf");
}
Connect to the Guest and find out the ip address:
ifconfig
example of result (ip address is 10.0.2.15):
eth0 Link encap:Ethernet HWaddr 08:00:27:AE:36:99
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
Go to Vbox instance window -> Menu -> Network adapters:
Go to host system and try it in browser:
http://127.0.0.1:8000
or your network ip address (find out on the host machine by running: ipconfig).
In this case port forwarding is not needed, the communication goes over the LAN back to the host.
On the host machine - find out your netw ip address:
ipconfig
example of result:
IP Address. . . . . . . . . . . . : 192.168.5.1
On the guest machine you can communicate directly with the host, e.g. check it with ping:
# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...
@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):
sudo ufw allow 8000
Yes. unless, there is an ambiguity.
The Content-Type in request header is really important, especially when you post the data from curl or any other tools.
Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.
I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:
StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = @PatientId and IdDrugService = 226)> 0)
THEN cast((S.UnitsOrdered) as varchar(50))
ELSE 'No Labs Available'
END
I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.
@Martijn your order of function calls is slightly off. Try this instead:
x=-3:0.1:3;
y = x.^3;
plot(x,y), hold on
plot([-3 3], [0 0], 'k:')
hold off
DECLARE @vchVAlue NVARCHAR(255) = 'SWP, Lettering Position 1: 4 ?, 2: 8 ?, 3: 16 ?, 4: , 5: , 6: , Voltage Selector, Solder, 6, Step switch, : w/o fuseholder '
WHILE PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))) > 0
BEGIN
SELECT @vchVAlue = STUFF(@vchVAlue,PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))),1,' ')
END
SELECT @vchVAlue
redirect 301 /contact.php /contact-us.php
There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally
When using in Maven, update artifact junit:junit from e.g. 4.8.2 to 4.11.
I'd use SimpleXMLElement.
<?php
$xml = new SimpleXMLElement('<xml/>');
for ($i = 1; $i <= 8; ++$i) {
$track = $xml->addChild('track');
$track->addChild('path', "song$i.mp3");
$track->addChild('title', "Track $i - Track Title");
}
Header('Content-type: text/xml');
print($xml->asXML());
For all smartphones and large screens use this format of media query
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
Google led me to this solution (base64_encode). Hope this helps!
The best practice would be to use traditionnal getters and setters, because of introspection or reflection. There is a way in PHP (exactly like in Java) to obtain the name of a method or of all methods. Such a thing would return "__get" in the first case and "getFirstField", "getSecondField" in the second (plus setters).
More on that: http://php.net/manual/en/book.reflection.php
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
With the header function. There is an example in the section on the first parameter it takes.
This is python regex, but it probably works in other languages that implement it, too.
I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:
\w{3,}
if just letters and digits:
[a-zA-Z0-9]{3,}
Python also has a regex method to return all matches from a string.
>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
<input name="user_name" type="text" >
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.
You can disable SSL certificate checking by adding one or more of these command line parameters:
-Dmaven.wagon.http.ssl.insecure=true
- enable use of relaxed SSL check for user generated certificates.-Dmaven.wagon.http.ssl.allowall=true
- enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.-Dmaven.wagon.http.ssl.ignore.validity.dates=true
- ignore issues with certificate dates.Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/
Here's the oneliner for an easy copy-and-paste:
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
Ajay Gautam suggested that you could also add the above to the ~/.mavenrc
file as not to have to specify it every time at command line:
$ cat ~/.mavenrc
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
I had a similar problem on OSX but tried to play around with double and single quotes. For your case, you could try something like this
$query = 'SELECT * FROM "sf_bands"'; // NOTE: double quotes on "sf_Bands"
php7.1 mongoDB:
$data = $collection->findOne([],['sort' => ['_id' => -1],'projection' => ['_id' => 1]]);
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
As pointed out in other answers, often what you really want the dominant color as opposed to the average color which tends to be brown. I wrote a script that gets the most common color and posted it on this gist
Random random = new Random();
int n = random.nextInt(69) + 32;
if (n > 96) {
n += 26;
}
char c = (char) n;
I guess it depends which punctuation you want to include, but this should generate a random character including all of the punctuation on this ASCII table. Basically, I've generated a random int from 32 - 96 or 123 - 126, which I have then casted to a char, which gives the ASCII equivalent of that number. Also, make sure youimport java.util.Random
The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised
You'll have to use a temp table/table variable outside of the dynamic SQL:
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)
INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')
select * FROM @siteId
Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY
<script>
$(document).ready(function(){
$(window).scroll(function() { // check if scroll event happened
if ($(document).scrollTop() > 50) { // check if user scrolled more than 50 from top of the browser window
$(".navbar-fixed-top").css("background-color", "#f8f8f8"); // if yes, then change the color of class "navbar-fixed-top" to white (#f8f8f8)
} else {
$(".navbar-fixed-top").css("background-color", "transparent"); // if not, change it back to transparent
}
});
});
</script>
Another solution, similar to Gerbus' solution, but this also works with relative font sizing.
ul {
letter-spacing: -1em; /* Effectively collapses white-space */
}
ul li {
display: inline;
letter-spacing: normal; /* Reset letter-spacing to normal value */
}
Change the Package Name
To rename your package name, all you have to do is go to your AndroidManifest.xml
file, put your mouse cursor in front of the part of the package name you want to change.
Right-Click > Refactor > Rename
In the new window press Rename package
Change name and press Refactor
…and press Do Refactor at the bottom.
Your package name usually is in format com.domain.appname, in this example we changed the appname part, but you can do the same steps for the domain too.
Done! You changed your package name!
size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.
When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, following program would definitely give the unexpected result:
// C program to demonstrate that size_t or
// any unsigned int type should be used
// carefully when used in a loop
#include<stdio.h>
int main()
{
const size_t N = 10;
int a[N];
// This is fine
for (size_t n = 0; n < N; ++n)
a[n] = n;
// But reverse cycles are tricky for unsigned
// types as can lead to infinite loop
for (size_t n = N-1; n >= 0; --n)
printf("%d ", a[n]);
}
Output
Infinite loop and then segmentation fault
I would do as below
rebase feature
git checkout -b feature2 origin/feature
git push -u origin feature2:feature2
Delete the old remote branch feature
git push -u origin feature:feature
Now the remote will have feature(rebased on latest master) and feature2(with old master head). This would allow you to compare later if you have done mistakes in reolving conflicts.
Use a double for the sum, otherwise you are doing an integer division and you won't get any decimals:
private double calculateAverage(List <Integer> marks) {
if (marks == null || marks.isEmpty()) {
return 0;
}
double sum = 0;
for (Integer mark : marks) {
sum += mark;
}
return sum / marks.size();
}
or using the Java 8 stream API:
return marks.stream().mapToInt(i -> i).average().orElse(0);
You can add a little white one with a Base64 Encoded GIF (online generator here):
url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==")
With Chrome, for instance, I use it to style the checkbox control:
INPUT[type=checkbox]:focus
{
outline:1px solid rgba(0,0,0,0.2);
}
INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
-webkit-appearance: button;
width: 17px;
height: 17px;
margin-top: 1px;
cursor:pointer;
}
INPUT[type=checkbox]:checked
{
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
If you just wanted it in an IMG tag, you would do the checkmark/tickmark as:
<img alt="" src="data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==" width="11" height="10">
I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.
The simplest solution is:
git checkout the name of the source branch and the paths to the specific files that we want to add to our current branch
git checkout sourceBranchName pathToFile
Simply check what is the connection, where it's coming from. You can see all this in:
SELECT * FROM pg_stat_activity WHERE datname = 'TARGET_DB';
Perhaps it is your connection?
For best performance, here is what I wrote :
(see execution plan)
DELETE FROM your_table
WHERE rowid IN
(select t1.rowid from your_table t1
LEFT OUTER JOIN (
SELECT MIN(rowid) as rowid, column1,column2, column3
FROM your_table
GROUP BY column1, column2, column3
) co1 ON (t1.rowid = co1.rowid)
WHERE co1.rowid IS NULL
);
The ones I can think of are
def foo(l: List[Option[_]]) = ...
case class A[K[_],T](a: K[T])
val _ = 5
List(1, 2, 3) foreach { _ => println("Hi") }
trait MySeq { _: Seq[_] => }
Some(5) match { case Some(_) => println("Yes") }
"abc" match { case s"a$_c" => }
C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }
import java.util._
import java.util.{ArrayList => _, _}
def bang_!(x: Int) = 5
def foo_=(x: Int) { ... }
List(1, 2, 3) map (_ + 2)
List(1, 2, 3) foreach println _
def toFunction(callByName: => Int): () => Int = callByName _
var x: String = _ // unloved syntax may be eliminated
There may be others I have forgotten!
Example showing why foo(_)
and foo _
are different:
This example comes from 0__:
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
In the first case, process _
represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A
that will give the type (_ => Unit) => ?
(Existential _
is not a type).
In the second case, process(_)
is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach
expects, and _ => Unit
is a type (whereas just plain _
isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Make a custom ImageView
that maintains its aspect ratio:
src/com/example/graphicstest/SquareImageView.java
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:
res/layout/grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.graphicstest.SquareImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="@android:color/white"
android:background="#55000000"/>
</FrameLayout>
Now make some sort of adapter for your GridView
:
src/com/example/graphicstest/MyAdapter.java
private final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mItems.add(new Item("Red", R.drawable.red));
mItems.add(new Item("Magenta", R.drawable.magenta));
mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
mItems.add(new Item("Gray", R.drawable.gray));
mItems.add(new Item("Green", R.drawable.green));
mItems.add(new Item("Cyan", R.drawable.cyan));
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Item getItem(int i) {
return mItems.get(i);
}
@Override
public long getItemId(int i) {
return mItems.get(i).drawableId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private static class Item {
public final String name;
public final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
Set that adapter to your GridView
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}
And enjoy the results:
Even though this is a year old question, I would like to say that using dict
will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be
import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict
Another Option that has worked well for me is using the synchronize module . Then remove the original directory using the file module.
Here is an example from the docs:
- synchronize:
src: /first/absolute/path
dest: /second/absolute/path
archive: yes
delegate_to: "{{ inventory_hostname }}"
If the return value is string and you need to search by Id you can use:
string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();
or using generic variable:
var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));
If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options
for your host or to put these lines in their virtual host configuration file.
Just in case you have pandas (import pandas as pd
) or are ok with using it:
test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)],
[random.gauss(4,2) for _ in range(400)]])
plt.hist(test.values.T)
plt.show()
As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:
for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i
one way to do this would be to use indexing with .loc
.
Example
In the absence of an example dataframe, I'll make one up here:
import numpy as np
import pandas as pd
df = pd.DataFrame({'c1': list('abcdefg')})
df.loc[5, 'c1'] = 'Value'
>>> df
c1
0 a
1 b
2 c
3 d
4 e
5 Value
6 g
Assuming you wanted to create a new column c2
, equivalent to c1
except where c1
is Value
, in which case, you would like to assign it to 10:
First, you could create a new column c2
, and set it to equivalent as c1
, using one of the following two lines (they essentially do the same thing):
df = df.assign(c2 = df['c1'])
# OR:
df['c2'] = df['c1']
Then, find all the indices where c1
is equal to 'Value'
using .loc
, and assign your desired value in c2
at those indices:
df.loc[df['c1'] == 'Value', 'c2'] = 10
And you end up with this:
>>> df
c1 c2
0 a a
1 b b
2 c c
3 d d
4 e e
5 Value 10
6 g g
If, as you suggested in your question, you would perhaps sometimes just want to replace the values in the column you already have, rather than create a new column, then just skip the column creation, and do the following:
df['c1'].loc[df['c1'] == 'Value'] = 10
# or:
df.loc[df['c1'] == 'Value', 'c1'] = 10
Giving you:
>>> df
c1
0 a
1 b
2 c
3 d
4 e
5 10
6 g
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
Already @Abubakkar Rangara answered easy way to handle your problem
Alternative is :
String[] result = null;
if(fieldName.endsWith(",")) {
String[] result = fieldName.split(",");
for(int i = 1; i < result.length - 1; i++) {
result[0] = result[0].concat(result[i]);
}
}
Class WebMvcConfigurerAdapter
is deprecated as of 5.0 WebMvcConfigurer
has default methods and can be implemented directly without the need for this adapter. For this case:
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
}
See also: Same-Site flag for session cookie
is there a tag for don't render HTML until you hit the closing tag?
No, there is not. In HTML proper, there’s no way short of escaping some characters:
&
as &
<
as <
(Incidentally, there is no need to escape >
but people often do it for reasons of symmetry.)
And of course you should surround the resulting, escaped HTML code within <pre><code>…</code></pre>
to (a) preserve whitespace and line breaks, and (b) mark it up as a code element.
All other solutions, such as wrapping your code into a <textarea>
or the (deprecated) <xmp>
element, will break.1
XHTML that is declared to the browser as XML (via the HTTP Content-Type
header! — merely setting a DOCTYPE
is not enough) could alternatively use a CDATA section:
<![CDATA[Your <code> here]]>
But this only works in XML, not in HTML, and even this isn’t a foolproof solution, since the code mustn’t contain the closing delimiter ]]>
. So even in XML the simplest, most robust solution is via escaping.
1 Case in point:
textarea {border: none; width: 100%;}
_x000D_
<textarea readonly="readonly">
<p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>
<xmp>
Computer <xmp>says</xmp> <span>no.</span>
</xmp>
_x000D_
Since Entity Framework 5.0 you can use following code in order to solve your issue:
public abstract class YourContext : DbContext
{
public YourContext()
{
(this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
}
}
This should solve your problems as Entity Framerwork will use 'C# like' null comparison.
The other answers sufficiently answer the question, but I thought I would share some additional information. Others describe the "DESCRIBE table" syntax in order to get the table information. If you want to get the information in the same format, but without using DESCRIBE, you could do:
SELECT column_name as COLUMN_NAME, nullable || ' ' as BE_NULL,
SUBSTR(data_type || '(' || data_length || ')', 0, 10) as TYPE
FROM all_tab_columns WHERE table_name = 'TABLENAME';
Probably doesn't matter much, but I wrote it up earlier and it seems to fit.
With JUnit 5 I was able to solve this using the @RepeatedTest annotation:
@RepeatedTest(10)
public void testMyCode() {
//your test code goes here
}
Note that @Test
annotation shouldn't be used along with @RepeatedTest
.
you can replace the 2 with your desired number
select * from ( select distinct (sal),ROW_NUMBER() OVER (order by sal desc) rn from emp ) where rn=2
I've had trouble with git revert in the past (mainly because I'm not quite certain how it works.) I've had trouble reverting because of merge problems..
My simple solution is this.
Step 1.
git clone <your repos URL> .
your project in another folder, then:
Step 2.
git reset --hard <the commit you wanna go to>
then Step 3.
in your latest (and main) project dir (the one that has the problematic last commit) paste the files of step 2
Step 4.
git commit -m "Fixing the previous messy commit"
Step 5.
Enjoy
For completeness these are the cmap choices I encountered so far:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
One way to obtain the headers from JavaScript is using the WebRequest API, which allows us to access the different events that originate from http or websockets, the life cycle that follows is this: WebRequest Lifecycle
So in order to access the headers of a page it would be like this:
browser.webRequest.onHeadersReceived.addListener(
(headersDetails)=> {
console.log("Request: " + headersDetails);
},
{urls: ["*://hostName/*"]}
);`
The issue is that in order to use this API, it must be executed from the browser, that is, the browser object refers to the browser itself (tabs, icons, configuration), and the browser does have access to all the Request and Reponse of any page , so you will have to ask the user for permissions to be able to do this (The permissions will have to be declared in the manifest for the browser to execute them)
And also being part of the browser you lose control over the pages, that is, you can no longer manipulate the DOM, (not directly) so to control the DOM again it would be done as follows:
browser.webRequest.onHeadersReceived.addListener(
browser.tabs.executeScript({
code: 'console.log("Headers success")',
});
});
or if you want to run a lot of code
browser.webRequest.onHeadersReceived.addListener(
browser.tabs.executeScript({
file: './headersReveiced.js',
});
});
Also by having control over the browser we can inject CSS and images
Documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived
I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."
Calling a function/class instance in Python means invoking the __call__
method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__
method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".
As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...)
is a shorthand for x.__call__(arg1, arg2, ...)
".
Thus whenever you define a function with the shorthand def funcname(parameters):
you are really just creating an object with a method __call__
and the shorthand for __call__
is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (url.equals("your url")) {
Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
startActivity(intent);
}
}
Best way to do this is to add a data attribute to the field (textbox) where you want to avoid the cut,copy and paste.
Just create a method for the same which is as follows :-
function ignorePaste() {
$("[data-ignorepaste]").bind("cut copy paste", function (e) {
e.preventDefault(); //prevent the default behaviour
});
};
Then once when you add the above code simply add the data attribute to the field where you want to ignore cut copy paste. in our case your add a data attribute to confirm email text box as below :-
Confirm Email: <input type="textbox" id= "confirmEmail" data-ignorepaste=""/>
Call the method ignorePaste()
So in this way you will be able to use this throughout the application, all you need to do is just add the data attribute where you want to ignore cut copy paste
If you use:
import Math
then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.
If you want to import a module's functions without having to prefix them, you must explicitly name them, like:
from Math import Calculate, Add, Subtract
Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:
from Math import *
However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.
If you prefer an Integer[]
instead array of an int[]
array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
I completely uninstalled brew and started again, only to find the same problem again.
Brew appears to work by symlinking the required binaries into your system where other installation methods would typically copy the files.
I found an existing set of node libraries here:
/usr/local/include/node
After some head scratching I remembered installing node at the date against this old version and it hadn't been via brew.
I manually deleted this entire folder and successfully linked npm.
This would explain why using brew uninstall or even uninstall brew itself had no effect.
The highest ranked answer puts this very simply, but I thought I'd add my observations about why it's necessary.
I'm guessing a bunch of issues with other brew packages might be caused by old non-brew instances of packages being in the way.
You will need to add external Repository to your pom, since this is using Mulsoft-Release
repository not Maven Central
<project>
...
<repositories>
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
</repositories>
...
</project>
I’m lazy and my memory is bad, so I decided to create easycolab which is easier to memorize and type:
import easycolab as ec
ec.mount()
Make sure to install it first: !pip install easycolab
The mount()
method basically implement this:
from google.colab import drive
drive.mount(‘/content/drive’)
cd ‘/content/gdrive/My Drive/’
For MySQL (5.6+) you can do this:
SELECT ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000)
Which will return (e.g.):
1420998416685 --milliseconds
This answer didn't seem to exist already.
directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]
Calendar.get
takes as argument one of the standard Calendar fields, like YEAR
or MONTH
not a month name.
Calendar.JANUARY
is 0, which is also the value of Calendar.ERA
, so Calendar.getInstance().get(0)
will return the era, in this case Calendar.AD
, which is 1.
For the first part of your question, note that, as is wildly documented, months start at 0, so 10 is actually November.
What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.
You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.
Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).
Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org
Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.
In summary then: it all depends on your region.
Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.
Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.
maybe
string = document.location.href;
arrayOfStrings = string.toString().split('/');
assuming you want the current url
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
<a href="deletelink" onclick="return confirm('Are you sure?')">Delete</a>
In a function:
<a href="deletelink" onclick="return checkDelete()">Delete</a>
and then put this in <head>
:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
<a href="deletelink" class="delete">Delete</a>
And put this in <head>
:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>
Try this something like this:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
import base64
from PIL import Image
import io
image = base64.b64decode(str('stringdata'))
fileName = 'test.jpeg'
imagePath = ('D:\\base64toImage\\'+"test.jpeg")
img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
This behavior appears to have changed in Jelly Bean. The paddingLeft trick adds additional padding, making the text look too far right. Any one else notice that?
Answers provided previously have problems with paths containing dots. Some examples:
/xyz.dir/file.ext
./file.ext
/a.b.c/x.ddd.txt
I prefer to use |sed -e 's/\.[^./]*$//'
. For example:
$ echo "/xyz.dir/file.ext" | sed -e 's/\.[^./]*$//'
/xyz.dir/file
$ echo "./file.ext" | sed -e 's/\.[^./]*$//'
./file
$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^./]*$//'
/a.b.c/x.ddd
Note: If you want to remove multiple extensions (as in the last example), use |sed -e 's/\.[^/]*$//'
:
$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^/]*$//'
/a.b.c/x
However, this method will fail in "dot-files" with no extension:
$ echo "/a.b.c/.profile" | sed -e 's/\.[^./]*$//'
/a.b.c/
To cover also such cases, you can use:
$ echo "/a.b.c/.profile" | sed -re 's/(^.*[^/])\.[^./]*$/\1/'
/a.b.c/.profile
I saw a good article which helped me out at the last moment .. I was trying to insert few rows in a table which had identity column but did it wrongly and have to delete back. Once I deleted the rows then my identity column got changed . I was trying to find an way to update the column which was inserted but - no luck. So, while searching on google found a link ..
I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.
function scriptFromFile(file) {
var script = document.createElement("script");
script.src = chrome.extension.getURL(file);
return script;
}
function scriptFromSource(source) {
var script = document.createElement("script");
script.textContent = source;
return script;
}
function inject(scripts) {
if (scripts.length === 0)
return;
var otherScripts = scripts.slice(1);
var script = scripts[0];
var onload = function() {
script.parentNode.removeChild(script);
inject(otherScripts);
};
if (script.src != "") {
script.onload = onload;
document.head.appendChild(script);
} else {
document.head.appendChild(script);
onload();
}
}
The example of usage would be:
var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");
inject([
scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
scriptFromFile("EqEditor/eq_editor-lite-17.js"),
scriptFromFile("EqEditor/eq_config.js"),
scriptFromFile("highlight/highlight.pack.js"),
scriptFromFile("injected.js")
]);
Actually, I'm kinda new to JS, so feel free to ping me to the better ways.
Here is what I would do:
find /path/to/dir -type f -iname "*filename*" -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'
this will look for all files containing filename
in the file's name under the /path/to/dir
, than for every file found, search for the line with searchstring
and replace old
with new
.
Though if you want to omit looking for a specific file with a filename
string in the file's name, than simply do:
find /path/to/dir -type f -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'
This will do the same thing above, but to all files found under /path/to/dir
.
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
I think we can answer it much more succinctly. I answered a related question, and copying my answer from there
But first, an NP-hard problem is a problem for which we cannot prove that a polynomial time solution exists. NP-hardness of some "problem-P" is usually proven by converting an already proven NP-hard problem to the "problem-P" in polynomial time.
To answer the rest of question, you first need to understand which NP-hard problems are also NP-complete. If an NP-hard problem belongs to set NP, then it is NP-complete. To belong to set NP, a problem needs to be
(i) a decision problem,
(ii) the number of solutions to the problem should be finite and each solution should be of polynomial length, and
(iii) given a polynomial length solution, we should be able to say whether the answer to the problem is yes/noNow, it is easy to see that there could be many NP-hard problems that do not belong to set NP and are harder to solve. As an intuitive example, the optimization-version of traveling salesman where we need to find an actual schedule is harder than the decision-version of traveling salesman where we just need to determine whether a schedule with length <= k exists or not.
$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));