Change your positioning a bit:
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
position:relative;
}
.tag {
float: left;
position: absolute;
left: 0px;
top: 0px;
background-color: green;
}
You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.
You should use LoadXml method, not Load:
xmlDoc.LoadXml(myXML);
Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
}
Actually you should define your styles in res/values/styles.xml
. I guess now you've got the following configuration:
<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>
so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black
or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black"
. You must be lacking android namespace before style tag.
You can read more about styles and themes here.
In general the less number of calls to the database the better (meaning faster, more efficient), so try to code the inserts in such a way that it minimizes database accesses. Remember, unless your using a connection pool, each databse access has to create a connection, execute the sql, and then tear down the connection. Quite a bit of overhead!
After reading Material Table not updating post data update #11638 Bug Report I found the best (read, the easiest solution) was as suggested by the final commentor 'shhdharmen' with a suggestion to use an EventEmitter.
This involves a few simple changes to the generated datasource class
ie) add a new private variable to your datasource class
import { EventEmitter } from '@angular/core';
...
private tableDataUpdated = new EventEmitter<any>();
and where I push new data to the internal array (this.data), I emit an event.
public addRow(row:myRowInterface) {
this.data.push(row);
this.tableDataUpdated.emit();
}
and finally, change the 'dataMutation' array in the 'connect' method - as follows
const dataMutations = [
this.tableDataUpdated,
this.paginator.page,
this.sort.sortChange
];
Wouldn't it just be a case of:
ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
// Fill in nodeList here...
outer.add(nodeList);
Repeat as necesary.
This should return you a list in the format you specified.
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
This works for me perfectly!
you can also use this code in your style.xml file so you don't need to write anything else in your activity.java
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- 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:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>
<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
Here is a little utility class that I created:
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Convenience utility to create a FilenameFilter, based on a list of extensions
*/
public class FileExtensionFilter implements FilenameFilter {
private Set<String> exts = new HashSet<String>();
/**
* @param extensions
* a list of allowed extensions, without the dot, e.g.
* <code>"xml","html","rss"</code>
*/
public FileExtensionFilter(String... extensions) {
for (String ext : extensions) {
exts.add("." + ext.toLowerCase().trim());
}
}
public boolean accept(File dir, String name) {
final Iterator<String> extList = exts.iterator();
while (extList.hasNext()) {
if (name.toLowerCase().endsWith(extList.next())) {
return true;
}
}
return false;
}
}
Usage:
String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));
Ensure to call this.dialog.show . (Activity)
Use following code
List data = getJdbcTemplate().queryForList(query,String.class)
If you have to search an ASCII string in another ASCII string, such as a URL, you will find my solution to be better. I've tested icza's method and mine for the speed and here are the results:
The code:
public static String lowerCaseAscii(String s) {
if (s == null)
return null;
int len = s.length();
char[] buf = new char[len];
s.getChars(0, len, buf, 0);
for (int i=0; i<len; i++) {
if (buf[i] >= 'A' && buf[i] <= 'Z')
buf[i] += 0x20;
}
return new String(buf);
}
public static boolean containsIgnoreCaseAscii(String str, String searchStr) {
return StringUtils.contains(lowerCaseAscii(str), lowerCaseAscii(searchStr));
}
I have formatted the nice solution provided by JeremyP above into a more generic reusable function below:
///Return an ARRAY containing the exploded chunk of strings
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}
You can do something like
MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
<div class="col-md-4 text-right">
<a ng-class="campaign_range === 'thismonth' ? 'btn btn-blue' : 'btn btn-link'" href="#" ng-click='change_range("thismonth")'>This Month</a>
<a ng-class="campaign_range === 'all' ? 'btn btn-blue' : 'btn btn-link'" href="#" ng-click='change_range("all")'>All Time</a>
</div>
$scope.campaign_range = "all";
$scope.change_range = function(range) {
if (range === "all")
{
$scope.campaign_range = "all"
}
else
{
$scope.campaign_range = "thismonth"
}
};
This is because you're using getActivity()
inside an inner class. Try using:
SherlockFragmentActivity.this.getActivity()
instead, though there's really no need for the getActivity()
part. In your case,
SherlockFragmentActivity .this
should suffice.
Error: ng:areq Bad Argument has gotten me a couple times because I close the square bracket too soon. In the BAD example below it is closed incorrectly after '$state' when it should actually go before the final parenthese.
BAD:
sampleApp.controller('sampleApp', ['$scope', '$state'], function($scope, $state){
});
GOOD:
sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){
}]);
If you're giving the same seed, that's normal. That's an important feature allowing tests.
Check this to understand pseudo random generation and seeds:
A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.
If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random
instance should of course be kept outside of your method.
Your code should probably be like this:
private Random generator = new Random();
double randomGenerator() {
return generator.nextDouble()*0.5;
}
Assuming:
master
master
yet git log --format="%ae %an" master..<HERE_COMES_THE_BRANCH_NAME> | tail -1
If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!
Do
<table>
<caption style="gimme some style!"><!-- Title of table --></caption>
<thead><!-- ... --></thead>
<tbody><!-- ... --></tbody>
</table>
Don't
<div>
<div style="float: left;/* extra styling /*"><!-- Title of table --></div>
<table>
<thead><!-- ... --></thead>
<tbody><!-- ... --></tbody>
</table>
<div style="clear: both"></div>
</div>
Hive Partitioning:
Partition divides large amount of data into multiple slices based on value of a table column(s).
Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.
Pros:
Cons:
Hive Bucketing:
Bucketing decomposes data into more manageable or equal parts.
With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.
Pros
Cons
Just Simply use
use css code: text-transform: uppercase;
ContextLoaderListener
is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener
, just a basic minimum web.xml
with DispatcherServlet
.
Here is what it would look like:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5">
<display-name>Some Minimal Webapp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
Create a file called dispatcher-servlet.xml
and store it under WEB-INF
. Since we mentioned index.jsp
in welcome list, add this file under WEB-INF
.
dispatcher-servlet.xml
In the dispatcher-servlet.xml
define your beans:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="bean1">
...
</bean>
<bean id="bean2">
...
</bean>
<context:component-scan base-package="com.example" />
<!-- Import your other configuration files too -->
<import resource="other-configs.xml"/>
<import resource="some-other-config.xml"/>
<!-- View Resolver -->
<bean
id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property
name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
calling import setuptools
will monkey patch distutils to force compatibility with Visual Studio. Calling vcvars32.bat
manually will setup the virtual environment and prevent other common errors the compiler will throw. For VS 2017 the file is located at
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"
Here is the setup script I use to quickly compile .pyx files to .pyd: (Note: it uses the 3rd party module send2trash
# cython_setup.py
import sys, os, time, platform, subprocess
from setuptools import setup, find_packages
from Cython.Build import cythonize
from traceback import format_exc
# USAGE:
#
# from cython_setup import run
# run(pyx_path)
# vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"
# NOTE: to use visual studio 2017 you must have setuptools version 34+
vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars32.bat"
def _build_ext():
try:
pyx_path = sys.argv.pop(-1)
pyx_path = os.path.abspath(pyx_path)
if not os.path.exists(pyx_path):
raise FileNotFoundError(f"{pyx_path} does not exist")
project_name = sys.argv.pop(-1)
os.chdir(os.path.abspath(os.path.dirname(pyx_path)))
print("cwd: %s" % os.getcwd())
print(os.path.abspath("build"))
setup(
name=project_name,
# cmdclass = {'build_ext': build_ext},
packages=find_packages(),
# ext_modules=cythonize(extensions)
ext_modules=cythonize(pyx_path,
compiler_directives={'language_level': 3, 'infer_types': True, 'binding': False},
annotate=True),
# include_dirs = [numpy.get_include()]
build_dir=os.path.abspath("build")
)
except:
input(format_exc())
def retry(func):
def wrapper(*args, **kw):
tries = 0
while True:
try:
return func(*args, **kw)
except Exception:
tries += 1
if tries > 4:
raise
time.sleep(0.4)
return wrapper
@retry
def cleanup(pyx_path):
from send2trash import send2trash
c_file = os.path.splitext(pyx_path)[0] + ".c"
if os.path.exists(c_file):
os.remove(c_file)
if os.path.exists("build"):
send2trash("build")
def move_pyd_files(pyx_path):
pyx_dir = os.path.dirname(pyx_path)
build_dir = os.path.join(pyx_dir, "build")
if not os.path.exists(build_dir):
raise RuntimeError(f"build_dir {build_dir} did not exist....")
found_pyd = False
for top, dirs, nondirs in os.walk(build_dir):
for name in nondirs:
if name.lower().endswith(".pyd") or name.lower().endswith(".so"):
found_pyd = True
old_path = os.path.join(top, name)
new_path = os.path.join(pyx_dir, name)
if os.path.exists(new_path):
print(f"removing {new_path}")
os.remove(new_path)
print(f"file created at {new_path}")
os.rename(old_path, new_path)
if not found_pyd:
raise RuntimeError("Never found .pyd file to move")
def run(pyx_path):
"""
:param pyx_path:
:type pyx_path:
:return: this function creates the batch file, which in turn calls this module, which calls cythonize, once done
the batch script deletes itself... I'm sure theres a less convoluted way of doing this, but it works
:rtype:
"""
try:
project_name = os.path.splitext(os.path.basename(pyx_path))[0]
run_script(project_name, os.path.abspath(pyx_path))
except:
input(format_exc())
def run_script(project_name, pyx_path):
dirname = os.path.dirname(pyx_path)
# ------------------------------
os.chdir(dirname)
if os.path.exists(vcvars):
# raise RuntimeError(
# f"Could not find vcvars32.bat at {vcvars}\nis Visual Studio Installed?\nIs setuptools version > 34?")
subprocess.check_call(f'call "{vcvars}"', shell=True)
cmd = "python" if platform.system() == "Windows" else "python3"
subprocess.check_call(f'{cmd} "{__file__}" build_ext "{project_name}" "{pyx_path}"', shell=True)
move_pyd_files(pyx_path)
cleanup(pyx_path)
if len(sys.argv) > 2:
_build_ext()
Using the autofocus
attribute works well with text input and checkboxes.
<input type="text" name="foo" value="boo" autofocus="autofocus"> FooBoo
<input type="checkbox" name="foo" value="boo" autofocus="autofocus"> FooBoo
In Opera 9.62, Mozilla 3.0.4, Safari 3.2 (for Windows) it helps, if you put some text or at least a whitespace within the same line as the input field.
<div style="line-height: 60px; height: 60px; border: 1px solid black;">
<input type="text" value="foo" />
</div>
(imagine an   after the input-statement)
IE 7 ignores every CSS hack I tried. I would recommend using padding for IE only. Should make it easier for you to position it correctly if it only has to work within one specific browser.
.widget-HomePageSlider .slider-loader-hide {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 10000;
background: white;
}
I had a lot of trouble with this too. Couldn't get it working using the case examples above, but this does the job for me:
Replace(rtrim(ltrim(ISNULL(Flat_no, '') +
' ' + ISNULL(House_no, '') +
' ' + ISNULL(Street, '') +
' ' + ISNULL(Town, '') +
' ' + ISNULL(City, ''))),' ',' ')
Replace corrects the double spaces caused by concatenating single spaces with nothing between them. r/ltrim gets rid of any spaces at the ends.
hey i know it is so late for this answer but add sort_keys and assign false to it as follows :
json.dumps({'****': ***},sort_keys=False)
this worked for me
This is less for @easwee and more for others that might have the same question:
If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.
With the current, final standard, you would be done with
.container {
display: flex;
}
.container div {
flex: 1;
}
.column_center {
order: 2;
}
That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into
.container {
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.container div {
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.column_center {
-webkit-box-ordinal-group: 2; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-ordinal-group: 2; /* OLD - Firefox 19- */
-ms-flex-order: 2; /* TWEENER - IE 10 */
-webkit-order: 2; /* NEW - Chrome */
order: 2; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New
One solution is to put them inside <center>
, like this:
<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>
I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/
just a moment ago, i came across with the same issue. and i resolve it in the following manner.
Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);
with reference to the this
For correct work your shape should be with selector and item tags
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#ffffff" />
<stroke android:width="1dp"
android:color="@color/shape_border_active"/>
</shape>
</item>
</selector>
private func setupView() {
view.backgroundColor = .white
navigationController?.setNavigationBarHidden(true, animated: false)
}
I know this is an old thread but I have tried numerous things and fixed my issue using the following means..
I'm developing a cross platform app on Windows but to be used on Linux and Windows servers.
A MySQL database called "jtm" installed on both systems. For some reason, in my code I had the database name as "JTM". On Windows it worked fine, in fact on several Windows systems it flew along.
On Ubuntu I got the error above time and time again. I tested it out with the correct case in the code "jtm" and it works a treat.
Linux is obviously a lot less forgiving about case sensitivity (rightly so), whereas Windows makes allowances.
I feel a bit daft now but check everything. The error message is not the best but it does seem fixable if you persevere and get things right.
First of all this code snippet
char *addr=NULL;
strcpy(addr,retstring().c_str());
is invalid because you did not allocate memory where you are going to copy retstring().c_str().
As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.
In case someone is using swagger:
Change the Scheme to HTTP
or HTTPS
, depend on needs, prior to hit the execute.
Postman:
Change the URL Path to http://
or https://
in the url address
In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.
[Edit:] It looks like std::remquo doesn't really return the quotient after all.
Just provide the env values on command line
USER_ID='abc' USER_KEY='def' node app.js
Use Arrays.asList()
to wrap the array in a List<String>
, which does have a contains()
method:
Arrays.asList(dan).contains(say.getText())
You inherit class attributes, not class constructors .This is how it goes :
If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .
if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.
if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .
if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .
this way you are sure that the inherited class attributes are always instanciated .
There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it's not too bad.
Select Id,
Case When Col1 < Col2 And Col1 < Col3 Then Col1
When Col2 < Col1 And Col2 < Col3 Then Col2
Else Col3
End As TheMin
From YourTableNameHere
I used jruby-1.7.4 to compile my ruby code.
require 'roman-numerals.rb'
is the code which threw the below error.
LoadError: no such file to load -- roman-numerals
require at org/jruby/RubyKernel.java:1054
require at /Users/amanoharan/.rvm/rubies/jruby-1.7.4/lib/ruby/shared/rubygems/custom_require.rb:36
(root) at /Users/amanoharan/Documents/Aptana Studio 3 Workspace/RubyApplication/RubyApplication1/Ruby2.rb:2
I removed rb from require and gave
require 'roman-numerals'
It worked fine.
the code provided didn't work for me. I found another way to Map :
MapElements :
package com.cellfish.mediadb.rest.lucene;
import javax.xml.bind.annotation.XmlElement;
class MapElements
{
@XmlElement public String key;
@XmlElement public Integer value;
private MapElements() {} //Required by JAXB
public MapElements(String key, Integer value)
{
this.key = key;
this.value = value;
}
}
MapAdapter :
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.adapters.XmlAdapter;
class MapAdapter extends XmlAdapter<MapElements[], Map<String, Integer>> {
public MapElements[] marshal(Map<String, Integer> arg0) throws Exception {
MapElements[] mapElements = new MapElements[arg0.size()];
int i = 0;
for (Map.Entry<String, Integer> entry : arg0.entrySet())
mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
return mapElements;
}
public Map<String, Integer> unmarshal(MapElements[] arg0) throws Exception {
Map<String, Integer> r = new HashMap<String, Integer>();
for (MapElements mapelement : arg0)
r.put(mapelement.key, mapelement.value);
return r;
}
}
The rootElement :
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
public class Root {
private Map<String, Integer> mapProperty;
public Root() {
mapProperty = new HashMap<String, Integer>();
}
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, Integer> getMapProperty() {
return mapProperty;
}
public void setMapProperty(Map<String, Integer> map) {
this.mapProperty = map;
}
}
I found the code in this website : http://www.developpez.net/forums/d972324/java/general-java/xml/hashmap-jaxb/
You can generate a noise array, and add it to your signal
import numpy as np
noise = np.random.normal(0,1,100)
# 0 is the mean of the normal distribution you are choosing from
# 1 is the standard deviation of the normal distribution
# 100 is the number of elements you get in array noise
Details: Objective-C project with Swift 3 code in Xcode 8.1
Tasks:
ObjcClass.h
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, ObjcEnum) {
ObjcEnumValue1,
ObjcEnumValue2,
ObjcEnumValue3
};
@interface ObjcClass : NSObject
+ (void) PrintEnumValues;
@end
ObjcClass.m
#import "ObjcClass.h"
#import "SwiftCode.h"
@implementation ObjcClass
+ (void) PrintEnumValues {
[self PrintEnumValue:SwiftEnumValue1];
[self PrintEnumValue:SwiftEnumValue2];
[self PrintEnumValue:SwiftEnumValue3];
}
+ (void) PrintEnumValue:(SwiftEnum) value {
switch (value) {
case SwiftEnumValue1:
NSLog(@"-- SwiftEnum: SwiftEnumValue1");
break;
case SwiftEnumValue2:
case SwiftEnumValue3:
NSLog(@"-- SwiftEnum: long value = %ld", (long)value);
break;
}
}
@end
In my sample I use SwiftCode.h to detect Swift code in Objective-C. This file generate automatically (I did not create a physical copy of this header file in a project), and you can only set name of this file:
If the compiler can not find your header file Swift code, try to compile the project.
import Foundation
@objc
enum SwiftEnum: Int {
case Value1, Value2, Value3
}
@objc
class SwiftClass: NSObject {
class func PrintEnumValues() {
PrintEnumValue(.Value1)
PrintEnumValue(.Value2)
PrintEnumValue(.Value3)
}
class func PrintEnumValue(value: ObjcEnum) {
switch value {
case .Value1, .Value2:
NSLog("-- ObjcEnum: int value = \(value.rawValue)")
case .Value3:
NSLog("-- ObjcEnum: Value3")
break
}
}
}
You need to create bridging header file. When you add Swift file in Objective-C project, or Objective-C file in swift project Xcode will suggest you to create bridging header.
You can change bridging header file name here:
Bridging-Header.h
#import "ObjcClass.h"
#import "SwiftCode.h"
...
[ObjcClass PrintEnumValues];
[SwiftClass PrintEnumValues];
[SwiftClass PrintEnumValue:ObjcEnumValue3];
Full integration steps Objective-c and Swift described above. Now I will write some other code examples.
Swift class
import Foundation
@objc
class SwiftClass:NSObject {
private var _stringValue: String
var stringValue: String {
get {
print("SwiftClass get stringValue")
return _stringValue
}
set {
print("SwiftClass set stringValue = \(newValue)")
_stringValue = newValue
}
}
init (stringValue: String) {
print("SwiftClass init(String)")
_stringValue = stringValue
}
func printValue() {
print("SwiftClass printValue()")
print("stringValue = \(_stringValue)")
}
}
Objective-C code (calling code)
SwiftClass *obj = [[SwiftClass alloc] initWithStringValue: @"Hello World!"];
[obj printValue];
NSString * str = obj.stringValue;
obj.stringValue = @"HeLLo wOrLd!!!";
Result
Objective-C class (ObjcClass.h)
#import <Foundation/Foundation.h>
@interface ObjcClass : NSObject
@property NSString* stringValue;
- (instancetype) initWithStringValue:(NSString*)stringValue;
- (void) printValue;
@end
ObjcClass.m
#import "ObjcClass.h"
@interface ObjcClass()
@property NSString* strValue;
@end
@implementation ObjcClass
- (instancetype) initWithStringValue:(NSString*)stringValue {
NSLog(@"ObjcClass initWithStringValue");
_strValue = stringValue;
return self;
}
- (void) printValue {
NSLog(@"ObjcClass printValue");
NSLog(@"stringValue = %@", _strValue);
}
- (NSString*) stringValue {
NSLog(@"ObjcClass get stringValue");
return _strValue;
}
- (void) setStringValue:(NSString*)newValue {
NSLog(@"ObjcClass set stringValue = %@", newValue);
_strValue = newValue;
}
@end
Swift code (calling code)
if let obj = ObjcClass(stringValue: "Hello World!") {
obj.printValue()
let str = obj.stringValue;
obj.stringValue = "HeLLo wOrLd!!!";
}
Result
Swift extension
extension UIView {
static func swiftExtensionFunc() {
NSLog("UIView swiftExtensionFunc")
}
}
Objective-C code (calling code)
[UIView swiftExtensionFunc];
Objective-C extension (UIViewExtension.h)
#import <UIKit/UIKit.h>
@interface UIView (ObjcAdditions)
+ (void)objcExtensionFunc;
@end
UIViewExtension.m
@implementation UIView (ObjcAdditions)
+ (void)objcExtensionFunc {
NSLog(@"UIView objcExtensionFunc");
}
@end
Swift code (calling code)
UIView.objcExtensionFunc()
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
Something like:
library(dplyr)
df <- data.frame(id=c(1,1,1,2,2,2,3,3,3),
stopId=c("a","b","c","a","b","c","a","b","c"),
stopSequence=c(1,2,3,3,1,4,3,1,2))
first_last <- function(x) {
bind_rows(slice(x, 1), slice(x, n()))
}
df %>%
group_by(id) %>%
arrange(stopSequence) %>%
do(first_last(.)) %>%
ungroup
## Source: local data frame [6 x 3]
##
## id stopId stopSequence
## 1 1 a 1
## 2 1 c 3
## 3 2 b 1
## 4 2 c 4
## 5 3 b 1
## 6 3 a 3
With do
you can pretty much perform any number of operations on the group but @jeremycg's answer is way more appropriate for just this task.
Note that to call First
here is actually to call a Linq extension of IEnumerable, which is implemented by Dictionary<TKey,TValue>
. But for a Dictionary, "first" doesn't have a defined meaning. According to this answer, the last item added ends up being the "First" (in other words, it behaves like a Stack), but that is implementation specific, it's not the guaranteed behavior. In other words, to assume you're going to get any defined item by calling First would be to beg for trouble -- using it should be treated as akin to getting a random item from the Dictionary, as noted by Bobson below. However, sometimes this is useful, as you just need any item from the Dictionary.
Just use the Linq First()
:
var first = like.First();
string key = first.Key;
Dictionary<string,string> val = first.Value;
Note that using First
on a dictionary gives you a KeyValuePair
, in this case KeyValuePair<string, Dictionary<string,string>>
.
Note also that you could derive a specific meaning from the use of First
by combining it with the Linq OrderBy
:
var first = like.OrderBy(kvp => kvp.Key).First();
>>> x = 'lipsum'
>>> x.replace(x[:3], '')
'sum'
Originally we used no-cache many years ago and did run into some problems with stale content with certain browsers... Don't remember the specifics unfortunately.
We had since settled on JUST the use of no-store. Have never looked back or had a single issue with stale content by any browser or intermediaries since.
This space is certainly dominated by reality of implementations vs what happens to have been written in various RFCs. Many proxies in particular tend to think they do a better job of "improving performance" by replacing the policy they are supposed to be following with their own.
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
I just ran into this problem today. It turned out that a bug on the server (null pointer exception) was causing it to fail in creating a response, yet it still generated an HTTP status code of 200. Because of the 200 status code, Chrome expected a valid response. The first thing that Chrome did was to look for the 'Access-Control-Allow-Origin' header, which it did not find. Chrome then cancelled the request, and Angular gave me an error. The bug during processing the POST request is the reason why the OPTIONS would succeed, but the POST would fail.
In short, if you see this error, it may be that your server didn't return any headers at all in response to the POST request.
The most fully-featured library to handle this as of 2019 seems to be natural-orderby.
const { orderBy } = require('natural-orderby')
const unordered = [
'123asd',
'19asd',
'12345asd',
'asd123',
'asd12'
]
const ordered = orderBy(unordered)
// [ '19asd',
// '123asd',
// '12345asd',
// 'asd12',
// 'asd123' ]
It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.
Surprisingly, it's also only 1.6kB when gzipped.
The argument order seems to matter... to exclude subdirectories, I used
robocopy \\source\folder C:\destinationfolder /XD * /MIR
...and that works for me (Windows 10 copy from Windows Server 2016)
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
https://github.com/nigma/django-easy-pdf
Template:
{% extends "easy_pdf/base.html" %}
{% block content %}
<div id="content">
<h1>Hi there!</h1>
</div>
{% endblock %}
View:
from easy_pdf.views import PDFTemplateView
class HelloPDFView(PDFTemplateView):
template_name = "hello.html"
If you want to use django-easy-pdf on Python 3 check the solution suggested here.
Counting to 2^128 - ambitious.
Lets imagine that we can count 2^32 IDs per second per machine - not that ambitious, since it's not even 4.3 billion per second. Lets dedicate 2^32 machines to that task. Furthermore, lets get 2^32 civilisations to each dedicate the same resources to the task.
So far, we can count 2^96 IDs per second, meaning we will be counting for 2^32 seconds (a little over 136 years).
Now, all we need is to get 4,294,967,296 civilisations to each dedicate 4,294,967,296 machines, each machine capable of counting 4,294,967,296 IDs per second, purely to this task for the next 136 years or so - I suggest we get started on this essential task right now ;-)
Be sure you edited php.ini in /php folder, I lost all day to detect error and finally I found I edited php.ini in wrong location.
If your branch is local only and hasn't been pushed to the server, use
git rebase master
Otherwise, use
git merge master
Edit:
There's either a bug with git pull
, or you can't do what you're trying to do with that command. You can however, do it with fetch and merge:
cd /X
git --git-dir=/X/Y/.git fetch
git --git-dir=/X/Y/.git --work-tree=/X/Y merge origin/master
Original answer:
Assuming you're running bash or similar, you can do (cd /X/Y; git pull)
.
The git man page specifies some variables (see "The git Repository") that seem like they should help, but I can't make them work right (with my repository in /tmp/ggg2):
GIT_WORK_TREE=/tmp/ggg2 GIT_DIR=/tmp/ggg2/.git git pull
fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.
Running the command below while my cwd is /tmp updates that repo, but the updated file appears in /tmp instead of the working tree /tmp/ggg2:
GIT_DIR=/tmp/ggg2/.git git pull
See also this answer to a similar question, which demonstrates the --git-dir
and --work-tree
flags.
No, don't do it that way.
From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.
Tadaa!! :)
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
It means that a Lambda expression of type TDelegate
which contains a ([parameters]) => { some code };
cannot be converted to an Expression<TDelegate>
. It's the rule.
Simplify your query. The one you provided can be rewritten as the following and will compile:
Arr[] myArray = objects.Select(o => new Obj()
{
Var1 = o.someVar,
Var2 = o.var2
} ).ToArray();
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.
I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.
This script will help you switch Gopaths. https://github.com/buffonomics/goswitch
A natural key, if available, is usually best. So, if datetime/char uniquely identifies the row and both parts are meaningful to the row, that's great.
If just the datetime is meaningful, and the char is just tacked on to make it unique, then you might as well just go with an identify field.
I would try to set a flag on the window.onfocus
and window.onblur
events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
Try this, but you can adjust frame size with bounds and edit title.
package co.form.Try;
import javax.swing.JFrame;
public class Form {
public static void main(String[] args) {
JFrame obj =new JFrame();
obj.setBounds(10,10,700,600);
obj.setTitle("Application Form");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I think you are looking for:
git update-index --skip-worktree FILENAME
which ignore changes made local
Here's http://devblog.avdi.org/2011/05/20/keep-local-modifications-in-git-tracked-files/ more explanation about these solution!
to undo use:
git update-index --no-skip-worktree FILENAME
If your matrix is called m
, just use :
R> m[m$three == 11, ]
For posterity, this answer is incorrect as noted by Steven Lu. Leaving original text however.
Original answer:
To those arriving via web search (several years later)...
When using screen, your scrollback buffer is a combination of both the screen
scrollback buffer as the two previous answers have noted, as well as your putty scrollback buffer.
Be sure that you are increasing BOTH the putty scrollback buffer as well as the screen scrollback buffer, else your putty window itself won't let you scroll back to see your screen
's scrollback history (overcome by scrolling within screen with ctrl+a->ctrl+u
)
You can change your putty scrollback limit under the "Window" category in the settings. Exiting and reopening a putty session to your screen won't close your screen (assuming you just close the putty window and don't type exit
), as the OP asked for.
Hope that helps identify why increasing the screen's scrollback buffer doesn't solve someone's problem.
Why not simply check for dict.keys.contains(key)
?
Checking for dict[key] != nil
will not work in cases where the value is nil.
As with a dictionary [String: String?]
for example.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
<h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>
You can try the code here:
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat
that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat
that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat
like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
I had the same problem and for me it was because the vc2010 redist x86 was too recent.
Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named
and check if you have the following error
Installation Blockers:
A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.
Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).
then go to Control Panel>Program & Features and uninstall all the
After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.
answering to your question:
How can I destroy or unset the value of the session?
I can help you by this:
$this->session->unset_userdata('some_name');
and for multiple data you can:
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
and to destroy the session:
$this->session->sess_destroy();
Now for the on page change part (on the top of my mind):
you can set the config "anchor_class" of the paginator equal to the classname you want.
after that just check it with jquery onclick for that class which will send a head up to the controller function that will unset the user session.
DateTime
is not standard nullable type. If you want assign null to DateTime
type of variable, you have to use DateTime?
type which supports null value.
If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:
if (dateTimeVariable == default(DateTime))
{
//do work for dateTimeVariable == null situation
}
The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array
:
size_in_bytes = my_numpy_array.nbytes
Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.
No need for the specificity .navbar-default
in your CSS. Background color requires background-color:#cc333333
(or just background:#cc3333
). Finally, probably best to consolidate all your customizations into a single class, as below:
.navbar-custom {
color: #FFFFFF;
background-color: #CC3333;
}
..
<div id="menu" class="navbar navbar-default navbar-custom">
Example: http://www.bootply.com/OusJAAvFqR#
(did not mean to make the comment)
Ok, it doesn't really depend on types in that way. I may have mis-understood the original question here so forgive me if that is the case. If you create serliazers.py then in there you create classes that have meta classes.
Class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = modelName
fields =('csv','of','fields')
Then when you get the data in the view class you can:
model_data - Model.objects.filter(...)
serializer = MyModelSerializer(model_data, many=True)
return Response({'data': serilaizer.data}, status=status.HTTP_200_OK)
That is pretty much what I have in a vareity of places and it returns nice JSON via the JSONRenderer.
As I said this is courtesy of the DjangoRestFramework so it's worth looking into that.
A good plugin that I have used before is DataTables.
s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)
Output: ['hi', 'how', 'are', 'you']
Of course.
Declaring a class abstract only means that you don't allow it to be instantiated on its own.
Declaring a method abstract means that subclasses have to provide an implementation for that method.
The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final
methods but never the other way around.
if else condition can be covered with ternary operator
@item.rigged? ? 'Yes' : 'No'
Answer for a slightly different problem:
You have a sequence of raw unicode that was saved into a str variable:
s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"
You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)
s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'
Solution:
s_new: bytes = bytes(s, encoding="raw_unicode_escape")
Reference (scroll up for standard encodings):
Oddly nobody mentioned mobx
. The idea is similar to redux
. If I have a piece of data that multiple components are subscribed to it, then I can use this data to drive multiple components.
It is important that your datetime is in the correct ISO format when using any of the momentjs queries: isBefore
, isAfter
, isSameOrBefore
, isSameOrAfter
, isBetween
So instead of 2014-03-24T01:14:000, your datetime should be either:
2014-03-24T01:14:00 or 2014-03-24T01:14:00.000Z
otherwise you may receive the following deprecation warning and the condition will evaluate to false:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
// https://momentjs.com/docs/#/query/_x000D_
_x000D_
const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
console.log(`Date is After: ${dateIsAfter}`);_x000D_
console.log(`Date is Same: ${dateIsSame}`);_x000D_
console.log(`Date is Before: ${dateIsBefore}`);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"_x000D_
></script>
_x000D_
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity
, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent
in an onClick
:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath))
, which is different from the code from developer.android.com. The original code gave me a FileNotFoundException
.
Check out ALL_TRIGGERS:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#i1592586
if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.
Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-
<select id="uomList" ng-init="modelData.unitId"_x000D_
ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">
_x000D_
You are going right way my friend.Now if you want retrive cookie
anywhere in project just put this code $val = Cookie::get('COOKIE_NAME');
That's it!
For more information how can this done click here
I'm not a fan of using modules when they are not needed. This job only requires simple math, so here is my simple function to do the job:
def ipToInt(ip):
o = map(int, ip.split('.'))
res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
return res
def isIpInSubnet(ip, ipNetwork, maskLength):
ipInt = ipToInt(ip)#my test ip, in int form
maskLengthFromRight = 32 - maskLength
ipNetworkInt = ipToInt(ipNetwork) #convert the ip network into integer form
binString = "{0:b}".format(ipNetworkInt) #convert that into into binary (string format)
chopAmount = 0 #find out how much of that int I need to cut off
for i in range(maskLengthFromRight):
if i < len(binString):
chopAmount += int(binString[len(binString)-1-i]) * 2**i
minVal = ipNetworkInt-chopAmount
maxVal = minVal+2**maskLengthFromRight -1
return minVal <= ipInt and ipInt <= maxVal
Then to use it:
>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',24)
True
>>> print isIpInSubnet('66.151.97.193', '66.151.97.192',29)
True
>>> print isIpInSubnet('66.151.96.0', '66.151.97.192',24)
False
>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',29)
That's it, this is much faster than the solutions above with the included modules.
What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.
seems like opening a new session is the key.
see this answer.
and here is an awesome explanation about this error
Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...
create or replace procedure temp_proc is
begin
DBMS_OUTPUT.ENABLE(1000000);
DBMS_OUTPUT.PUT_LINE('Test');
end;
...and call it in a PLSQL block...
begin
temp_proc;
end;
...as SQL is non-procedural.
Just start it with a slash? This means root. As long as you're testing on a web server (e.g. localhost) and not a file system (e.g. C:) then that should be all you need to do.
Edit: As of iOS 3.2, this functionality is built in. If you need to support pre-3.2, you can still use this solution.
I created a simple module that extends UILabel
and handles loading .ttf files. I released it opensource under the Apache license and put it on github Here.
The important files are FontLabel.h
and FontLabel.m
.
It uses some of the code from Genericrich's answer.
Browse the source Here.
OR
Copy your font file into resources
Add a key to your Info.plist
file called UIAppFonts. ("Fonts provided by application)
Make this key an array
For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
Save Info.plist
Now in your application you can simply call [UIFont fontWithName:@"CustomFontName" size:15]
to get the custom font to use with your UILabels
and UITextViews
, etc…
I somehow stumbled on this clever hack on the internet ... I'm not sure if it's nasty or beautiful, but it lets you create a "magical" operator that allows you to unpack multiple return values into their own variable. The :=
function is defined here, and included below for posterity:
':=' <- function(lhs, rhs) {
frame <- parent.frame()
lhs <- as.list(substitute(lhs))
if (length(lhs) > 1)
lhs <- lhs[-1]
if (length(lhs) == 1) {
do.call(`=`, list(lhs[[1]], rhs), envir=frame)
return(invisible(NULL))
}
if (is.function(rhs) || is(rhs, 'formula'))
rhs <- list(rhs)
if (length(lhs) > length(rhs))
rhs <- c(rhs, rep(list(NULL), length(lhs) - length(rhs)))
for (i in 1:length(lhs))
do.call(`=`, list(lhs[[i]], rhs[[i]]), envir=frame)
return(invisible(NULL))
}
With that in hand, you can do what you're after:
functionReturningTwoValues <- function() {
return(list(1, matrix(0, 2, 2)))
}
c(a, b) := functionReturningTwoValues()
a
#[1] 1
b
# [,1] [,2]
# [1,] 0 0
# [2,] 0 0
I don't know how I feel about that. Perhaps you might find it helpful in your interactive workspace. Using it to build (re-)usable libraries (for mass consumption) might not be the best idea, but I guess that's up to you.
... you know what they say about responsibility and power ...
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
I just wanted to share a timestamp prototype I made using Pierre's idea. Not enough points to comment :(
// US common date timestamp
Date.prototype.timestamp = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var h = this.getHours().toString();
var m = this.getMinutes().toString();
var s = this.getSeconds().toString();
return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy + " - " + ((h > 12) ? h-12 : h) + ":" + m + ":" + s;
};
d = new Date();
var timestamp = d.timestamp();
// 10/12/2013 - 2:04:19
if you also want to compare the order of the answer you can extend the answer to something like this:
Array.prototype.compareTo = function (array2){
var array1 = this;
var difference = [];
$.grep(array2, function(el) {
if ($.inArray(el, array1) == -1) difference.push(el);
});
if( difference.length === 0 ){
var $i = 0;
while($i < array1.length){
if(array1[$i] !== array2[$i]){
return false;
}
$i++;
}
return true;
}
return false;
}
You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
display: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
display: block;_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a></li>_x000D_
<li><a href="">Dolor</a></li>_x000D_
<li><a href="">Sit</a></li>_x000D_
<li><a href="">Amet</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/
Yes, ensure
ENSURES it is run every time, so you don't need the file.close
in the begin
block.
By the way, a good way to test is to do:
begin
# Raise an error here
raise "Error!!"
rescue
#handle the error here
ensure
p "=========inside ensure block"
end
You can test to see if "=========inside ensure block" will be printed out when there is an exception.
Then you can comment out the statement that raises the error and see if the ensure
statement is executed by seeing if anything gets printed out.
I juste wrote a proxy in nodejs that take care of HTTPS with optional decoding of the message. This proxy also can add proxy-authentification header in order to go through a corporate proxy. You need to give as argument the url to find the proxy.pac file in order to configurate the usage of corporate proxy.
I was having the same problem and discovered that when show the div, call google.maps.event.trigger(map, 'resize');
and it appears to resolve the issue for me.
You can use the Python implementation of the curses library: curses — Terminal handling for character-cell displays
Also, run this and you'll find your box:
for i in range(255):
print i, chr(i)
Try this command:
@echo off
cls
:loop
echo RAINBOW
color 0
echo RAINBOW
color 1
echo RAINBOW
color 2
echo RAINBOW
color 3
echo RAINBOW
color 4
echo RAINBOW
color 5
echo RAINBOW
color 6
echo RAINBOW
color 8
echo RAINBOW
color 9
echo RAINBOW
color A
echo RAINBOW
color B
echo RAINBOW
color C
echo RAINBOW
color D
echo RAINBOW
color E
echo RAINBOW
goto loop
This should create color changing text go in a loop.
Edit: You can change the words rainbow to whatever you want.
If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:
printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n",
sp->name,
sp->args,
sp->value,
sp->arraysize);
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_ALL to default locale: No such file or directory
Solution:
Try this (uk_UA.UTF-8 is my current locale. Write your locale, for example en_US.UTF-8 !)
sudo locale-gen uk_UA.UTF-8
and this.
sudo dpkg-reconfigure locales
This FutureWarning isn't from Pandas, it is from numpy and the bug also affects matplotlib and others, here's how to reproduce the warning nearer to the source of the trouble:
import numpy as np
print(np.__version__) # Numpy version '1.12.0'
'x' in np.arange(5) #Future warning thrown here
FutureWarning: elementwise comparison failed; returning scalar instead, but in the
future will perform elementwise comparison
False
Another way to reproduce this bug using the double equals operator:
import numpy as np
np.arange(5) == np.arange(5).astype(str) #FutureWarning thrown here
An example of Matplotlib affected by this FutureWarning under their quiver plot implementation: https://matplotlib.org/examples/pylab_examples/quiver_demo.html
There is a disagreement between Numpy and native python on what should happen when you compare a strings to numpy's numeric types. Notice the left operand is python's turf, a primitive string, and the middle operation is python's turf, but the right operand is numpy's turf. Should you return a Python style Scalar or a Numpy style ndarray of Boolean? Numpy says ndarray of bool, Pythonic developers disagree. Classic standoff.
Should it be elementwise comparison or Scalar if item exists in the array?
If your code or library is using the in
or ==
operators to compare python string to numpy ndarrays, they aren't compatible, so when if you try it, it returns a scalar, but only for now. The Warning indicates that in the future this behavior might change so your code pukes all over the carpet if python/numpy decide to do adopt Numpy style.
Numpy and Python are in a standoff, for now the operation returns a scalar, but in the future it may change.
https://github.com/numpy/numpy/issues/6784
https://github.com/pandas-dev/pandas/issues/7830
Either lockdown your version of python and numpy, ignore the warnings and expect the behavior to not change, or convert both left and right operands of ==
and in
to be from a numpy type or primitive python numeric type.
Suppress the warning globally:
import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(5)) #returns False, without Warning
Suppress the warning on a line by line basis.
import warnings
import numpy as np
with warnings.catch_warnings():
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(2)) #returns False, warning is suppressed
print('x' in np.arange(10)) #returns False, Throws FutureWarning
Just suppress the warning by name, then put a loud comment next to it mentioning the current version of python and numpy, saying this code is brittle and requires these versions and put a link to here. Kick the can down the road.
TLDR: pandas
are Jedi; numpy
are the hutts; and python
is the galactic empire. https://youtu.be/OZczsiCfQQk?t=3
This is what DocumentFragment
was meant for.
var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
If you are using Sql Server Management Studio, you can create your own schema by browsing to Databases - Your Database - Security - Schemas.
To create one using a script is as easy as (for example):
CREATE SCHEMA [EnterSchemaNameHere] AUTHORIZATION [dbo]
You can use them to logically group your tables, for example by creating a schema for "Financial" information and another for "Personal" data. Your tables would then display as:
Financial.BankAccounts Financial.Transactions Personal.Address
Rather than using the default schema of dbo.
This is an image registration problem. The general strategy is:
Here's a rough and ready approach, "the dumbest thing that could possibly work":
To counteract the orientation problem, you could have 8 or so initial settings for the basic directions (North, North East, etc). Run each one individually and throw away any results where two or more toes end up at the same pixel. I'll think about this some more, but this kind of thing is still being researched in image processing - there are no right answers!
Slightly more complex idea: (weighted) K-means clustering. It's not that bad.
Then iterate until convergence:
This method will almost certainly give much better results, and you get the mass of each cluster which may help in identifying the toes.
(Again, you've specified the number of clusters up front. With clustering you have to specify the density one way or another: Either choose the number of clusters, appropriate in this case, or choose a cluster radius and see how many you end up with. An example of the latter is mean-shift.)
Sorry about the lack of implementation details or other specifics. I would code this up but I've got a deadline. If nothing else has worked by next week let me know and I'll give it a shot.
As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.
I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)
see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm
Alternatively, if you want to solely obtain the current directory of the current NodeJS script, you could try something simple like this. Note that this will not work in the Node CLI itself:
var fs = require('fs'),
path = require('path');
var dirString = path.dirname(fs.realpathSync(__filename));
// output example: "/Users/jb/workspace/abtest"
console.log('directory to start walking...', dirString);
I encountered this problem when I update my xcode to 8.2beta (with the app name xcode-beta.app), I found the answer above by Jeremy Huddleston Sequoia and tried to rename xcode-beta.app to xcode.app, it worked. I guess the name should be xcode.app to use the simulators, even if you didn't changed the name by yourself when you download the beta one.
@techedemic is correct but is missing '.' to mention the current directory, and this command go throught all subdirectories.
find . -name '*.gz' -exec gunzip '{}' \;
Just initialize an array and push the element on the array. It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']
This generates a random integer of size psize
public static Integer getRandom(Integer pSize) {
if(pSize<=0) {
return null;
}
Double min_d = Math.pow(10, pSize.doubleValue()-1D);
Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
int min = min_d.intValue();
int max = max_d.intValue();
return RAND.nextInt(max-min) + min;
}
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
Based on @Nathan's answer above, but without needing to "remove the final union" and with the option to sort the output, I use the following SQL. It generates another SQL statement which then just run:
select CONCAT( 'select * from (\n', group_concat( single_select SEPARATOR ' UNION\n'), '\n ) Q order by Q.exact_row_count desc') as sql_query
from (
SELECT CONCAT(
'SELECT "',
table_name,
'" AS table_name, COUNT(1) AS exact_row_count
FROM `',
table_schema,
'`.`',
table_name,
'`'
) as single_select
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'YOUR_SCHEMA_NAME'
and table_type = 'BASE TABLE'
) Q
You do need a sufficiently large value of group_concat_max_len
server variable but from MariaDb 10.2.4 it should default to 1M.
The problem is WHEN the event is added and EXECUTED via triggering
(the document
onload
property modification can be verified by examining the properties list).
When does this execute and modify onload
relative to the onload
event trigger:
document.addEventListener('load', ... );
before, during or after the load and/or render of the page's HTML?
This simple scURIple (cut & paste to URL) "works" w/o alert
ing as naively expected:
data:text/html;charset=utf-8,
<html content editable><head>
<script>
document.addEventListener('load', function(){ alert(42) } );
</script>
</head><body>goodbye universe - hello muiltiverse</body>
</html>
Does loading imply script contents have been executed?
A little out of this world expansion ...
Consider a slight modification:
data:text/html;charset=utf-8,
<html content editable><head>
<script>
if(confirm("expand mind?"))document.addEventListener('load', function(){ alert(42) } );
</script>
</head><body>goodbye universe - hello muiltiverse</body>
</html>
and whether the HTML has been loaded or not.
Rendering is certainly pending since goodbye universe - hello muiltiverse
is not seen on screen but, does not the confirm( ... )
have to be already loaded to be executed? ... and so document.addEventListener('load', ... )
... ?
In other words, can you execute code to check for self-loading when the code itself is not yet loaded?
Or, another way of looking at the situation, if the code is executable and executed then it has ALREADY been loaded as a done deal and to retroactively check when the transition occurred between not yet loaded and loaded is a priori fait accompli.
So which comes first: loading and executing the code or using the code's functionality though not loaded?
onload
as a window
property works because it is subordinate to the object and not self-referential as in the document
case, ie. it's the window
's contents, via document
, that determine the loaded question err situation.
PS.: When do the following fail to alert(...)
? (personally experienced gotcha's):
caveat: unless loading to the same window is really fast ... clobbering is the order of the day
so what is really needed below when using the same named window:
window.open(URIstr1,"w") .
addEventListener('load',
function(){ alert(42);
window.open(URIstr2,"w") .
addEventListener('load',
function(){ alert(43);
window.open(URIstr3,"w") .
addEventListener('load',
function(){ alert(44);
/* ... */
} )
} )
} )
alternatively, proceed each successive window.open
with:
alert("press Ok either after # alert shows pending load is done or inspired via divine intervention" );
data:text/html;charset=utf-8,
<html content editable><head><!-- tagging fluff --><script>
window.open(
"data:text/plain, has no DOM or" ,"Window"
) . addEventListener('load', function(){ alert(42) } )
window.open(
"data:text/plain, has no DOM but" ,"Window"
) . addEventListener('load', function(){ alert(4) } )
window.open(
"data:text/html,<html><body>has DOM and", "Window"
) . addEventListener('load', function(){ alert(2) } )
window.open(
"data:text/html,<html><body>has DOM and", "noWindow"
) . addEventListener('load', function(){ alert(1) } )
/* etc. including where body has onload=... in each appropriate open */
</script><!-- terminating fluff --></head></html>
which emphasize onload
differences as a document
or window
property.
Another caveat concerns preserving XSS, Cross Site Scripting, and SOP, Same Origin Policy rules which may allow loading an HTML URI but not modifying it's content to check for same. If a scURIple is run as a bookmarklet/scriplet from the same origin/site then there maybe success.
ie. From an arbitrary page, this link will do the load but not likely do alert('done')
:
<a href="javascript:window.open('view-source:http://google.ca') .
addEventListener( 'load', function(){ alert('done') } )"> src. vu </a>
but if the link is bookmarked and then clicked when viewing a google.ca
page, it does both.
test environment:
window.navigator.userAgent =
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 (Splashtop-v1.2.17.0)
Simply execute command update-migration -Script. This generate new *.sql script which include all DB changes included in migration. In the end of code are insert commands something like this: INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion]) you can simply run this all INSERT and DB will be synchronized
Here is my solution, without overdoing it.
private static string AppendAtPosition(string baseString, int position, string character)
{
var sb = new StringBuilder(baseString);
for (int i = position; i < sb.Length; i += (position + character.Length))
sb.Insert(i, character);
return sb.ToString();
}
Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));
Update: I wrote a solution that doesn't require reading the entire file in one go. It's too big for a stackoverflow answer, but can be found here jsonstream
.
You can use json.JSONDecoder.raw_decode
to decode arbitarily big strings of "stacked" JSON (so long as they can fit in memory). raw_decode
stops once it has a valid object and returns the last position where wasn't part of the parsed object. It's not documented, but you can pass this position back to raw_decode
and it start parsing again from that position. Unfortunately, the Python json
module doesn't accept strings that have prefixing whitespace. So we need to search to find the first none-whitespace part of your document.
from json import JSONDecoder, JSONDecodeError
import re
NOT_WHITESPACE = re.compile(r'[^\s]')
def decode_stacked(document, pos=0, decoder=JSONDecoder()):
while True:
match = NOT_WHITESPACE.search(document, pos)
if not match:
return
pos = match.start()
try:
obj, pos = decoder.raw_decode(document, pos)
except JSONDecodeError:
# do something sensible if there's some error
raise
yield obj
s = """
{"a": 1}
[
1
,
2
]
"""
for obj in decode_stacked(s):
print(obj)
prints:
{'a': 1}
[1, 2]
I was having this problem on a new Linux Ubuntu install and noticed I was getting an error about 'too many watchers for limit' in VSCode at the same time. I followed the instructions to fix it in VSCode and it also fixed the issue with ng watch. More info here https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc
I noticed people suggesting sudo
to run watch. This is a dangerous game, you are giving npm packages root access to your system. If your permissions are correct, my issue could be your fix since the limit is per user, and by running as sudo, you are running as root instead of your current user that is past the limit (running a watch heavy ide like vscode or atom on ). If for some reason you have the wrong permissions, set them properly to your user / group with chown
.
With library(lubridate)
, numeric representations of date and time saved as the number of seconds since
1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime()
:
lubridate::as_datetime(1352068320)
[1] "2012-11-04 22:32:00 UTC"
1. Open the eclipse.ini
file from your eclipse folder,see the picture below.
2. Open eclipse.ini
in Notepad
or any other text-editor
application, Find the line -Xmx256m
(or -Xmx1024m
). Now change the default value 256m
(or 1024m
) to 512m
. You also need to give the exact java installed version (1.6 or 1.7 or other).
Like This:
-Xmx512m
-Dosgi.requiredJavaVersion=1.6
OR
-Xmx512m
-Dosgi.requiredJavaVersion=1.7
OR
-Xmx512m
-Dosgi.requiredJavaVersion=1.8
Then it works well for me.
In attribute inspector give the identifier for that view controller and the below code works for me
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
[self.navigationController pushViewController:detailViewController animated:YES];
A programmer solution:
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;
bool matrix[MATRIX_SIZE][MATRIX_SIZE] = {0};
struct Point { int x; int y; };
Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
void init()
{
int numberOfOnBits = 0;
for (int x = 0 ; x < MATRIX_SIZE ; ++x)
{
for (int y = 0 ; y < MATRIX_SIZE ; ++y)
{
if (x * x + y * y < RADIUS * RADIUS)
{
matrix[x][y] = true;
loopUpTable[numberOfOnBits].x = x;
loopUpTable[numberOfOnBits].y = y;
++numberOfOnBits;
} // if
} // for
} // for
} // ()
Point choose()
{
int randomIndex = randomInt(numberOfBits);
return loopUpTable[randomIndex];
} // ()
The bitmap is only necessary for the explanation of the logic. This is the code without the bitmap:
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;
struct Point { int x; int y; };
Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
void init()
{
int numberOfOnBits = 0;
for (int x = 0 ; x < MATRIX_SIZE ; ++x)
{
for (int y = 0 ; y < MATRIX_SIZE ; ++y)
{
if (x * x + y * y < RADIUS * RADIUS)
{
loopUpTable[numberOfOnBits].x = x;
loopUpTable[numberOfOnBits].y = y;
++numberOfOnBits;
} // if
} // for
} // for
} // ()
Point choose()
{
int randomIndex = randomInt(numberOfBits);
return loopUpTable[randomIndex];
} // ()
make sure you are on a branch, at least in master branch
type:
git branch
you should see:
ubuntu-user:~/git/turmeric-releng$ git branch
* (no branch)
master
then type:
git checkout master
then all your changes will fit in master branch (or the branch u choose)
sed is a stream editor. I would say try man sed.If you didn't find this man page in your system refer this URL:
Applets from what I remember do not need a main method, though I am not sure they are technically a program.
Old way of doing it. Many might hate this way of doing but i still many time find this is still better in my perspective.
Input:
var records = [{
"empid":1,
"fname": "X",
"lname": "Y"
},
{
"empid":2,
"fname": "A",
"lname": "Y"
},
{
"empid":3,
"fname": "B",
"lname": "Y"
},
{
"empid":4,
"fname": "C",
"lname": "Y"
},
{
"empid":5,
"fname": "C",
"lname": "Y"
}
]
var newArr = [1,4,5];
Code:
var newObj = [];
for(var a = 0 ; a < records.length ; a++){
if(newArr.indexOf(records[a].empid) > -1){
newObj.push(records[a]);
}
}
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
Output:
[{
"empid": 1,
"fname": "X",
"lname": "Y"
}, {
"empid": 4,
"fname": "C",
"lname": "Y"
}, {
"empid": 5,
"fname": "C",
"lname": "Y"
}]
Try odbTools at http://odbtools.software.informer.com - it is free.
odbTools is set of integrated GUI tools to manage, administer, monitor and tune the Oracle database.
It is not possible to write an extension method, however it is possible to mimic the behaviour you are asking for.
using FooConsole = System.Console;
public static class Console
{
public static void WriteBlueLine(string text)
{
FooConsole.ForegroundColor = ConsoleColor.Blue;
FooConsole.WriteLine(text);
FooConsole.ResetColor();
}
}
This will allow you to call Console.WriteBlueLine(fooText) in other classes. If the other classes want access to the other static functions of Console, they will have to be explicitly referenced through their namespace.
You can always add all of the methods in to the replacement class if you want to have all of them in one place.
So you would have something like
using FooConsole = System.Console;
public static class Console
{
public static void WriteBlueLine(string text)
{
FooConsole.ForegroundColor = ConsoleColor.Blue;
FooConsole.WriteLine(text);
FooConsole.ResetColor();
}
public static void WriteLine(string text)
{
FooConsole.WriteLine(text);
}
...etc.
}
This would provide the kind of behaviour you are looking for.
*Note Console will have to be added through the namespace that you put it in.
git diff master...feature
shows all the new commits of your current (possibly multi-commit) feature branch.
man git-diff
documents that:
git diff A...B
is the same as:
git diff $(git merge-base A B) B
but the ...
is easier to type and remember.
As mentioned by Dave, the special case of HEAD
can be omitted. So:
git diff master...HEAD
is the same as:
git diff master...
which is enough if the current branch is feature
.
Finally, remember that order matters! Doing git diff feature...master
will show changes that are on master
not on feature
.
I wish more git commands would support that syntax, but I don't think they do. And some even have different semantics for ...
: What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?
I had to add !important
to get it to work. I also made my own class button-primary-override
.
.button-primary-override:hover,
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
background-color: #42A5F5 !important;
border-color: #42A5F5 !important;
background-image: none !important;
border: 0 !important;
}
Have you tried adding the verbose (-v
) operator when you clone?
git clone -v git://git.kernel.org/pub/scm/.../linux-2.6 my2.6
Try using:
SELECT * FROM <tablename> WITH ROWLOCK XLOCK HOLDLOCK
This should make the lock exclusive and hold it for the duration of the transaction.
Actually this doesn't work for both Objects and Classes.
This does:
class TestClass
def methodName
end
end
So with the given answer, this works:
TestClass.method_defined? :methodName # => TRUE
But this does NOT work:
t = TestClass.new
t.method_defined? : methodName # => ERROR!
So I use this for both classes and objects:
Classes:
TestClass.methods.include? 'methodName' # => TRUE
Objects:
t = TestClass.new
t.methods.include? 'methodName' # => TRUE
On my machine, port is in /opt/local/bin/port
- try typing that into a terminal on its own.
For me this is the best way:
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Reset form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").reset();
}
</script>
If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:
import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2
This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.
import numpy as np
len(a) == np.shape(a)[0]
To get the number of elements in a multi-dimensional array of arbitrary shape:
import numpy as np
size = 1
for dim in np.shape(a): size *= dim
You have the following options on Windows command line:
net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]
Try like:
net use H: /delete /y
In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears:
newstr = oldstr.replace("M", "")
If you want to remove the central character:
midlen = len(oldstr)/2 # //2 in python 3
newstr = oldstr[:midlen] + oldstr[midlen+1:]
You asked if strings end with a special character. No, you are thinking like a C programmer. In Python, strings are stored with their length, so any byte value, including \0
, can appear in a string.
Use the library ngx-print.
Installing:
yarn add ngx-print
or
npm install ngx-print --save
Change your module:
import {NgxPrintModule} from 'ngx-print';
...
imports: [
NgxPrintModule,
...
Template:
<div id="print-section">
// print content
</div>
<button ngxPrint printSectionId="print-section">Print</button>
did you try this ?
$("#yourdiv").load(url, function(){
your functions goes here !!!
});
Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.
$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry
Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.
<form blah blah blah method="post">
<input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
<input type="submit" name="add" value="Add />
</form>
And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML
I don't see how
if(!empty($var))
can create confusion, but I do agree thatif ($var)
is simpler. – vanneto Mar 8 '12 at 13:33Because
empty
has the specific purpose of suppressing errors for nonexistent variables. You don't want to suppress errors unless you need to. The Definitive Guide To PHP'sisset
Andempty
explains the problem in detail. – deceze? Mar 9 '12 at 1:24
Focusing on the error suppression part, if the variable is an array where a key being accessed may or may not be defined:
if($web['status'])
would produce:
Notice: Undefined index: status
if(isset($web['status']) && $web['status'])
(2nd condition is not tested if the 1st one is FALSE
) ORif(!empty($web['status']))
.However, as deceze? pointed out, a truthy value of a defined variable makes !empty
redundant, but you still need to remember that PHP assumes the following examples as FALSE
:
null
''
or ""
0.0
0
'0'
or "0"
'0' + 0 + !3
So if zero is a meaningful status that you want to detect, you should actually use string and numeric comparisons:
Error free and zero detection:
if(isset($web['status'])){
if($web['status'] === '0' || $web['status'] === 0 ||
$web['status'] === 0.0 || $web['status']) {
// not empty: use the value
} else {
// consider it as empty, since status may be FALSE, null or an empty string
}
}
The generic condition ($web['status']
) should be left at the end of the entire statement.
I wrote a short convenience function for posting JSON.
$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};
$.postJSON('test/url', data, function(result) {
console.log('result', result);
});
Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!
You could have just changed your query to:
SELECT ename, empno, (SELECT ename FROM EMP WHERE empno = e.mgr)AS MANAGER, mgr
from emp e
order by empno;
This would tell the engine that for the inner emp table, empno should be matched with mgr column from the outer table.
var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
var lines = $('#myTextAreaId').val().split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
Side note, if you prefer forEach a sample loop is
lines.forEach(function(line) {
console.log('Line is ' + line)
})
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
If the destination table does exist but you don't want to specify column names:
DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);
SET @COLUMN_LIST = (SELECT DISTINCT
SUBSTRING(
(
SELECT ', table1.' + SYSCOL1.name AS [text()]
FROM sys.columns SYSCOL1
WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
ORDER BY SYSCOL1.object_id
FOR XML PATH ('')
), 2, 1000)
FROM
sys.columns SYSCOL2
WHERE
SYSCOL2.object_id = object_id('dbo.TableOne') )
SET @SQL_INSERT = 'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT
You need element.scrollHeight. Compare it with $(element).height()
.
If you don't want to change to numeric you can try this.
> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6
You can set environmental variables in Pycharm's run configurations menu.
Open the Run Configuration selector in the top-right and cick Edit Configurations...
Find Environmental variables
and click ...
Add or change variables, then click OK
You can access your environmental variables with os.environ
import os
print(os.environ['SOME_VAR'])
Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.
I would use ruby-build
with rbenv
. The following lines install Ruby 3.0.0 and set it as your default Ruby version:
$ brew update
$ brew install ruby-build
$ brew install rbenv
$ rbenv install 3.0.0
$ rbenv global 3.0.0
In Swift 5 it looks like this:
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true
i believe this jquery work for you well please check a code below.
this will make your submit action works and open a link in new tab whether you want to open action url again or a new link
jQuery('form').on('submit',function(e){
setTimeout(function () { window.open('https://www.google.com','_blank');}, 1000);});})
This code works for me perfect..
as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)
you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key
also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.
I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:
filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
This works:
params.require(:model).permit(filters: [[:name, values: []]])
Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...
CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;
CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid),
INDEX(tmpid))
SELECT * FROM tmpLivecheck;
... solved my problem.
Greetings...
This is a vectorized version of unutbu's answer:
def find_nearest(array, values):
array = np.asarray(array)
# the last dim must be 1 to broadcast in (array - values) below.
values = np.expand_dims(values, axis=-1)
indices = np.abs(array - values).argmin(axis=-1)
return array[indices]
image = plt.imread('example_3_band_image.jpg')
print(image.shape) # should be (nrows, ncols, 3)
quantiles = np.linspace(0, 255, num=2 ** 2, dtype=np.uint8)
quantiled_image = find_nearest(quantiles, image)
print(quantiled_image.shape) # should be (nrows, ncols, 3)
I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
@Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
alertDialog.show();
}
});
}
}
Use System.DateTime.Now.ToUniversalTime()
. That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.
In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).
Then use Search > Bookmark > Remove Bookmarked Lines.
Why would you use -z? To test if a string is non-empty, you typically use -n:
if test -n "$errorstatus"; then echo errorstatus is not empty fi
No for the moment.
I doubt it will be possible for the future for ActiveX support will be discontinued in near future (as MS stated).
Look here about HTML Object tag, but not anything will be accepted. You should try.
Another option is to pass the single quote as an awk variable:
awk -v q=\' 'BEGIN {FS=" ";} {printf "%s%s%s ", q, $1, q}'
Simpler example with string concatenation:
# Prints 'test me', *including* the single quotes.
$ awk -v q=\' '{print q $0 q }' <<<'test me'
'test me'
Late to the party, but maybe my solution will help somebody.
I haven't found any solution that works on a responsive website when the viewport changes or the layout is fluid.
So I've created a jQuery script for django-cms that is dynamically adapting to a changing viewport. I'm going to update this response as soon as I have the need for a modern variant of it that is more modular and has no jQuery dependency.
html
<div class="g-recaptcha" data-sitekey="{site_key}" data-size={size}>
</div>
css
.g-recaptcha { display: none; }
.g-recaptcha.g-recaptcha-initted {
display: block;
overflow: hidden;
}
.g-recaptcha.g-recaptcha-initted > * {
transform-origin: top left;
}
js
window.djangoReCaptcha = {
list: [],
setup: function() {
$('.g-recaptcha').each(function() {
var $container = $(this);
var config = $container.data();
djangoReCaptcha.init($container, config);
});
$(window).on('resize orientationchange', function() {
$(djangoReCaptcha.list).each(function(idx, el) {
djangoReCaptcha.resize.apply(null, el);
});
});
},
resize: function($container, captchaSize) {
scaleFactor = ($container.width() / captchaSize.w);
$container.find('> *').css({
transform: 'scale(' + scaleFactor + ')',
height: (captchaSize.h * scaleFactor) + 'px'
});
},
init: function($container, config) {
grecaptcha.render($container.get(0), config);
var captchaSize, scaleFactor;
var $iframe = $container.find('iframe').eq(0);
$iframe.on('load', function() {
$container.addClass('g-recaptcha-initted');
captchaSize = captchaSize || { w: $iframe.width() - 2, h: $iframe.height() };
djangoReCaptcha.resize($container, captchaSize);
djangoReCaptcha.list.push([$container, captchaSize]);
});
},
lateInit: function(config) {
var $container = $('.g-recaptcha.g-recaptcha-late').eq(0).removeClass('.g-recaptcha-late');
djangoReCaptcha.init($container, config);
}
};
window.djangoReCaptchaSetup = window.djangoReCaptcha.setup;
Use getLayoutPosition() in your custom interface java method. This will return the selected position of an item, check full detail on
https://becody.com/get-clicked-item-and-its-position-in-recyclerview/
You can find some technical comparison on npmcompare
Comparing browserify vs. grunt vs. gulp vs. webpack
As you can see webpack is very well maintained with a new version coming out every 4 days on average. But Gulp seems to have the biggest community of them all (with over 20K stars on Github) Grunt seems a bit neglected (compared to the others)
So if need to choose one over the other i would go with Gulp
For example you can find any textView:
TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);
<video width="400" controls="controls" preload="metadata">_x000D_
<source src="https://www.youtube.com/watch?v=Ulp1Kimblg0">_x000D_
</video>
_x000D_
Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.
cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));
>>> isinstance([0, 10, 20, 30], list)
True
>>> isinstance(50, list)
False
To support any type of sequence, check collections.Sequence
instead of list
.
note: isinstance
also supports a tuple of classes, check type(x) in (..., ...)
should be avoided and is unnecessary.
You may also wanna check not isinstance(x, (str, unicode))
an simple solution!
setInterval(()=>console.clear(),1500);
Thank you Marcosc! Building on his answer, if you want to rename any function, use this:
// returns the function named with the passed name
function namedFunction(name, fn) {
return new Function('fn',
"return function " + name + "(){ return fn.apply(this,arguments)}"
)(fn)
}
Linked list does guarantee sequential order.
Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.
Use ListIterator
ListIterator<Object> iterator = myLinkedList.listIterator();
while( iterator.hasNext()) {
System.out.println(iterator.next());
}
No need for scripts or other 'tricks': openssl
and ssh-keygen
are enough. I'm assuming no password for the keys (which is bad).
All the following methods give an RSA key pair in the same format
With openssl (man genrsa)
openssl genrsa -out dummy-genrsa.pem 2048
In OpenSSL v1.0.1 genrsa
is superseded by genpkey
so this is the new way to do it (man genpkey):
openssl genpkey -algorithm RSA -out dummy-genpkey.pem -pkeyopt rsa_keygen_bits:2048
With ssh-keygen
ssh-keygen -t rsa -b 2048 -f dummy-ssh-keygen.pem -N '' -C "Test Key"
If you have an RSA key pair in DER format, you may want to convert it to PEM to allow the format conversion below:
Generation:
openssl genpkey -algorithm RSA -out genpkey-dummy.cer -outform DER -pkeyopt rsa_keygen_bits:2048
Conversion:
openssl rsa -inform DER -outform PEM -in genpkey-dummy.cer -out dummy-der2pem.pem
in PEM format:
openssl rsa -in dummy-xxx.pem -pubout
in OpenSSH v2 format see:
ssh-keygen -y -f dummy-xxx.pem
OS and software version:
[user@test1 ~]# cat /etc/redhat-release ; uname -a ; openssl version
CentOS release 6.5 (Final)
Linux test1.example.local 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
OpenSSL 1.0.1e-fips 11 Feb 2013
References:
From your config file, it seems like you're only excluding node_modules
from being parsed with babel-loader
, but not from being bundled.
In order to exclude node_modules
and native node libraries from bundling, you need to:
target: 'node'
to your webpack.config.js
. This will exclude native node modules (path, fs, etc.) from being bundled.node_modules
.So your result config file should look like:
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
...
};
I've created an extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism
/// <summary>
/// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">Type of IEnumerable</typeparam>
/// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
/// <param name="action">an async <see cref="Action" /> to execute</param>
/// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
/// Must be grater than 0</param>
/// <returns>A Task representing an async operation</returns>
/// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
public static async Task ForEachAsyncConcurrent<T>(
this IEnumerable<T> enumerable,
Func<T, Task> action,
int? maxDegreeOfParallelism = null)
{
if (maxDegreeOfParallelism.HasValue)
{
using (var semaphoreSlim = new SemaphoreSlim(
maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
{
var tasksWithThrottler = new List<Task>();
foreach (var item in enumerable)
{
// Increment the number of currently running tasks and wait if they are more than limit.
await semaphoreSlim.WaitAsync();
tasksWithThrottler.Add(Task.Run(async () =>
{
await action(item).ContinueWith(res =>
{
// action is completed, so decrement the number of currently running tasks
semaphoreSlim.Release();
});
}));
}
// Wait for all tasks to complete.
await Task.WhenAll(tasksWithThrottler.ToArray());
}
}
else
{
await Task.WhenAll(enumerable.Select(item => action(item)));
}
}
Sample Usage:
await enumerable.ForEachAsyncConcurrent(
async item =>
{
await SomeAsyncMethod(item);
},
5);
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<stroke android:width="1dp" />
<solid android:color="#1e90ff" />
</shape>
android:background="@drawable/corner"
SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%
EDIT
Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.
Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:
@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
SET "line=%%L"
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !line:bath=hello!
ENDLOCAL
)
ENDLOCAL
You can add a redirection to a file:
ECHO !line:bath=hello!>>file2.txt
Or you can apply the redirection to the batch file. It must be a different file.
EDIT 2
Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !
, ^
et al. (Thanks, jeb!)
If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.
Update:
According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).
Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.
First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.
Then, the convention:
And that's it.
It gives
class MyClass {
enum TheEnumeration {
FIRST_ELEMENT,
SECOND_ELEMENT,
}
int class_variable;
int MyMethod(int first_param, int second_parameter) {
int local_variable;
TheEnumeration local_enum;
for(int myindex=0, myindex<class_variable, myindex++) {
localEnum = FIRST_ELEMENT;
}
}
}
They are just \r\n and \n
are variants.
\r\n
is used in windows
\n
is used in mac and linux