I got this error then restarted my GlassFish server that held connection pools between my client app and the database, and the error went away. So, try restarting your application server if applicable.
I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.
Entity Class: implement Serializable?
Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.
Constructors: create a constructor with all required fields of the entity?
Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.
Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.
OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.
Constructors: also, package private default constructor?
Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.
Fields/Properties
Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.
As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.
Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.
Protected is better for (Hibernate) performance?
Unlikely.
Equals/HashCode?
This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.
A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.
The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!
So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.
You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.
Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized
Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.
Equals/HashCode -- never refer to related entities
"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"
Sounds like good advice.
Hope this helps!
Append code snippet to iterate over Map.entrySet()
:
${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
${keyType} ${key} = ${entry}.getKey();
${valueType} ${value} = ${entry}.getValue();
${cursor}
}
for (Entry<String, String> entry : properties.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
|
}
@Mark007, I have changed the type selection criteria to ride of the DbSet<> properties of the DbContext. I think this is safer because there are times when you have classes in the given namespace that shouldn't be part of the model definition or they are but are not entities. Or your entities could reside in separate namespaces or separate assemblies and be pulled together into once Context.
Also, even though unlikely, I do not think it's safe to rely on ordering of method definitions, so it's better to pull them out with by Parameter list. (.GetTypeMethods() is an extension method I built to work with the new TypeInfo paradigm and can flatten class hierarchies when looking for methods).
Do note that OnModelCreating delegates to this method:
private void OnModelCreatingSetDecimalPrecisionFromAttribute(DbModelBuilder modelBuilder)
{
foreach (var iSetProp in this.GetType().GetTypeProperties(true))
{
if (iSetProp.PropertyType.IsGenericType
&& (iSetProp.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>) || iSetProp.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)))
{
var entityType = iSetProp.PropertyType.GetGenericArguments()[0];
foreach (var propAttr in entityType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) })
.Where(propAttr => propAttr.attr != null))
{
var entityTypeConfigMethod = modelBuilder.GetType().GetTypeInfo().DeclaredMethods.First(m => m.Name == "Entity");
var entityTypeConfig = entityTypeConfigMethod.MakeGenericMethod(entityType).Invoke(modelBuilder, null);
var param = ParameterExpression.Parameter(entityType, "c");
var lambdaExpression = Expression.Lambda(Expression.Property(param, propAttr.prop.Name), true, new ParameterExpression[] { param });
var propertyConfigMethod =
entityTypeConfig.GetType()
.GetTypeMethods(true, false)
.First(m =>
{
if (m.Name != "Property")
return false;
var methodParams = m.GetParameters();
return methodParams.Length == 1 && methodParams[0].ParameterType == lambdaExpression.GetType();
}
);
var decimalConfig = propertyConfigMethod.Invoke(entityTypeConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
}
}
}
}
public static IEnumerable<MethodInfo> GetTypeMethods(this Type typeToQuery, bool flattenHierarchy, bool? staticMembers)
{
var typeInfo = typeToQuery.GetTypeInfo();
foreach (var iField in typeInfo.DeclaredMethods.Where(fi => staticMembers == null || fi.IsStatic == staticMembers))
yield return iField;
//this bit is just for StaticFields so we pass flag to flattenHierarchy and for the purpose of recursion, restrictStatic = false
if (flattenHierarchy == true)
{
var baseType = typeInfo.BaseType;
if ((baseType != null) && (baseType != typeof(object)))
{
foreach (var iField in baseType.GetTypeMethods(true, staticMembers))
yield return iField;
}
}
}
You are using cache system.. you can modify the original file and clear cache to show updates
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate
.
If you have a named form myForm
, you can programmatically call myForm.my_field.$validate()
to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate
has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid
is set to true
for your model.
Before using the $result
variable, you should use $row = mysqli_fetch_array($result)
or mysqli_fetch_assoc()
functions.
Like this:
$row = mysqli_fetch_array($result);
and use the $row
array as you need.
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
You have to run the create_tables.sql inside the examples/ folder on phpMyAdmin to create the tables needed for the advanced features. That or disable those features by commenting them on the config file.
You don't need one unless your class maintains unmanaged resources like Windows file handles.
SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
SearchView.OnQueryTextListener
has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
This is how you can implement abstract methods of the listener.
@Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView
.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
It seems that using mongoose there is a limit of more than 1000 documents, when using
Potato.collection.insert(potatoBag, onInsert);
You can use:
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
But this is almost twice as fast when testing with 10000 documents:
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
Given numbers are only for storing 1 character
If you want to avoid npm install and not running in browser, you can also use nodejs https module;
const https = require('https')
const url = "https://jsonmock.hackerrank.com/api/movies";
https.get(url, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
data = JSON.parse(data);
console.log(data);
})
}).on('error', err => {
console.log(err.message);
})
I just encountered a case of needing to revert just one file to previous revision, right after I had done commit and push. Shorthand syntax for specifying these revisions isn't covered by the other answers, so here's command to do that
hg revert path/to/file -r-2
That -2
will revert to the version before last commit, using -1
would just revert current uncommitted changes.
If the main idea is to make the SQL select statement sent to the Database server have only the required fields, and not all the Entity fields, then u can do this:
public class Class1
{
public IList<Car> getCarsByProjectionOnSmallNumberOfProperties()
{
try
{
//Get the SQL Context:
CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext dbContext
= new CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext();
//Specify the Context of your main entity e.g. Car:
var oDBQuery = dbContext.Set<Car>();
//Project on some of its fields, so the created select statment that is
// sent to the database server, will have only the required fields By making a new anonymouse type
var queryProjectedOnSmallSetOfProperties
= from x in oDBQuery
select new
{
x.carNo,
x.eName,
x.aName
};
//Convert the anonymouse type back to the main entity e.g. Car
var queryConvertAnonymousToOriginal
= from x in queryProjectedOnSmallSetOfProperties
select new Car
{
carNo = x.carNo,
eName = x.eName,
aName = x.aName
};
//return the IList<Car> that is wanted
var lst = queryConvertAnonymousToOriginal.ToList();
return lst;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
throw;
}
}
}
Synchronization or Thread Safe :
Hash Map is not synchronized hence it is not thred safe and it cannot be shared between multiple threads without proper synchronized block whereas, Hashtable is synchronized and hence it is thread safe.
Null keys and null values :
HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.
Iterating the values:
Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method.
Superclass and Legacy :
HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.
Performance :
As HashMap is not synchronized it is faster as compared to Hashtable.
Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection
You can just put:
header("HTTP/1.0 500 Internal Server Error");
inside your conditions like:
if (that happened) {
header("HTTP/1.0 500 Internal Server Error");
}
As for the database query, you can just do that like this:
$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");
You should remember that you have to put this code before any html tag (or output).
If you want the overflow to wrap: flex-flow: row wrap
Your DateFormat
pattern does not match you input date String
. You could use
new SimpleDateFormat("dd-MMM-yyyy")
If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:
header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();
mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.
Please use following CSS properties for center align element horizontally as well as vertically. This is worked fine for me.
div {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0px;
margin: auto;
width: 100px;
height: 100px;
}
1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:
gem 'devise', '3.0.0.rc'
Then execute:
$ bundle
2) Add the old functionality of attr_accessible
again to rails 4.0
Try to use attr_accessible
and don't comment this out.
Add this line to your application's Gemfile:
gem 'protected_attributes'
Then execute:
$ bundle
to find the program you want you can run this command at terminal:
find / usr-name "your_program"
If it is the most recent commit, you can simply do this:
git commit --amend
This brings up the editor with the last commit message and lets you edit the message. (You can use -m
if you want to wipe out the old message and use a new one.)
And then when you push, do this:
git push --force-with-lease <repository> <branch>
Or you can use "+":
git push <repository> +<branch>
Or you can use --force
:
git push --force <repository> <branch>
Be careful when using these commands.
If someone else pushed changes to the same branch, you probably want to avoid destroying those changes. The --force-with-lease
option is the safest, because it will abort if there are any upstream changes (
If you don't specify the branch explicitly, Git will use the default push settings. If your default push setting is "matching", then you may destroy changes on several branches at the same time.
Anyone who already pulled will now get an error message, and they will need to update (assuming they aren't making any changes themselves) by doing something like this:
git fetch origin
git reset --hard origin/master # Loses local commits
Be careful when using reset --hard
. If you have changes to the branch, those changes will be destroyed.
The destroyed data is really just the old commit message, but --force
doesn't know that, and will happily delete other data too. So think of --force
as "I want to destroy data, and I know for sure what data is being destroyed." But when the destroyed data is committed, you can often recover old commits from the reflog—the data is actually orphaned instead of destroyed (although orphaned commits are periodically deleted).
If you don't think you're destroying data, then stay away from --force
... bad things might happen.
This is why --force-with-lease
is somewhat safer.
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
In addition, gcc will look in the directories specified after the -I
option.
document.getElementById('gadget_url').value = 'your value';
Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.
import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]
query = sa.text("""
SELECT *
FROM my_table
WHERE col1 IN :values;
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)
Few ideas:
Try something like this:
SELECT DISTINCT TOP 10 p.id, pl.nm -- , pl.val, pl.txt_val
FROM dm.labs pl
JOIN mas_data.patients p
on pl.id = p.id
where pl.nm like '%LDL%'
and val is not null
ORDER BY pl.nm
Note that i commented out some of the SELECT to limit your result set and DISTINCT logic.
This code will help you, and it's fairly self-explanatory:
#include <stdio.h> /* Standard Library of Input and Output */
#include <complex.h> /* Standard Library of Complex Numbers */
int main() {
double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;
printf("Working with complex numbers:\n\v");
printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));
double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));
double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));
double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));
double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));
double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));
return 0;
}
with:
creal(z1)
: get the real part (for float crealf(z1)
, for long double creall(z1)
)
cimag(z1)
: get the imaginary part (for float cimagf(z1)
, for long double cimagl(z1)
)
Another important point to remember when working with complex numbers is that functions like cos()
, exp()
and sqrt()
must be replaced with their complex forms, e.g. ccos()
, cexp()
, csqrt()
.
The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with
conda install -c anaconda pandas
Unfortunately I do not know how to help with Eclipse.
Click on the Monitor (DDMS Included) button on the toolbar -- it looks like the Android bugdroid:
That will bring up the DDMS window. Select the emulator instance from the Devices tab on the left, and click on the camera button in the toolbar above it, next to the stop sign icon:
Note that if your emulator is running Android 4.4 or I think 4.3, then screen capture functionality is broken -- you'll have to use a physical device to get screenshots on those OS versions. It works okay for Android prior to 4.3. That bug is https://code.google.com/p/android/issues/detail?id=62284
Wade73's answer for decimals doesn't quite work. I've modified it to allow only a single decimal point.
declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar)
values
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......');
-- This shows that Wade73's answer allows some non-numeric values to slip through.
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber
from
@MyTable
) t order by IsNumber;
-- Notice the addition of "and MyVar not like N'%.%.%'".
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' then 1 else 0 end as IsNumber
from
@MyTable
) t
order by IsNumber;
Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab?
$(document).on('click','span.external-link',function(){
var t = $(this),
URL = t.attr('data-href');
$('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();
});
Working example.
You might not have developer access to the project or master branch. You need dev access to push new work up.
New work meaning new branches and commits.
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
I don't know how the table is created but try this...
SELECT users1.user_id, users2.user_parent_id
FROM users AS users1
INNER JOIN users AS users2
ON users1.id = users2.id
WHERE users1.user_id = users2.user_parent_id
SELECT * FROM Accounts WHERE Username LIKE '%$query%'
but it's not suggested. use PDO
Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.
Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR
Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR
Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.
Credit to www.androidofficer.com
Example in Swift 3, with a previous and a next button in the top right.
let prevButtonItem = UIBarButtonItem(title: "\u{25C0}", style: .plain, target: self, action: #selector(prevButtonTapped))
let nextButtonItem = UIBarButtonItem(title: "\u{25B6}", style: .plain, target: self, action: #selector(nextButtonTapped))
self.navigationItem.rightBarButtonItems = [nextButtonItem, prevButtonItem]
Late but more complete answer in point of getting the most advanced date from $Output
## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv
## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
Sort-Object Date | Select-Object -Last 1 -Expand Date
## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
Sort-Object | Select-Object -Last 1
## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
[datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1
## for non English locales
$Output.Date | ForEach-Object{
[datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1
## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
[datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1
It's possible to pass args to npm run
since npm 2 (2014). The syntax is as follows:
npm run <command> [-- <args>]
Note the --
separator, used to separate the params passed to npm
command itself, and the params passed to your script.
With the example package.json
:
"scripts": {
"grunt": "grunt",
"server": "node server.js"
}
here's how to pass the params to those scripts:
npm run grunt -- task:target // invokes `grunt task:target`
npm run server -- --port=1337 // invokes `node server.js --port=1337`
Note: If your param does not start with -
or --
, then having an explicit --
separator is not needed; but it's better to do it anyway for clarity.
npm run grunt task:target // invokes `grunt task:target`
Note below the difference in behavior (test.js
has console.log(process.argv)
): the params which start with -
or --
are passed to npm
and not to the script, and are silently swallowed there.
$ npm run test foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar']
$ npm run test -foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js']
$ npm run test --foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js']
$ npm run test -- foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar']
$ npm run test -- -foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '-foobar']
$ npm run test -- --foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '--foobar']
The difference is clearer when you use a param actually used by npm:
$ npm test --help // this is disguised `npm --help test`
npm test [-- <args>]
aliases: tst, t
To get the parameter value, see this question. For reading named parameters, it's probably best to use a parsing library like yargs or minimist; nodejs exposes process.argv
globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).
Edit 2013.10.03: It's not currently possible directly. But there's a related GitHub issue opened on npm
to implement the behavior you're asking for. Seems the consensus is to have this implemented, but it depends on another issue being solved before.
Original answer (2013.01): As a some kind of workaround (though not very handy), you can do as follows:
Say your package name from package.json
is myPackage
and you have also
"scripts": {
"start": "node ./script.js server"
}
Then add in package.json
:
"config": {
"myPort": "8080"
}
And in your script.js
:
// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080
That way, by default npm start
will use 8080. You can however configure it (the value will be stored by npm
in its internal storage):
npm config set myPackage:myPort 9090
Then, when invoking npm start
, 9090 will be used (the default from package.json
gets overridden).
From the manual:
SET NAMES indicates what character set the client will use to send SQL statements to the server.
More elaborately, (and once again, gratuitously lifted from the manual):
SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)
Below code works fine before 18 API :-
public String getRealPathFromURI(Uri contentUri) {
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
below code use on kitkat :-
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
see below link for more info:-
Here is a well tested function which i used for my projects with detailed self explanatory comments
There are many times when the ports other than 80 are blocked by server firewall so the code appears to be working fine on localhost but not on the server
function get_page($url){
global $proxy;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
curl_setopt($ch, CURLOPT_TIMEOUT, 200); // http request timeout 20 seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // the page encoding
$data = curl_exec($ch); // execute the http request
curl_close($ch); // close the connection
return $data;
}
You were so close! Here is the easiest solution: NEWTESTSTRING=$(echo ${TESTSTRINGONE::5})
So for your example:
$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=$(echo ${TESTSTRINGONE::5})
$ echo $NEWTESTSTRING
MOTES
ELXAN@DB1> create table cedvel(id integer,ad varchar2(15)); Table created. ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id); Table altered. ELXAN@DB1> create sequence test_seq start with 1 increment by 1; Sequence created. ELXAN@DB1> create or replace trigger ad_insert before insert on cedvel REFERENCING NEW AS NEW OLD AS OLD for each row begin select test_seq.nextval into :new.id from dual; end; / 2 3 4 5 6 7 8 Trigger created. ELXAN@DB1> insert into cedvel (ad) values ('nese'); 1 row created.
In Linux I resolve this problem by going to the root command prompt type:
# mysqladmin -u root password 'Secret Phrase Here'
Then go back and login. Works every time!
Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:
Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:
<configuration>
<system.serviceModel>
<services>
<service name="com.aschneider.examples.wcf.services.EchoService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/EchoService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors></serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IEchoService"/>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address = "net.pipe://localhost/EchoService"
binding = "netNamedPipeBinding"
bindingConfiguration = "NetNamedPipeBinding_IEchoService"
contract = "EchoServiceReference.IEchoService"
name = "NetNamedPipeBinding_IEchoService"/>
</client>
</system.serviceModel>
</configuration>
The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).
Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...
After several strange errors with relative paths in connectionstring I felt the need to post this here.
When using "|DataDirectory|" or "~" you are not allowed to step up and out using "../" !
Example is using several projects accessing the same localdb file placed in one of the projects.
" ~/../other" and " |DataDirectory|/../other" will fail
Even if it is clearly written at MSDN here the errors it gave where a bit unclear so hard to find and could not find it here at SO.
There are several correct ways to display a down-pointing and upward-pointing triangle.
HTML :
▲
▼
HTML :
▲
▼
HTML :
?
?
HTML :
<span class='icon-up'></span>
<span class='icon-down'></span>
CSS :
.icon-up:before {
content: "\25B2";
}
.icon-down:before {
content: "\25BC";
}
Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. ♥
to display ?).
You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.
Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.
If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.
A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.
This following code is the base64 for and SVG version of the icon :
/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=
For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:
SVG images
color
, font-size
, line-height
, background-color
or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.Icon fonts
color
, font-size
, line-height
, background-color
or other font related styling rules to change the display of your iconPersonally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color
, background-color
and other color-related CSS rules for fonts.
The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.
Instead of having to account for window.location.protocol and window.location.origin, and possibly missing a specified port number, etc., just grab everything up to the 3rd "/":
// get nth occurrence of a character c in the calling string
String.prototype.nthIndex = function (n, c) {
var index = -1;
while (n-- > 0) {
index++;
if (this.substring(index) == "") return -1; // don't run off the end
index += this.substring(index).indexOf(c);
}
return index;
}
// get the base URL of the current page by taking everything up to the third "/" in the URL
function getBaseURL() {
return document.URL.substring(0, document.URL.nthIndex(3,"/") + 1);
}
Give your inner div a width.
EXAMPLE
Change your CSS:
<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>
To this:
<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; width:500px }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>
You need to use the alias
directive for location /static
:
server {
index index.html;
server_name test.example.com;
root /web/test.example.com/www;
location /static/ {
alias /web/test.example.com/static/;
}
}
The nginx wiki explains the difference between root and alias better than I can:
Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.
Note that root
and alias
handle trailing slashes differently.
I really think you will benefit from establishing the following function calling coding guidelines:
As in all other places, always be const
-correct.
const
specifier.Only pass a value by pointer if the value 0/NULL is a valid input in the current context.
Rationale 1: As a caller, you see that whatever you pass in must be in a usable state.
Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value.
Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can.
If a function argument is an out-value, then pass it by reference.
Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.
If you are looking for a complete solution for Async
loading a JSON file from Relative Path
with Error Handling
// Global variables
// Request path module for relative path
const path = require('path')
// Request File System Module
var fs = require('fs');
// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
console.log("Got a GET request for list of users");
// Create a relative path URL
let reqPath = path.join(__dirname, '../mock/users.json');
//Read JSON from relative path of this file
fs.readFile(reqPath , 'utf8', function (err, data) {
//Handle Error
if(!err) {
//Handle Success
console.log("Success"+data);
// Parse Data to JSON OR
var jsonObj = JSON.parse(data)
//Send back as Response
res.end( data );
}else {
//Handle Error
res.end("Error: "+err )
}
});
})
Directory Structure:
Using the SSH URL from GitLab:
Step 1: Generate an SSH Key with default values from GitLab.
GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.
STEP 2: Add the SSH key to your keychain using the command ssh-add -K
.
Open the terminal and paste the above command in it. This will add the key to your keychain.
STEP 3: Restart SourceTree and clone remote repo using URL.
Restarting SourceTree is needed so that SourceTree picks the new key.
STEP 4: Copy the SSH URL provided by GitLab.
STEP 5: Paste the SSH URL into the Source URL field of SourceTree.
These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.
One of these :
$ip = $_SERVER['REMOTE_ADDR'];
$ip = $_SERVER['HTTP_CLIENT_IP'];
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = $_SERVER['HTTP_X_FORWARDED'];
$ip = $_SERVER['HTTP_FORWARDED_FOR'];
$ip = $_SERVER['HTTP_FORWARDED'];
Not the answer for this question
I got this exception when trying to delete a folder where i deleted the file inside.
Example:
createFolder("folder");
createFile("folder/file");
deleteFile("folder/file");
deleteFolder("folder"); // error here
While deleteFile("folder/file");
returned that it was deleted, the folder will only be considered empty after the program restart.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-
Refering to MySql documentation,
CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.
You can access the full uri/url with 'document.referrer'
Check https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
If this happens in visual studio then clean your project and run it again.
Build --> Clean Solution
Run (or F5)
Unix cp
doesn't 'support both directories and files':
betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).
To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.
There is some disconnect here though - cp -r
when passed a filename as the source will happily copy just the single file; copytree won't.
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
I am using below solution but for that you have to install sshpass
If its not already installed, install it using sudo apt install sshpass
Now you can do this,
sshpass -p *YourPassword* shh root@IP
You can create a bash alias as well so that you don't have to run the whole command again and again. Follow below steps
cd ~
sudo nano .bash_profile
at the end of the file add below code
mymachine() { sshpass -p *YourPassword* shh root@IP }
source .bash_profile
Now just run mymachine
command from terminal and you'll enter your machine without password prompt.
Note:
mymachine
can be any command of your choice.The typical solution is to dump the database as necessary and backup those files.
Depending on your development platform, there may be opensource plugins available. Rolling your own code to do it is usually fairly trivial.
Note: You may want to backup the database dump instead of putting it into version control. The files can get huge fast in version control, and cause your entire source control system to become slow (I'm recalling a CVS horror story at the moment).
I had the same problem & in my case this is what I did
@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)
and in Partial view
@foreach (Shop cabinet in Model)
{
//...
}
You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:
string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(json);
StringBuilder sb = new StringBuilder();
sb.Append("<table>\n <thead>\n <tr>\n");
// Build the header based on the keys in the
// first data item.
foreach (string key in data["items"][0].Keys) {
sb.AppendFormat(" <th>{0}</th>\n", key);
}
sb.Append(" </tr>\n </thead>\n <tbody>\n");
foreach (Dictionary<string, object> item in data["items"]) {
sb.Append(" <tr>\n");
foreach (string val in item.Values) {
sb.AppendFormat(" <td>{0}</td>\n", val);
}
}
sb.Append(" </tr>\n </tbody>\n</table>");
string myTable = sb.ToString();
At the end, myTable
will hold a string that looks like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>22</td>
<td>PPP</td>
<tr>
<td>BBB</td>
<td>25</td>
<td>QQQ</td>
<tr>
<td>CCC</td>
<td>38</td>
<td>RRR</td>
</tr>
</tbody>
</table>
A possible solution:
import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['x'])
xLower = df["x"].map(lambda x: x if type(x)!=str else x.lower())
print (xLower)
And a result:
0 one
1 two
2 NaN
Name: x, dtype: object
Not sure about the efficiency though.
If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:
stringnamehere.decode('utf-8', 'ignore')
If you are learning it's helpful to use a GUI like SQLyog, make the changes using the program and then see the History tab for the DDL statements that made those changes.
This is how I keep the structure of folders while ignoring everything else. You have to have a README.md file in each directory (or .gitkeep).
/data/*
!/data/README.md
!/data/input/
/data/input/*
!/data/input/README.md
!/data/output/
/data/output/*
!/data/output/README.md
As oliver writes:
add_header
works as well withproxy_pass
as without.
However, as Shane writes, as of Nginx 1.7.5, you must pass always
in order to get add_header
to work for error responses, like so:
add_header X-Upstream $upstream_addr always;
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
First of all, you don't need to "clean up" string
s and int
s - they will be taken care of automatically by the garbage collector. The only thing that needs to be cleaned up in Dispose
are unmanaged resources or managed recources that implement IDisposable
.
However, assuming this is just a learning exercise, the recommended way to implement IDisposable
is to add a "safety catch" to ensure that any resources aren't disposed of twice:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
// Indicate that the instance has been disposed.
_disposed = true;
}
}
Here a simple and easy solution on Angular JS using ng-repeat that might help.
var app = angular.module('myapp', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
_x000D_
$scope.arr= [_x000D_
{name:"Head1",desc:"Head1Desc"},_x000D_
{name:"Head2",desc:"Head2Desc"},_x000D_
{name:"Head3",desc:"Head3Desc"},_x000D_
{name:"Head4",desc:"Head4Desc"}_x000D_
];_x000D_
_x000D_
$scope.collapseIt = function(id){_x000D_
$scope.collapseId = ($scope.collapseId==id)?-1:id;_x000D_
}_x000D_
});
_x000D_
/* Put your css in here */_x000D_
li {_x000D_
list-style:none;_x000D_
padding:5px;_x000D_
color:red;_x000D_
}_x000D_
div{_x000D_
padding:10px;_x000D_
background:#ddd;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myapp">_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>AngularJS Simple Collapse</title>_x000D_
<script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>_x000D_
</head>_x000D_
<body ng-controller="MainCtrl">_x000D_
<ul>_x000D_
<li ng-repeat='ret in arr track by $index'>_x000D_
<div ng-click="collapseIt($index)">{{ret.name}}</div>_x000D_
<div ng-if="collapseId==$index">_x000D_
{{ret.desc}}_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
</html>
_x000D_
This should fulfill your requirements. Here is a working code.
Plunkr Link http://plnkr.co/edit/n5DZxluYHi8FI3OmzFq2?p=preview
Github: https://github.com/deepakkoirala/SimpleAngularCollapse
First of all, create a Github account and project in Github. Go to the root folder and follow steps.
The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.
git init
Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.idea
.DS_Store
/build
/captures
.externalNativeBuild
git add .
git remote add origin https://github.com/username/project.git
git commit - m "My First Commit"
git push -u origin master
Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.
Static methods in python are called classmethods. Take a look at the following code
class MyClass:
def myInstanceMethod(self):
print 'output from an instance method'
@classmethod
def myStaticMethod(cls):
print 'output from a static method'
>>> MyClass.myInstanceMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method myInstanceMethod() must be called [...]
>>> MyClass.myStaticMethod()
output from a static method
Notice that when we call the method myInstanceMethod, we get an error. This is because it requires that method be called on an instance of this class. The method myStaticMethod is set as a classmethod using the decorator @classmethod.
Just for kicks and giggles, we could call myInstanceMethod on the class by passing in an instance of the class, like so:
>>> MyClass.myInstanceMethod(MyClass())
output from an instance method
You can use UNION ALL instead.
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.MainTable AS mt
Union ALL
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.OtherTable AS ot
For me follwing steps helped.
It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:
File ? Settings ? Experimental ? Gradle ? Only sync the active variant
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
// 1. Use if for see that classes:_x000D_
_x000D_
if (document.querySelector(".section-name").classList.contains("section-filter")) {_x000D_
alert("Grid section");_x000D_
// code..._x000D_
}
_x000D_
<!--2. Add a class in the .html:-->_x000D_
_x000D_
<div class="section-name section-filter">...</div>
_x000D_
Padding is a way to add kind of a margin inside the Div.
Just Use
div { padding-left: 20px; }
And to mantain the size, you would have to -20px from the original width of the Div.
You may try something like;
<p><input type="radio" id="oddsPref" name="oddsPref" value="decimal" /><span>Decimal</span></p>
and give the span a margin top like;
span{
margin-top: 4px;
position:absolute;
}
here is the fiddle http://jsfiddle.net/UnA6j/11/
You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write()
:
html_str = """
<table border=1>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
<indent>
<% for i in range(10): %>
<tr>
<td><%= i %></td>
<td><%= i**2 %></td>
</tr>
</indent>
</table>
"""
Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()
my result looks like this:
public static async Task<string> Upload(byte[] image)
{
using (var client = new HttpClient())
{
using (var content =
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");
using (
var message =
await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
{
var input = await message.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
}
}
}
}
May be you are using wrong mysql_connector.
Use connector of same mysql version
Try setting C_INCLUDE_PATH
(for C header files) or CPLUS_INCLUDE_PATH
(for C++ header files).
As Ciro mentioned, CPATH
will set the path for both C and C++ (and any other language).
More details in GCC's documentation.
As you probably understood from previous answers, you can't really do what you're after. I think you can understand the problem SQL Server is experiencing with not knowing how to map the additional/missing columns.
That said, since you mention that the purpose of what you're trying to here is backup, maybe we can work with SQL Server and workaround the issue. Not knowing your exact scenario makes it impossible to hit with a right answer here, but I assume the following:
I wish to suggest two options for you:
The efficient practice (IMO) for this can be to detect schema changes using DDL triggers and use them to alter the backup table accordingly. This will enable you to use the 'select * from...' approach, because the column list will be consistent between the two tables.
I have used this approach successfully and you can leverage it to have DDL triggers automatically manage your auditing tables. In my case, I used a naming convention for a table requiring audits and the DDL trigger just managed it on the fly.
Another option that might be useful for your specific scenario is to create a supporting view for the tables aligning the column list. Here's a quick example:
create table foo (id int, name varchar(50))
create table foo_bk (id int, name varchar(50), tagid int)
go
create view vw_foo as select id,name from foo
go
create view vw_foo_bk as select id,name from foo_bk
go
insert into vw_foo
select * from vw_foo_bk
go
drop view vw_foo
drop view vw_foo_bk
drop table foo
drop table foo_bk
go
I hope this helps :)
Using jQuery:
$('#test').hide();
Using Javascript:
document.getElementById("test").style.display="none";
Threw an error "Cannot set property 'display' of undefined"
So, fix for this would be:
document.getElementById("test").style="display:none";
where your html code will look like this:
<div style="display:inline-block" id="test"></div>
here's a regex one for ya.
update table
set col1=null
where col1 not like '%[a-z,0-9]%'
essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.
I believe putty has a maximum number of columns you can specify for the window.
For Windows I personally use Windows PowerShell and set the screen buffer width reasonably high. The column width remains fixed and you can use a horizontal scroll bar to see the data. I had the same problem you're having now.
edit: For remote hosts that you have to SSH into you would use something like plink + Windows PowerShell
Usually timestamp has no timezone.
% irb
> Time.now.to_i == Time.now.getutc.to_i
=> true
I created a jQuery version of PhpMyCoder's answer:
$('form').submit(function( e ) {
if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
//Prevent default and display error
alert("File is wrong type or over 10Mb in size!");
e.preventDefault();
}
});
function get_extension(filename) {
return filename.split('.').pop().toLowerCase();
}
looks like a Chrome bug, i did something else as i almost got crazy because of this... using Chrom debugger if you change the css of the svg object it shows on the screen.
so what i did was: 1. check for screen size 2. listen to the "load" event of my SVG object 3. when the element is loaded i change its css using jQuery 4. it did the trick for me
if (jQuery(window).width() < 769) {_x000D_
_x000D_
jQuery('object#mysvg-logo')[0].addEventListener('load', function() {_x000D_
jQuery("object#mysvg-logo").css('width','181px');_x000D_
}, true);_x000D_
_x000D_
}
_x000D_
width: 180px;
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<object id="mysvg-logo" type="image/svg+xml" data="my svg logo url here">Your browser does not support SVG</object>
_x000D_
User1's example worked well for me. But, as a warning, it won't work with anything other than simple String/Integer types, unless you add an @XmlSeeAlso annotation:
@XmlRootElement(name = "List")
@XmlSeeAlso(MovieTicket.class)
public class MovieTicketList {
protected List<MovieTicket> list;
This works OK, although it prevents me from using a single generic list class across my entire application. It might also explain why this seemingly obvious class doesn't exist in the JAXB package.
Here is a code sample I've used (with a .NET Core view):
@{
Microsoft.Extensions.Primitives.StringValues queryVal;
if (Context.Request.Query.TryGetValue("yourKey", out queryVal) &&
queryVal.FirstOrDefault() == "yourValue")
{
}
}
This is basically Muhammad Saqib's answer except two diffs:
1: Adds width and height function parameters.
2: This is a small nuance which can be ignored... Saying 'As Bitmap', instead of 'As Image'. 'As Image' does work just fine. I just prefer to match Return
types. See Image VS Bitmap Class.
Public Shared Function ResizeImage(ByVal InputBitmap As Bitmap, width As Integer, height As Integer) As Bitmap
Return New Bitmap(InputImage, New Size(width, height))
End Function
Ex.
Dim someimage As New Bitmap("C:\somefile")
someimage = ResizeImage(someimage,800,600)
Removing float
s, and using inline-block
may fix your problems:
.pagination a {
- display: block;
+ display: inline-block;
width: 30px;
height: 30px;
- float: left;
margin-left: 3px;
background: url(/images/structure/pagination-button.png);
}
(remove the lines starting with -
and add the lines starting with +
.)
.pagination {_x000D_
text-align: center;_x000D_
}_x000D_
.pagination a {_x000D_
+ display: inline-block;_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
margin-left: 3px;_x000D_
background: url(/images/structure/pagination-button.png);_x000D_
}_x000D_
.pagination a.last {_x000D_
width: 90px;_x000D_
background: url(/images/structure/pagination-button-last.png);_x000D_
}_x000D_
.pagination a.first {_x000D_
width: 60px;_x000D_
background: url(/images/structure/pagination-button-first.png);_x000D_
}
_x000D_
<div class='pagination'>_x000D_
<a class='first' href='#'>First</a>_x000D_
<a href='#'>1</a>_x000D_
<a href='#'>2</a>_x000D_
<a href='#'>3</a>_x000D_
<a class='last' href='#'>Last</a>_x000D_
</div>_x000D_
<!-- end: .pagination -->
_x000D_
inline-block
works cross-browser, even on IE6 as long as the element is originally an inline element.
Quote from quirksmode:
An inline block is placed inline (ie. on the same line as adjacent content), but it behaves as a block.
this often can effectively replace floats:
The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.” ( http://www.quirksmode.org/css/display.html#inlineblock ).
From the W3C spec:
[inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.
Try with Contains
function;
Determines whether a sequence contains a specified element.
var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
There are at least three places where you may find shared_ptr
:
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr
), then std::shared_ptr
will be defined in <memory>
.
If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr
will likely be in <memory>
(Microsoft Visual C++) or <tr1/memory>
(g++'s libstdc++). Boost also provides a TR1 implementation that you can use.
Otherwise, you can obtain the Boost libraries and use boost::shared_ptr
, which can be found in <boost/shared_ptr.hpp>
.
This depends on the shell you prefer to use.
If you are using the cmd shell on Windows then the following should work:
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"
If you are using a bash or zsh type shell (such as git bash or babun on Windows or most Linux / OS X shells) then this is a much nicer, more succinct way to do what you want:
find . -iname "bin" | xargs rm -rf
find . -iname "obj" | xargs rm -rf
and this can be reduced to one line with an OR:
find . -iname "bin" -o -iname "obj" | xargs rm -rf
Note that if your directories of filenames contain spaces or quotes, find will send those entries as-is, which xargs may split into multiple entries. If your shell supports them, -print0
and -0
will work around this short-coming, so the above examples become:
find . -iname "bin" -print0 | xargs -0 rm -rf
find . -iname "obj" -print0 | xargs -0 rm -rf
and:
find . -iname "bin" -o -iname "obj" -print0 | xargs -0 rm -rf
If you are using Powershell then you can use this:
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
as seen in Robert H's answer below - just make sure you give him credit for the powershell answer rather than me if you choose to up-vote anything :)
It would of course be wise to run whatever command you choose somewhere safe first to test it!
This code works very fast. It comes from here
Option Explicit
Private Const clOneMask = 16515072 '000000 111111 111111 111111
Private Const clTwoMask = 258048 '111111 000000 111111 111111
Private Const clThreeMask = 4032 '111111 111111 000000 111111
Private Const clFourMask = 63 '111111 111111 111111 000000
Private Const clHighMask = 16711680 '11111111 00000000 00000000
Private Const clMidMask = 65280 '00000000 11111111 00000000
Private Const clLowMask = 255 '00000000 00000000 11111111
Private Const cl2Exp18 = 262144 '2 to the 18th power
Private Const cl2Exp12 = 4096 '2 to the 12th
Private Const cl2Exp6 = 64 '2 to the 6th
Private Const cl2Exp8 = 256 '2 to the 8th
Private Const cl2Exp16 = 65536 '2 to the 16th
Public Function Encode64(sString As String) As String
Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long
For lTemp = 0 To 63 'Fill the translation table.
Select Case lTemp
Case 0 To 25
bTrans(lTemp) = 65 + lTemp 'A - Z
Case 26 To 51
bTrans(lTemp) = 71 + lTemp 'a - z
Case 52 To 61
bTrans(lTemp) = lTemp - 4 '1 - 0
Case 62
bTrans(lTemp) = 43 'Chr(43) = "+"
Case 63
bTrans(lTemp) = 47 'Chr(47) = "/"
End Select
Next lTemp
For lTemp = 0 To 255 'Fill the 2^8 and 2^16 lookup tables.
lPowers8(lTemp) = lTemp * cl2Exp8
lPowers16(lTemp) = lTemp * cl2Exp16
Next lTemp
iPad = Len(sString) Mod 3 'See if the length is divisible by 3
If iPad Then 'If not, figure out the end pad and resize the input.
iPad = 3 - iPad
sString = sString & String(iPad, Chr(0))
End If
bIn = StrConv(sString, vbFromUnicode) 'Load the input string.
lLen = ((UBound(bIn) + 1) \ 3) * 4 'Length of resulting string.
lTemp = lLen \ 72 'Added space for vbCrLfs.
lOutSize = ((lTemp * 2) + lLen) - 1 'Calculate the size of the output buffer.
ReDim bOut(lOutSize) 'Make the output buffer.
lLen = 0 'Reusing this one, so reset it.
For lChar = LBound(bIn) To UBound(bIn) Step 3
lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2) 'Combine the 3 bytes
lTemp = lTrip And clOneMask 'Mask for the first 6 bits
bOut(lPos) = bTrans(lTemp \ cl2Exp18) 'Shift it down to the low 6 bits and get the value
lTemp = lTrip And clTwoMask 'Mask for the second set.
bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12) 'Shift it down and translate.
lTemp = lTrip And clThreeMask 'Mask for the third set.
bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6) 'Shift it down and translate.
bOut(lPos + 3) = bTrans(lTrip And clFourMask) 'Mask for the low set.
If lLen = 68 Then 'Ready for a newline
bOut(lPos + 4) = 13 'Chr(13) = vbCr
bOut(lPos + 5) = 10 'Chr(10) = vbLf
lLen = 0 'Reset the counter
lPos = lPos + 6
Else
lLen = lLen + 4
lPos = lPos + 4
End If
Next lChar
If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.
If iPad = 1 Then 'Add the padding chars if any.
bOut(lOutSize) = 61 'Chr(61) = "="
ElseIf iPad = 2 Then
bOut(lOutSize) = 61
bOut(lOutSize - 1) = 61
End If
Encode64 = StrConv(bOut, vbUnicode) 'Convert back to a string and return it.
End Function
Public Function Decode64(sString As String) As String
Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
Dim lTemp As Long
sString = Replace(sString, vbCr, vbNullString) 'Get rid of the vbCrLfs. These could be in...
sString = Replace(sString, vbLf, vbNullString) 'either order.
lTemp = Len(sString) Mod 4 'Test for valid input.
If lTemp Then
Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
End If
If InStrRev(sString, "==") Then 'InStrRev is faster when you know it's at the end.
iPad = 2 'Note: These translate to 0, so you can leave them...
ElseIf InStrRev(sString, "=") Then 'in the string and just resize the output.
iPad = 1
End If
For lTemp = 0 To 255 'Fill the translation table.
Select Case lTemp
Case 65 To 90
bTrans(lTemp) = lTemp - 65 'A - Z
Case 97 To 122
bTrans(lTemp) = lTemp - 71 'a - z
Case 48 To 57
bTrans(lTemp) = lTemp + 4 '1 - 0
Case 43
bTrans(lTemp) = 62 'Chr(43) = "+"
Case 47
bTrans(lTemp) = 63 'Chr(47) = "/"
End Select
Next lTemp
For lTemp = 0 To 63 'Fill the 2^6, 2^12, and 2^18 lookup tables.
lPowers6(lTemp) = lTemp * cl2Exp6
lPowers12(lTemp) = lTemp * cl2Exp12
lPowers18(lTemp) = lTemp * cl2Exp18
Next lTemp
bIn = StrConv(sString, vbFromUnicode) 'Load the input byte array.
ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1) 'Prepare the output buffer.
For lChar = 0 To UBound(bIn) Step 4
lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3)) 'Rebuild the bits.
lTemp = lQuad And clHighMask 'Mask for the first byte
bOut(lPos) = lTemp \ cl2Exp16 'Shift it down
lTemp = lQuad And clMidMask 'Mask for the second byte
bOut(lPos + 1) = lTemp \ cl2Exp8 'Shift it down
bOut(lPos + 2) = lQuad And clLowMask 'Mask for the third byte
lPos = lPos + 3
Next lChar
sOut = StrConv(bOut, vbUnicode) 'Convert back to a string.
If iPad Then sOut = Left$(sOut, Len(sOut) - iPad) 'Chop off any extra bytes.
Decode64 = sOut
End Function
Use the %r
for debugging, since it displays the "raw" data of the variable,
but the others are used for displaying to users.
That's how %r
formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n
used to display to users doesn't work. %r
shows the representation if the raw data of the variable.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months
Output:
Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
Check this example from Learn Python the Hard Way.
Another way :
change BOT_USER_NAME before use
https://telegram.me/BOT_USER_NAME?startgroup=true
If you want to select every element that has class attribute "myclass" use
$('#mydiv .myclass');
If you want to select only div elements that has class attribute "myclass" use
$("div#mydiv div.myclass");
find more about jquery selectors refer these articles
I solved this issue by extending the Preference class.
package com.example.android;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
public class VersionPreference extends Preference {
public VersionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
String versionName;
final PackageManager packageManager = context.getPackageManager();
if (packageManager != null) {
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = null;
}
setSummary(versionName);
}
}
}
Then in my preferences XML:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.example.android.VersionPreference android:title="Version" />
</PreferenceScreen>
Your DemoApplication
class is in the com.ag.digital.demo.boot
package and your LoginBean
class is in the com.ag.digital.demo.bean
package. By default components (classes annotated with @Component
) are found if they are in the same package or a sub-package of your main application class DemoApplication
. This means that LoginBean
isn't being found so dependency injection fails.
There are a couple of ways to solve your problem:
LoginBean
into com.ag.digital.demo.boot
or a sub-package.scanBasePackages
attribute of @SpringBootApplication
that should be on DemoApplication
.A few of other things that aren't causing a problem, but are not quite right with the code you've posted:
@Service
is a specialisation of @Component
so you don't need both on LoginBean
@RestController
is a specialisation of @Component
so you don't need both on DemoRestController
DemoRestController
is an unusual place for @EnableAutoConfiguration
. That annotation is typically found on your main application class (DemoApplication
) either directly or via @SpringBootApplication
which is a combination of @ComponentScan
, @Configuration
, and @EnableAutoConfiguration
.Here ya go - works just any other iterable:
d = {'param' : 'test'}
def f(dictionary):
for key in dictionary:
print key
f(d)
Following is a work-around:
Running the shortcut will execute your batch script as administrator.
One slow, dependable, old-school method that always works in every operating system with every language (and even between languages) is to write the "system/environment" data you need to a temporary text file, read it when you need it, and then erase it. Of course, if you're running in parallel, then you need unique names for the file, and if you're putting sensitive information in it, then you need to encrypt it.
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack
An even quicker/shorter solution is:
escaped = new Option(html).innerHTML
This is related to some weird vestige of JavaScript whereby the Option element retains a constructor that does this sort of escaping automatically.
You need mask
:
sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
Another solution with loc
and boolean indexing
:
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
Sample:
import pandas as pd
import numpy as np
sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
PR
0 10
1 100
2 40
sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
PR
0 NaN
1 100.0
2 NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
PR
0 NaN
1 100.0
2 NaN
EDIT:
Solution with apply
:
sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)
Timings len(df)=300k
:
sample = pd.concat([sample]*100000).reset_index(drop=True)
In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop
In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop
Here's a summary of different ways to do it, they will work for all these inputs:
"" => ""
"a b c" => "A B C"
"foO baR" => "FoO BaR"
"foo bar" => "Foo Bar"
"foo's bar" => "Foo's Bar"
"foo's1bar" => "Foo's1bar"
"foo 1bar" => "Foo 1bar"
- The simplest solution is to split the sentence into words and capitalize the first letter then join it back together:
# Be careful with multiple spaces, and empty strings
# for empty words w[0] would cause an index error,
# but with w[:1] we get an empty string as desired
def cap_sentence(s):
return ' '.join(w[:1].upper() + w[1:] for w in s.split(' '))
- If you don't want to split the input string into words first, and using fancy generators:
# Iterate through each of the characters in the string and capitalize
# the first char and any char after a blank space
from itertools import chain
def cap_sentence(s):
return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )
- Or without importing itertools:
def cap_sentence(s):
return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )
- Or you can use regular expressions, from steveha's answer:
# match the beginning of the string or a space, followed by a non-space
import re
def cap_sentence(s):
return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
Now, these are some other answers that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:
return s.title()
# Undesired outputs:
"foO baR" => "Foo Bar"
"foo's bar" => "Foo'S Bar"
"foo's1bar" => "Foo'S1Bar"
"foo 1bar" => "Foo 1Bar"
return ' '.join(w.capitalize() for w in s.split())
# or
import string
return string.capwords(s)
# Undesired outputs:
"foO baR" => "Foo Bar"
"foo bar" => "Foo Bar"
using ' ' for the split will fix the second output, but capwords() still won't work for the first
return ' '.join(w.capitalize() for w in s.split(' '))
# or
import string
return string.capwords(s, ' ')
# Undesired outputs:
"foO baR" => "Foo Bar"
Be careful with multiple blank spaces
return ' '.join(w[0].upper() + w[1:] for w in s.split())
# Undesired outputs:
"foo bar" => "Foo Bar"
Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:
>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}
You need to access image IDs using R.mipmap.yourImageName
There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,
If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN
, which can be used in conjunction with JPA CascadeType.ALL
.
If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.
execution sequence
With JPA 2.0, you can now use the option orphanRemoval = true
@OneToMany(mappedBy="foo", orphanRemoval=true)
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
ngAfterViewInit()
of AppComponent
is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.
if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.
-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.
I think that second thing is better because you give to java the automatic memory management.
If you need a formatted return String like "2 Days 03h 42m 07s", try this:
public String fill2(int value)
{
String ret = String.valueOf(value);
if (ret.length() < 2)
ret = "0" + ret;
return ret;
}
public String get_duration(Date date1, Date date2)
{
TimeUnit timeUnit = TimeUnit.SECONDS;
long diffInMilli = date2.getTime() - date1.getTime();
long s = timeUnit.convert(diffInMilli, TimeUnit.MILLISECONDS);
long days = s / (24 * 60 * 60);
long rest = s - (days * 24 * 60 * 60);
long hrs = rest / (60 * 60);
long rest1 = rest - (hrs * 60 * 60);
long min = rest1 / 60;
long sec = s % 60;
String dates = "";
if (days > 0) dates = days + " Days ";
dates += fill2((int) hrs) + "h ";
dates += fill2((int) min) + "m ";
dates += fill2((int) sec) + "s ";
return dates;
}
public enum Operator
{
PLUS, MINUS, MULTIPLY, DIVIDE
}
public class Calc
{
public void Calculate(int left, int right, Operator op)
{
switch (op)
{
case Operator.DIVIDE:
//Divide
break;
case Operator.MINUS:
//Minus
break;
case Operator.MULTIPLY:
//...
break;
case Operator.PLUS:
//;;
break;
default:
throw new InvalidOperationException("Couldn't process operation: " + op);
}
}
}
You can use this script to find dates between two dates. Reference taken from this Article:
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
SET @StartDateTime = '2015-01-01'
SET @EndDateTime = '2015-01-12';
WITH DateRange(DateData) AS
(
SELECT @StartDateTime as Date
UNION ALL
SELECT DATEADD(d,1,DateData)
FROM DateRange
WHERE DateData < @EndDateTime
)
SELECT DateData
FROM DateRange
OPTION (MAXRECURSION 0)
GO
As mentioned here, this feature is not currently supported.
First open Your cmd pannel And enter mysql -u root -p (And Hit Enter) After cmd ask's for mysql password (if you have mysql password so enter now and hit enter again) now type source mysqldata.sql(Hit Enter) Your database will import without any error
Just hit on this when trying to solve this type of thing my self.
I did a selector that deals with the element after being something other than a p.
.here .is.the #selector h4 + * {...}
Hope this helps anyone who finds it :)
For something a little more readable, run this command once:
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
so that when you then run:
git lg
you get a nice readout. To show only the last line:
git lg -1
Solution found here
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
I would first try resetting all Visual Studio settings (Tools > Import and Export Settings > Reset all settings), then go to the Resharper > Options > Keyboard & Menus and re-apply the keyboard shortcut scheme.
I had to do something similar once.
Perhaps the best way would be to implement your app as a web app. I think you can also make web apps that run direct on the phone, without internet access or a remote server.
Web app, sounds lame? But a lot can be done with DHTML / HTML5 / JavaScript. It's a rare app that requires more power and couldn't be done as a web app. And you get pretty good cross platform with Web / JavaScript - the browsers vary a bit but a good web dev can write one web app that works pretty much everywhere.
Of course if you're writing a high-performance 3D game, the browser might not deliver what you need! maybe in a few years... Apparently some Google hackers ported Quake 2 to HTML5 already!
http://web.appstorm.net/roundups/browsers/10-html5-games-paving-the-way/
If there is no possibility to remove or change path to a hard disc file using Virtual Media Manager (in my case) then:
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
while u write R
. you are referring to the R.java
class created by eclipse, use getResources().getString()
and pass the id
of the resource from which you are trying to read inside the getString()
method.
Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);
I recently got this error.
What worked for me is checking in the mysql workbench 'Users and Privileges' and realizing user still existed.
After deleting it from there, I was able to recreate the user.
You listen to the onerror event by assigning a function to window.onerror:
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
alert(msg, url, lineNo, columnNo, error);
}
return false;
};
I think table-cell
needs to have a parent display:table
element.
Go to view all content of the site (http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx). Select the document library "Pages" (the "Pages" library are named based on the language you created the site in. I.E. in norwegian the library is named "Sider"). Download the default.aspx to you computer and fix it (remove the web part and the <%Register tag). Save it and upload it back to the library (remember to check in the file).
EDIT:
ahh.. you are not using a publishing site template. Go to site action -> site settings. Under "site administration" select the menu "content and structure" you should now see your default.aspx page. But you cant do much with it...(delete, copy or move)
workaround: Enable publishing feature to the root web. Add the fixed default.aspx file to the Pages library and change the welcome page to this. Disable the publishing feature (this will delete all other list create from this feature but not the Pages library since one page is in use.). You will now have a new default.aspx page for the root web but the url is changed from sitename/default.aspx to sitename/Pages/default.aspx.
workaround II Use a feature to change the default.aspx file. The solution is explained here: http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx
In a batch file solution
for /R c:\source %%f in (*.xml) do copy %%f x:\destination\
The code works as such;
for each file for
in directory c:\source
and subdirectories /R
that match pattern (\*.xml)
put the file name in variable %%f
, then for each file do
copy file copy %%f
to destination x:\\destination\\
Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f
variable name version, as described in the linked question above.
This is the JSON String we want to decode :
{
"stats": {
"sdr": "aa:bb:cc:dd:ee:ff",
"rcv": "aa:bb:cc:dd:ee:ff",
"time": "UTC in millis",
"type": 1,
"subt": 1,
"argv": [
{"1": 2},
{"2": 3}
]}
}
I store this string under the variable name "sJSON" Now, this is how to decode it :)
// Creating a JSONObject from a String
JSONObject nodeRoot = new JSONObject(sJSON);
// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");
// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");
In my case, the service name was 'Monitor' which is also used by a windows service called 'Monitor', when I tried to update my services, I tried uninstalling them, the installer tried to remove the windows service 'Monitor' which it couldn't, and the installation was always rolled back.
I ended up renaming my service to something else
Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export
to force them to do so. Change:
test: NODE_ENV = test
to this:
test: export NODE_ENV = test
(assuming you have a sufficiently modern version of GNU make >= 3.77 ).
You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :
Now let's see how to make these fancy responsive squares!
The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom
.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.
As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :
HTML :
<div></div>
CSS
div {
width: 30%;
padding-bottom: 30%; /* = width for a square aspect ratio */
}
Here is a simple layout example of 3*3 squares grid using the code above.
With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.
Aspect ratio | padding-bottom | for 30% width
------------------------------------------------
1:1 | = width | 30%
1:2 | width x 2 | 60%
2:1 | width x 0.5 | 15%
4:3 | width x 0.75 | 22.5%
16:9 | width x 0.5625 | 16.875%
As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute;
and put the content inside them. This will take the content out of the flow and keep the size of the square.
Don't forget to add position:relative;
on the parent divs so the absolute children are positioned/sized relatively to their parent.
Let's add some content to our 3x3 grid of squares :
HTML :
<div class="square">
<div class="content">
.. CONTENT HERE ..
</div>
</div>
... and so on 9 times for 9 squares ...
CSS :
.square {
float:left;
position: relative;
width: 30%;
padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
RESULT <-- with some formatting to make it pretty!
Horizontally :
This is pretty easy, you just need to add text-align:center
to .content
.
RESULT
Vertical alignment
This becomes serious! The trick is to use
display:table;
/* and */
display:table-cell;
vertical-align:middle;
but we can't use display:table;
on .square
or .content
divs because it conflicts with position:absolute;
so we need to create two children inside .content
divs. Our code will be updated as follow :
HTML :
<div class="square">
<div class="content">
<div class="table">
<div class="table-cell">
... CONTENT HERE ...
</div>
</div>
</div>
</div>
... and so on 9 times for 9 squares ...
CSS :
.square {
float:left;
position: relative;
width: 30%;
padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
.table{
display:table;
height:100%;
width:100%;
}
.table-cell{
display:table-cell;
vertical-align:middle;
height:100%;
width:100%;
}
We have now finished and we can take a look at the result here :
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
For testing on a device, you can connect the device using USB and run from Eclipse just as an emulator.
If you need to distribute the app, then use the export feature:
Then follow instructions. You will have to create a key in the process.
It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
So, I agree in two points:
(A.) Yes, in many times a better design can avoid it; BUT
(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.
Yes, you can get your project back. Just rename the yourproject.apk
file to yourproject.zip
, and you will get all the files inside that ZIP file. We are changing the file extension from .apk to .zip. From that ZIP file, extract the classes.dex
file and decompile it by following way.
First, you need a tool to extract all the (compiled) classes on the DEX to a JAR. There's one called dex2jar, which is made by a Chinese student.
Then, you can use JD-GUI to decompile the classes in the JAR to source code. The resulting source code should be quite readable, as dex2jar applies some optimizations.
Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.
/^(7|8|9)\d{9}$/
What this does:
^
and $
denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.()
denotes a capturing group.7|8|9
denotes matching either of 7
, 8
, or 9
. It does this with alternations, which is what the pipe operator |
does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:Pattern: (r|f)at
Match string: carat
Pattern: [rf]at
Match string: carat
\d{9}
matches nine digits. \d
is a shorthanded metacharacter, which matches any digits./^[7|8|9][\d]{9}$/
Look at what it does:
^
and $
denotes anchored matches as well.[7|8|9]
is a character class. Any characters from the list 7
, |
, 8
, |
, or 9
can be matched, thus the |
was added in incorrectly. This matches without backtracking.[\d]
is a character class that inhabits the metacharacter \d
. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.{9}
indicates the previous single construct is repeated nine times in total.The optimal regex is /^[789]\d{9}$/
, because /^(7|8|9)\d{9}$/
captures unnecessarily which imposes a performance decrease on most regex implementations (javascript happens to be one, considering the question uses keyword var
in code, this probably is JavaScript). The use of php which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes []
instead of alternations |
gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.
One way:
set -- $(md5sum $file)
md5=$1
Another way:
md5=$(md5sum $file | while read sum file; do echo $sum; done)
Another way:
md5=$(set -- $(md5sum $file); echo $1)
(Do not try that with back-ticks unless you're very brave and very good with backslashes.)
The advantage of these solutions over other solutions is that they only invoke md5sum
and the shell, rather than other programs such as awk
or sed
. Whether that actually matters is then a separate question; you'd probably be hard pressed to notice the difference.
epoch is an iteration of subset of the samples for training, for example, the gradient descent algorithm in neutral network. A good reference is: http://neuralnetworksanddeeplearning.com/chap1.html
Note that the page has a code for the gradient descent algorithm which uses epoch
def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
"""Train the neural network using mini-batch stochastic
gradient descent. The "training_data" is a list of tuples
"(x, y)" representing the training inputs and the desired
outputs. The other non-optional parameters are
self-explanatory. If "test_data" is provided then the
network will be evaluated against the test data after each
epoch, and partial progress printed out. This is useful for
tracking progress, but slows things down substantially."""
if test_data: n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data)
mini_batches = [
training_data[k:k+mini_batch_size]
for k in xrange(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print "Epoch {0}: {1} / {2}".format(
j, self.evaluate(test_data), n_test)
else:
print "Epoch {0} complete".format(j)
Look at the code. For each epoch, we randomly generate a subset of the inputs for the gradient descent algorithm. Why epoch is effective is also explained in the page. Please take a look.
The OpenXSD library mentions that they have support for generating XML instances based on the XSD. Check that out.
Warning: this can introduce security issues that SSL is designed to protect against, rendering your entire codebase insecure. It goes against every recommended practice.
But a really simple fix that worked for me was to call:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
before calling:
curl_exec():
in the php file.
I believe that this disables all verification of SSL certificates.
Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:
array.length * array[0].length
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.
You need to convert the object into an array to use the map
function:
const mad = Object.values(this.props.location.state);
where this.props.location.state
is the passed object into another component.
Just to expand on the previous answer colorRampPalette
can handle more than two colors.
So for a more expanded "heat map" type look you can....
colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)
The resulting image:
I solved it using the LOCAL
option in the command:
LOAD DATA LOCAL INFILE "text.txt" INTO TABLE mytable;
You can find more info here.
If LOCAL is specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full path name to specify its exact location. If given as a relative path name, the name is interpreted relative to the directory in which the client program was started.
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
Try to enter the full-path of the dll. If it doesn't work, try to copy the dll into the system32 folder.
It's so easy, man. Just press on the power button until you see the "Phone Options" screen and turn on mobile data. After that you can sign into your account or remotely unlock your device.
Approch used by me is similar to Gary Beardsley mentioned above with small change.
Filename: Server.py
import os, sys
script_path = os.path.realpath(os.path.dirname(__name__))
os.chdir(script_path)
sys.path.append("..")
# above mentioned steps will make 1 level up module available for import
# here Client, Server and Common all 3 can be imported.
# below mentioned import will be relative to root project
from Common import Common
from Client import Client
I finally pasted my jar file into the same folder as my JDK so I didn't have to include the paths. I also had to open the command prompt as an admin.
java.exe -jar <jar file name>.jar
You can use theme_get()
to display the possible options for theme.
You can control the legend font size using:
+ theme(legend.text=element_text(size=X))
replacing X with the desired size.
To access an array member you use $array['KEY'];
To access an object member you use $obj->KEY;
To access an object member inside an array of objects:
$array[0]
// Get the first object in the array
$array[0]->KEY
// then access its key
You may also loop over an array of objects like so:
foreach ($arrayOfObjs as $key => $object) {
echo $object->object_property;
}
Think of an array as a collection of things. It's a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here, but this bag can contain other bags too :)
An array contains 'key
' and 'value
' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key
'.
So we can define an array in the following ways (with respect to keys):
$colorPallete = ['red', 'blue', 'green'];
The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.
$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'
$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.
$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'
A third option, for a pipelined one-liner is to nest the -replaces:
PS> ("ABC" -replace "B","C") -replace "C","D"
ADD
And:
PS> ("ABC" -replace "C","D") -replace "B","C"
ACD
This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?
-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.
Please see:
help about_operators
Another way of solving this, extending from Vaclav's answer to solve this particular calculation — i.e. a calculation on each row.
.filter('total', function () {
return function (input, property) {
var i = input instanceof Array ? input.length : 0;
if (typeof property === 'undefined' || i === 0) {
return i;
} else if (typeof property === 'function') {
var total = 0;
while (i--)
total += property(input[i]);
return total;
} else if (isNaN(input[0][property])) {
throw 'filter total can count only numeric values';
} else {
var total = 0;
while (i--)
total += input[i][property];
return total;
}
};
})
To do this with a calculation, just add a calculation function to your scope, e.g.
$scope.calcItemTotal = function(v) { return v.price*v.quantity; };
You would use {{ datas|total:calcItemTotal|currency }}
in your HTML code. This has the advantage of not being called for every digest, because it uses filters, and can be used for simple or complex totals.
This may be a case where debugging the debugger might be useful. Essentially if you follow the instructions here you can run two ide's and one will debug into the other. If you un your application in one, you can sometimes catch errors that you otherwise miss. Its worth a try.
In order to do the database style ComboBoxes manually trying to setup a relationship between a number (internal) and some text (visible), I've found you have to:
First things first. Change your KeyValuePair to so it looks like:
(0,"Select") (1,"Option 1")
Now, when you run your sql "Select empstatus from employees where blah" and get back an integer, you need to set the combobox without wasting a bunch of time.
Simply: *** SelectedVALUE - not Item ****
cmbEmployeeStatus.SelectedValue = 3; //or
cmbEmployeeStatus.SelectedValue = intResultFromQuery;
This will work whether you have manually loaded the combobox with code values, as you did, or if you load the comboBox from a query.
If your foreign keys are integers, (which for what I do, they all are), life is easy. After the user makes the change to the comboBox, the value you will store in the database is SelectedValue. (Cast to int as needed.)
Here is my code to set the ComboBox to the value from the database:
if (t is DBInt) //Typical for ComboBox stuff
{
cb.SelectedValue = ((DBInt)t).value;
}
And to retrieve:
((DBInt)t).value = (int) cb.SelectedValue;
DBInt is a wrapper for an Integer, but this is part of my ORM that gives me manual control over databinding, and reduces code errors.
Why did I answer this so late? I was struggling with this also, as there seems to be no good info on the web about how to do this. I figured it out, and thought I'd be nice and post it for someone else to see.
You can use addition to concatenate strings.
Strings are added by being joined into a larger string.
jq '.users[] | .first + " " + .last'
The above works when both first
and last
are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.
jq '.users[] | .first + " " + (.number|tostring)'
Import your library project to Intellij from Eclipse project (this step only applies if you created your library in Eclipse).
Right click on module and choose Open Module Settings.
Setup libraries of v7 jar file
Setup library module of v7
Setup app module dependency of v7 library module
if not (line.startswith("OK ") or line.strip() == "."):
print line
var root = document.createElement("div");
root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var texts = [].map.call( root.querySelectorAll("b"), function(v){
return v.textContent || v.innerText || "";
});
//["Bob", "20", "programming"]
//VC6.0 (386 & better)
__int64 my_qw_var = 0x1234567890abcdef;
__int32 v_dw_h;
__int32 v_dw_l;
__asm
{
mov eax,[dword ptr my_qw_var + 4] //dwh
mov [dword ptr v_dw_h],eax
mov eax,[dword ptr my_qw_var] //dwl
mov [dword ptr v_dw_l],eax
}
//Oops 0.8 format
printf("val = 0x%0.8x%0.8x\n", (__int32)v_dw_h, (__int32)v_dw_l);
Regards.
Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop
for (var key in catalog){
document.getElementById(key).my_id = key
document.getElementById(key).addEventListener('click', function(e) {
editorContent.loadCatalogEntry(e.srcElement.my_id)
}, false);
}
It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers
I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D
Try this:
@RequestBody(required = false) String str
You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().
tar -zcvf compressFileName.tar.gz folderToCompress
everything in folderToCompress will go to compressFileName
Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName
I doubt for Keys.TAB
in sendKeys
method... if you want to use TAB you need to do something like below:
Actions builder = new Actions(driver);
builder.keyDown(Keys.TAB).perform()
The simplest thing to do is:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
In some cases you need a deep merge, i.e., merge the contents of fields with identical names (just like when copying folders in Windows). This function may be helpful:
/**
* Merge "source" into "target". If fields have equal name, merge them recursively.
* @return the merged object (target).
*/
public static JSONObject deepMerge(JSONObject source, JSONObject target) throws JSONException {
for (String key: JSONObject.getNames(source)) {
Object value = source.get(key);
if (!target.has(key)) {
// new value for "key":
target.put(key, value);
} else {
// existing value for "key" - recursively deep merge:
if (value instanceof JSONObject) {
JSONObject valueJson = (JSONObject)value;
deepMerge(valueJson, target.getJSONObject(key));
} else {
target.put(key, value);
}
}
}
return target;
}
/**
* demo program
*/
public static void main(String[] args) throws JSONException {
JSONObject a = new JSONObject("{offer: {issue1: value1}, accept: true}");
JSONObject b = new JSONObject("{offer: {issue2: value2}, reject: false}");
System.out.println(a+ " + " + b+" = "+JsonUtils.deepMerge(a,b));
// prints:
// {"accept":true,"offer":{"issue1":"value1"}} + {"reject":false,"offer":{"issue2":"value2"}} = {"reject":false,"accept":true,"offer":{"issue1":"value1","issue2":"value2"}}
}
To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,
CREATE TABLE [dbo].[User]
(
[Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
)
This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.
I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!
Better to first compress catalog on remote server:
tar czfP backup.tar.gz /path/to/catalog
Secondly, download from remote:
scp [email protected]:/path/to/backup.tar.gz .
At the end, extract the files:
tar -xzvf backup.tar.gz
Following is the list of conversion characters that you may use in the printf:
%d – for signed decimal integer
%f – for the floating point
%o – octal number
%c – for a character
%s – a string
%i – use for integer base 10
%u – for unsigned decimal number
%x – hexadecimal number
%% – for writing % (percentage)
%n – for new line = \n
You can use the Series.to_list
method.
For example:
import pandas as pd
df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})
print(df['a'].to_list())
Output:
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
To drop duplicates you can do one of the following:
>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]
I found it so much easier to do this:
1) Edit the frame to have the content inside (with 9patch tool).
2) Place the ImageView
inside a Linearlayout
, and set the frame background or colour you want as the background of the Linearlayout
. As you set the frame to have the content inside itself, your ImageView
will be inside the frame (right where you set the content with the 9patch tool).
For Win7 Acrobat Pro X
Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.
FYI: Below is the order in which I stepped through the repair.
Go to Control Panel
> folders options under each of the General
, View
and Search
Tabs
click the Restore Defaults
button and the Reset Folders
button
Go to Internet Explorer
, Tools
> Options
> Advanced
> Reset
( I did not need to delete personal settings)
Open Acrobat Pro X
, under Edit
> Preferences
> General
.
At the bottom of page select Default PDF Handler
. I chose Adobe Pro X
, and click Apply
.
You may be asked to reboot (I did).
Best Wishes
This may not help at all, but if you're using clang you can use the overloadable attribute - This works even when compiling as C
http://clang.llvm.org/docs/AttributeReference.html#overloadable
Header
extern void DecodeImageNow(CGImageRef image, CGContextRef usingContext) __attribute__((overloadable));
extern void DecodeImageNow(CGImageRef image) __attribute__((overloadable));
Implementation
void __attribute__((overloadable)) DecodeImageNow(CGImageRef image, CGContextRef usingContext { ... }
void __attribute__((overloadable)) DecodeImageNow(CGImageRef image) { ... }
It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
For Some reason it is not working so we can do this by another way
just remove the line and add this :-
<a onclick="window.open ('http://www.foracure.org.au', ''); return false" href="javascript:void(0);"></a>
Good luck.
Go here and download and unzip to an easy location:
http://developer.android.com/sdk/win-usb.html#top Download and install
Use Python's json module, or simplejson if you don't have python 2.6 or higher.
"Stack Me 123 Heppa1 oeu".toCharArray()
?
just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:
static void Name_pairs::read_names()
{
cout << "Enter name: ";
cin >> name;
names.push_back(name);
cout << endl;
}
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
Haven't you heard about the Comparable
interface being implemented by String
? If no, try to use
"abcda".compareTo("abcza")
And it will output a good root for a solution to your problem.
When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe
You can do it using:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
In case if your frameId is dynamic, and you only have one iframe, you can use something like:
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));