It says
Cannot find module 'express'
Do you have express installed? If not then run this.
npm install express
and run your program again.
As a side answer it's worth to note that:
aria-hidden
or aria-expanded
. But only if implemented and tested properly!I got the same error when i used the command source and gave the sql file path by drag n dropping it.
Then I just had to remove those single quotes which appeared by default with drag and drop, a space before file extension and it worked.
soln:
source /home/xyz/file .sql ;(path and a space before file extension)
Sometimes you want to:
Use @Column(name = "columnName", insertable = false, updatable = false)
A good scenario is when a certain column is automatically calculated by using other column values
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
go to package control by pressing Ctrl + Shift + p
type "remove package"
and type your package/plugin to uninstall and remove it
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
Install zip
sudo apt-get install zip
Zip your folder:
zip -r {filename.zip} {foldername}
Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.
I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z
format which offers superior compression ratios to traditional (PKZIP) *.zip
files:
Download 7-Zip from the 7-Zip home page
Add the path to 7z.exe
to your PATH
environment variable. See this QA:
How to set the path and environment variables in Windows
Open a new command-prompt window and use this command to create a PKZIP *.zip
file:
7z a -tzip {yourfile.zip} {yourfolder}
If you have the Java JDK installed then you can use the jar
utility to create Zip files, as *.jar
files are essentially just renamed *.zip
(PKZIP) files:
jar -cfM {yourfile.zip} {yourfolder}
Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file
For parseInt to work, your string should have only numerical data. Something like this:
str1 = "123.00";
str2 = "50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
Can you split the string before you start processing them for a total?
In Drupal 7, you can modify the memory limit in the settings.php file located in your sites/default folder. Around line 260, you'll see this:
ini_set('memory_limit', '128M');
Even if your php.ini settings are high enough, you won't be able to consume more than 128 MB if this isn't set in your Drupal settings.php file.
From the selectors specification:
Attribute values must be CSS identifiers or strings.
Identifiers cannot start with a number. Strings must be quoted.
1
is therefore neither a valid identifier nor a string.
Use "1"
(which is a string) instead.
var a = document.querySelector('a[data-a="1"]');
What I do is create a view that performs the same select as the table variable and link that view into the second view. So a view can select from another view. This achieves the same result
You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.
To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data
to an array before not after you try to slice it:
R = np.array(mean_data)[:,0]
instead of
R = np.array(mean_data[:,0])
But, assuming mean_data has a shape nx3
, instead of
R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]
You can simply do
A = np.array(mean_data).mean(axis=0)
which averages over the 0
th axis and returns a length-n
array
But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:
Let us assume:
then you really want to chop the files into parts, count parts in parallel on multiple nodes and sum up the results from there (this is basically @Chris White's idea).
Here is how you do that with GNU Parallel (version > 20161222). You need to list the nodes in ~/.parallel/my_cluster_hosts
and you must have ssh
access to all of them:
parwc() {
# Usage:
# parwc -l file
# Give one chunck per host
chunks=$(cat ~/.parallel/my_cluster_hosts|wc -l)
# Build commands that take a chunk each and do 'wc' on that
# ("map")
parallel -j $chunks --block -1 --pipepart -a "$2" -vv --dryrun wc "$1" |
# For each command
# log into a cluster host
# cd to current working dir
# execute the command
parallel -j0 --slf my_cluster_hosts --wd . |
# Sum up the number of lines
# ("reduce")
perl -ne '$sum += $_; END { print $sum,"\n" }'
}
Use as:
parwc -l myfile
parwc -w myfile
parwc -c myfile
Why do you use Restrictions.like(...
)?
You should use Restrictions.eq(...)
.
Note you can also use .le
, .lt
, .ge
, .gt
on date objects as comparison operators. LIKE
operator is not appropriate for this case since LIKE
is useful when you want to match results according to partial content of a column.
Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.
For example if you have a name column with some people's full name, you can do where name like 'robert %'
so that you will return all entries with name starting with 'robert '
(%
can replace any character).
In your case you know the full content of the date you're trying to match so you shouldn't use LIKE
but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...)
.
Your date object you got with the code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.
This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".
If you want to retrieve all entries of your database from a given day, you will have to use the following code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
// Create date 17-04-2011 - 00h00
Date minDate = formatter.parse(myDate);
// Create date 18-04-2011 - 00h00
// -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
Conjunction and = Restrictions.conjunction();
// The order date must be >= 17-04-2011 - 00h00
and.add( Restrictions.ge("orderDate", minDate) );
// And the order date must be < 18-04-2011 - 00h00
and.add( Restrictions.lt("orderDate", maxDate) );
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List< COrder > orders;
by default <UL/>
contains default padding
therefore try adding style to padding:0px
in css class or inline css
In order to use nslookup
, host
or gethostbyname()
then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.
You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?
I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.
Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.
The other answers are quite good, but it would also be useful to add LIMIT 1
(or the equivalent, to prevent the checking of unnecessary rows.
Ensures the path to Xcode.app bundle is without space or strange characters. I have Xcode installed in ~/Downloads/Last Dev Tools/ folder, so with spaces and renaming the folder to LastDevTools fixed this (after resetting xcode-select -p though)
This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6
repository. My repository was using jQuery 3
, but foundation requires an earlier version. I then changed it and it worked.
If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0"
.
Can you confirm that you are loading the correct version of jQuery?
I hope this helps.
Making a class abstract
sends a message to the readers of your code that you want users of your abstract
class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final
to disallow subclassing of your utility class.
Use dropna:
dat.dropna()
You can pass param how
to drop if all labels are nan or any of the labels are nan
dat.dropna(how='any') #to drop if any value in the row has a nan
dat.dropna(how='all') #to drop if all values in the row are nan
Hope that answers your question!
Edit 1:
In case you want to drop rows containing nan
values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:
dat.dropna(subset=[col_list]) # col_list is a list of column names to consider for nan values.
Alternatively, you can use the CHAR
function:
= "Maurice " & CHAR(34) & "Rocket" & CHAR(34) & " Richard"
The program is printing "Hey this is my first hello world "
, then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.
Removing Read-only CheckBox from C:\Users\SQL Service account name\AppData\Local\Temp
worked for me.
I would like to show you about how to color code. There is also a game to it if you would like to play it down below. Copy and paste if you would like and make sure to have a good day everyone! Also, this is for Python 3, not 2. ( Game )
# The Color Game!
# Thank you for playing this game.
# Hope you enjoy and please do not copy it. Thank you!
#
import colorama
from colorama import Fore
score = 0
def Check_Answer(answer):
if (answer == "no"):
print('correct')
return True
else:
print('wrong')
answer = input((Fore.RED + "This is green."))
if Check_Answer(answer) == True:
score = score + 1
else:
pass
answer = input((Fore.BLACK + "This is red."))
if Check_Answer(answer) == True:
score = score + 1
else:
pass
answer = input((Fore.BLUE + "This is black."))
if Check_Answer(answer) == True:
score = score + 1
else:
pass
print('Your Score is ', score)
Now for the color coding. It also comes with a list of colors YOU can try.
# Here is how to color code in Python 3!
# Some featured color codes are : RED, BLUE, GREEN, YELLOW, OR WHITE. I don't think purple or pink are not out yet.
# Here is how to do it. (Example is down below!)
import colorama
from colorama import Fore
print(Fore.RED + "This is red..")
Use jQuery
Look how easy it would be if you did.
Example:
$('#td1').html('hello world');
If there is a package.json
, and in it there is lodash
configuration in it. then you should:
npm install
if in the package.json
there is no lodash
:
npm install --save-dev
Be aware that if your string number contains more than 15 significant digits float(s)
will round it.In those cases it is better to use Decimal
Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info
Increment and decrement by 10.
require(Hmisc)
inc(x) <- 10
dec(x) <- 10
Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.
Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.
EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)
public class Job
{
public string id { get; set; }
public string position_title { get; set; }
public string organization_name { get; set; }
public string rate_interval_code { get; set; }
public int minimum { get; set; }
public int maximum { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public List<string> locations { get; set; }
public string url { get; set; }
}
And an edit to your code:
List<Job> model = null;
var client = new HttpClient();
var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);
});
task.Wait();
This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.
EDIT 2:
There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:
http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
I had this problem and couldn't solve it in Java code. The problem was with my xml.
I was trying to add a textView to a container, but had wrapped the textView inside a LinearLayout.
This was the original xml file:
<?xml version="1.0" encoding="utf-8"?>_x000D_
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:orientation="vertical"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent">_x000D_
_x000D_
<TextView xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:id="@android:id/text1"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceListItemSmall"_x000D_
android:gravity="center_vertical"_x000D_
android:paddingLeft="16dp"_x000D_
android:paddingRight="16dp"_x000D_
android:textColor="#fff"_x000D_
android:background="?android:attr/activatedBackgroundIndicator"_x000D_
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>_x000D_
_x000D_
</LinearLayout>
_x000D_
Now with the LinearLayout removed:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:id="@android:id/text1"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceListItemSmall"_x000D_
android:gravity="center_vertical"_x000D_
android:paddingLeft="16dp"_x000D_
android:paddingRight="16dp"_x000D_
android:textColor="#fff"_x000D_
android:background="?android:attr/activatedBackgroundIndicator"_x000D_
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
_x000D_
This didn't seem like much to me but it did the trick, and I didn't change my Java code at all. It was all in the xml.
Just for reference which functional interface can be used for method reference in cases method throws and/or returns a value.
void notReturnsNotThrows() {};
void notReturnsThrows() throws Exception {}
String returnsNotThrows() { return ""; }
String returnsThrows() throws Exception { return ""; }
{
Runnable r1 = this::notReturnsNotThrows; //ok
Runnable r2 = this::notReturnsThrows; //error
Runnable r3 = this::returnsNotThrows; //ok
Runnable r4 = this::returnsThrows; //error
Callable c1 = this::notReturnsNotThrows; //error
Callable c2 = this::notReturnsThrows; //error
Callable c3 = this::returnsNotThrows; //ok
Callable c4 = this::returnsThrows; //ok
}
interface VoidCallableExtendsCallable extends Callable<Void> {
@Override
Void call() throws Exception;
}
interface VoidCallable {
void call() throws Exception;
}
{
VoidCallableExtendsCallable vcec1 = this::notReturnsNotThrows; //error
VoidCallableExtendsCallable vcec2 = this::notReturnsThrows; //error
VoidCallableExtendsCallable vcec3 = this::returnsNotThrows; //error
VoidCallableExtendsCallable vcec4 = this::returnsThrows; //error
VoidCallable vc1 = this::notReturnsNotThrows; //ok
VoidCallable vc2 = this::notReturnsThrows; //ok
VoidCallable vc3 = this::returnsNotThrows; //ok
VoidCallable vc4 = this::returnsThrows; //ok
}
In CurrentGame
component you need to change initial state because you are trying use loop for participants
but this property is undefined
that's why you get error.,
getInitialState: function(){
return {
data: {
participants: []
}
};
},
also, as player
in .map
is Object
you should get properties from it
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
To use the strict ISO8601
, you can use the s
(Sortable) format string:
myDate.ToString("s"); // example 2009-06-15T13:45:30
It's a short-hand to this custom format string:
myDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
And of course, you can build your own custom format strings.
More info:
All these answers address the title question, but I wanted to propose some solutions for the problems presented in the body of the OP's question.
A quick way to calculate the size of the text inside the UITextView
is to use the NSLayoutManager
:
UITextView *textView;
CGSize textSize = [textView usedRectForTextContainer:textView.textContainer].size;
This gives the total scrollable content, which may be bigger than the UITextView
's frame. I found this to be much more accurate than textView.contentSize
since it actually calculates how much space the text takes up. For example, given an empty UITextView
:
textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)
UIFont
has a property that quickly allows you to get the line height for the given font. So you can quickly find the line height of the text in your UITextView
with:
UITextView *textView;
CGFloat lineHeight = textView.font.lineHeight;
Determining the amount of text that is actually visible is important for handling a "paging" effect. UITextView
has a property called textContainerInset
which actually is a margin between the actual UITextView.frame
and the text itself. To calculate the real height of the visible frame you can perform the following calculations:
UITextView *textView;
CGFloat textViewHeight = textView.frame.size.height;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textHeight = textViewHeight - textInsets.top - textInsets.bottom;
Lastly, now that you have the visible text size and the content, you can quickly determine what your offsets should be by subtracting the textHeight
from the textSize
:
// where n is the page number you want
CGFloat pageOffsetY = textSize - textHeight * (n - 1);
textView.contentOffset = CGPointMake(textView.contentOffset.x, pageOffsetY);
// examples
CGFloat page1Offset = 0;
CGFloat page2Offset = textSize - textHeight
CGFloat page3Offset = textSize - textHeight * 2
Using all of these methods, I didn't touch my insets and I was able to go to the caret or wherever in the text that I want.
add a float property to the #main_content
div - it will then expand to contain its floated contents
Fastest way is to use MySQL bulk loader by "load data infile" statement. It is the fastest way by far than any way you can come up with in Python. If you have to use Python, you can call statement "load data infile" from Python itself.
How is the HashMap declaration expressed in that scope? It should be:
HashMap<String, ArrayList> dictMap
If not, it is assumed to be Objects.
For instance, if your code is:
HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);
that will not work. Instead you want:
HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);
The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the Generics documentation.
Also note that ArrayList
is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your ArrayList
contains your class MyClass
, the line above might be:
HashMap<String, ArrayList<MyClass>> dictMap
You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.
Here's how you could do it with vanilla JavaScript:
<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>
Keycode 13 is the enter key.
Here's how you could do it with jQuery like as Stackoverflow does:
<textarea class="commentarea"></textarea>
with
$(document).ready(function() {
$('.commentarea').keydown(function(event) {
if (event.which == 13) {
this.form.submit();
event.preventDefault();
}
});
});
for names not present in the working copy or repo:
echo /globpattern >> .gitignore
or for an existing file (sh type command line):
echo /$(ls -1 file) >> .gitignore # I use tab completion to select the file to be ignored
git rm -r --cached file # if already checked in, deletes it on next commit
import {Keyboard} from 'react-native';
use Keyboard.dismiss()
to hide your keyboard in any onClick or onPress event.
' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")
' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close
' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
Line = File.ReadLine
WScript.Echo(Line)
Loop
File.Close
' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
});
}
To take the definitions the other mentioned earlier a bit further, how about this perspective...
LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).
There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).
LDAP is just a very lightweight DAP, as the name suggests.
Make sure that the actual .vim
file is in ~/.vim/plugin/
The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.
grep '^[-d]rwx.*[0-9]$' "$@"
See: Regular Expressions and grep for POSIX-standard details.
If you have a value and want to find the key, use array_search()
like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key
will now contain the key for value 'a'
(that is, 'first'
).
For ListFragment use
getListView().setDivider(null)
after the list has been obtained.
preg_split
the variable containing the text, and iterate over the returned array:
foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
// do stuff with $line
}
Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:
// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
.setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();
This implementation wrap entity exception to exception with detail text.
It handles DbEntityValidationException
, DbUpdateException
, datetime2
range errors (MS SQL), and include key of invalid entity in message (useful when savind many entities at one SaveChanges
call).
First, override SaveChanges
in DbContext class:
public class AppDbContext : DbContext
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException dbEntityValidationException)
{
throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
}
catch (DbUpdateException dbUpdateException)
{
throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
}
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
try
{
return await base.SaveChangesAsync(cancellationToken);
}
catch (DbEntityValidationException dbEntityValidationException)
{
throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
}
catch (DbUpdateException dbUpdateException)
{
throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
}
}
ExceptionHelper class:
public class ExceptionHelper
{
public static Exception CreateFromEntityValidation(DbEntityValidationException ex)
{
return new Exception(GetDbEntityValidationMessage(ex), ex);
}
public static string GetDbEntityValidationMessage(DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
return exceptionMessage;
}
public static IEnumerable<Exception> GetInners(Exception ex)
{
for (Exception e = ex; e != null; e = e.InnerException)
yield return e;
}
public static Exception CreateFromDbUpdateException(DbUpdateException dbUpdateException)
{
var inner = GetInners(dbUpdateException).Last();
string message = "";
int i = 1;
foreach (var entry in dbUpdateException.Entries)
{
var entry1 = entry;
var obj = entry1.CurrentValues.ToObject();
var type = obj.GetType();
var propertyNames = entry1.CurrentValues.PropertyNames.Where(x => inner.Message.Contains(x)).ToList();
// check MS SQL datetime2 error
if (inner.Message.Contains("datetime2"))
{
var propertyNames2 = from x in type.GetProperties()
where x.PropertyType == typeof(DateTime) ||
x.PropertyType == typeof(DateTime?)
select x.Name;
propertyNames.AddRange(propertyNames2);
}
message += "Entry " + i++ + " " + type.Name + ": " + string.Join("; ", propertyNames.Select(x =>
string.Format("'{0}' = '{1}'", x, entry1.CurrentValues[x])));
}
return new Exception(message, dbUpdateException);
}
}
the problem is that the dom element 'speclist' is not created at the time the javascript code is getting executed. So I put the javascript code inside a function and called that function on body onload event.
function do_this_first(){
//appending code
}
<body onload="do_this_first()">
</body>
You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:
var = 1
def global_var_change():
global var
var = "value changed"
global_var_change() #call the function for changes
print var
Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.
I've been struggling with Dialog animation today, finally got it working using styles, so here is an example.
To start with, the most important thing — I probably had it working 5 different ways today but couldn't tell because... If your devices animation settings are set to "No Animations" (Settings ? Display ? Animation) then the dialogs won't be animated no matter what you do!
The following is a stripped down version of my styles.xml. Hopefully it is self-explanatory. This should be located in res/values
.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="PauseDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
</style>
<style name="PauseDialogAnimation">
<item name="android:windowEnterAnimation">@anim/spin_in</item>
<item name="android:windowExitAnimation">@android:anim/slide_out_right</item>
</style>
</resources>
The windowEnterAnimation
is one of my animations and is located in res\anim
.
The windowExitAnimation
is one of the animations that is part of the Android SDK.
Then when I create the Dialog in my activities onCreateDialog(int id)
method I do the following.
Dialog dialog = new Dialog(this, R.style.PauseDialog);
// Setting the title and layout for the dialog
dialog.setTitle(R.string.pause_menu_label);
dialog.setContentView(R.layout.pause_menu);
Alternatively you could set the animations the following way instead of using the Dialog constructor that takes a theme.
Dialog dialog = new Dialog(this);
dialog.getWindow().getAttributes().windowAnimations = R.style.PauseDialogAnimation;
Your cases does not have a return value.
getButtons().get(i).setText("§");
In-line-if is Ternary operation all ternary operations must have return value. That variable is likely void and does not return anything and it is not returning to a variable. Example:
int i = 40;
String value = (i < 20) ? "it is too low" : "that is larger than 20";
for your case you just need an if statement.
if (compareChar(curChar, toChar("0"))) { getButtons().get(i).setText("§"); }
Also side note you should use curly braces it makes the code more readable and declares scope.
You can also do it with two sed calls:
$ cat file.txt
something1: +12.0 (some unnecessary trailing data (this must go))
something2: +15.5 (some more unnecessary trailing data)
something4: +9.0 (some other unnecessary data)
something1: +13.5 (blah blah blah)
$ sed 's/^[^:]*: *\([+0-9.]\+\) .*/\1/' file.txt | sed -e :a -e '$!N; s/\n/,/; ta'
+12.0,+15.5,+9.0,+13.5
First sed call removes uninteresting data, and the second join all lines.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Show Hide DIV" ng-click="ShowHide()" />
<br />
<br />
<div ng-show = "IsVisible">My DIV</div>
</div>
</body>
</html>
EXAMPLE : - http://jsfiddle.net/mafais/4WK7R/380/
I'm going to push my pet peeve: the USING keyword.
If both tables on both sides of the JOIN have their foreign keys properly named (ie, same name, not just "id) then this can be used:
SELECT ...
FROM customers JOIN orders USING (customer_id)
I find this very practical, readable, and not used often enough.
String newString= Arrays.toString(oldString).replace("[","").replace("]","").replace(",","").trim();
I found that this can be done rather simple using the ".values" method, which also gives named fields:
result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))
"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values
I had the same problem with a dummy app that happened to have the same name as my final app and couldn't publish because the App Name is already in use
To fix it, instead of deleting it(which you can't) I just changed the name of the dummy app to something random and hit SAVE. Then I was able to add the new app with the proper name
Actually it's not an error! It means you should enter some message to mark this merge. My OS is Ubuntu 14.04.If you use the same OS, you just need to do this as follows:
Type some message
CtrlCO
Type the file name (such as "Merge_feature01") and press Enter
CtrlX to exit
Now if you go to .git and you will find the file "Merge_feature01", that's the merge log actually.
This is known as a Shebang
:
http://en.wikipedia.org/wiki/Shebang_(Unix)
#!interpreter [optional-arg]
A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).
When a shell executes the script it will use the specified interpreter.
Example:
#!/bin/bash
# file: foo.sh
echo 1
$ chmod u+x foo.sh
$ ./foo.sh
1
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0[13578]|1[02])(-)31)|((0[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)02(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0[1-9])|(?:1[0-2]))(-)(?:0[1-9]|1\d|2[0-8])$
Examples:
You can test it here.
Note: if you want to accept one digit as month or day you can use:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0?[13578]|1[02])(-)31)|((0?[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)0?2(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0?[1-9])|(?:1[0-2]))(-)(?:0?[1-9]|1\d|2[0-8])$
I have created the above regex starting from this solution
No one has updated answer for latest Angular CLI.With latest Angular CLI
With latest version
of angular-cli in which angular-cli.json renamed to angular.json
, you can change the port by editing angular.json
file
you now specify a port per "project"
projects": {
"my-cool-project": {
... rest of project config omitted
"architect": {
"serve": {
"options": {
"port": 4500
}
}
}
}
}
Read more about it here
This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.
from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType
# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, long)
str_type = str if PY3 else (str, unicode)
class StringLiteral(String):
"""Teach SA how to literalize various things."""
def literal_processor(self, dialect):
super_processor = super(StringLiteral, self).literal_processor(dialect)
def process(value):
if isinstance(value, int_type):
return text(value)
if not isinstance(value, str_type):
value = text(value)
result = super_processor(value)
if isinstance(result, bytes):
result = result.decode(dialect.encoding)
return result
return process
class LiteralDialect(DefaultDialect):
colspecs = {
# prevent various encoding explosions
String: StringLiteral,
# teach SA about how to literalize a datetime
DateTime: StringLiteral,
# don't format py2 long integers to NULL
NullType: StringLiteral,
}
def literalquery(statement):
"""NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
import sqlalchemy.orm
if isinstance(statement, sqlalchemy.orm.Query):
statement = statement.statement
return statement.compile(
dialect=LiteralDialect(),
compile_kwargs={'literal_binds': True},
).string
Demo:
# coding: UTF-8
from datetime import datetime
from decimal import Decimal
from literalquery import literalquery
def test():
from sqlalchemy.sql import table, column, select
mytable = table('mytable', column('mycol'))
values = (
5,
u'snowman: ?',
b'UTF-8 snowman: \xe2\x98\x83',
datetime.now(),
Decimal('3.14159'),
10 ** 20, # a long integer
)
statement = select([mytable]).where(mytable.c.mycol.in_(values)).limit(1)
print(literalquery(statement))
if __name__ == '__main__':
test()
Gives this output: (tested in python 2.7 and 3.4)
SELECT mytable.mycol
FROM mytable
WHERE mytable.mycol IN (5, 'snowman: ?', 'UTF-8 snowman: ?',
'2015-06-24 18:09:29.042517', 3.14159, 100000000000000000000)
LIMIT 1
total count the documents where the value of the field is not equal to the specified value.
async function getRegisterUser() {
return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
if (err) {
return err;
}
return totResUser;
})
}
Use the traceback module:
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
print('An error occurred on line {} in statement {}'.format(line, text))
exit(1)
Bit per second is what is means - rate of data transmission of ones and zeros per second are used.This is called bit per second(bit/s. However, it should not be confused with bytes per second, abbreviated as bytes/s, Bps, or B/s.
Raw throughput values are normally given in bits per second, but many software applications report transfer rates in bytes per second.
So, the standard unit for bit throughput is the bit per second, which is commonly abbreviated bit/s, bps, or b/s.
Baud is a unit of measure of changes , or transitions , that occurs in a signal in each second.
For example if the signal changes from one value to a zero value(or vice versa) one hundred times per second, that is a rate of 100 baud.
The other one measures data(the throughput of channel), and the other ones measures transitions(called signalling rates).
For example if you look at modern modems they use advanced modulation techniques that encoded more than one bit of data into each transition.
Thanks.
I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.
I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.
For anyone interested, here is the actual solution:
... //rest of options
width: '100%',
height: '350',
chartArea:{
left:5,
top: 20,
width: '100%',
height: '350',
}
... //rest of options
The key here has nothing to do with the "left" or "top" values. But rather that the:
Dimensions of both the chart and chart-area are SET and set to the SAME VALUE
As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.
You don't have to press CTRL * space but maybe the delay is too big or you don't like the trigger (default is '.'). Go to
Window -> Preferences -> Java/Editor/Content Assist
And change the settings under Auto Activation to your likings.
If this does not work for windows users then see this answer.
I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).
If you dont have identity column in table B_table:
INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table
If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.
In case if you dont have existing B_table in B_db
SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table
will create table B_table in database B_db with all existing values
The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.
$myForm.find(':input:not(:disabled)').prop('disabled',true);
And to enable again you could do
$myForm.find(':input:disabled').prop('disabled',false);
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
You can use os.scandir()
. New function in stdlib starts from Python 3.5.
import os
for entry in os.scandir('.'):
if entry.is_file():
print(entry.name)
Faster than os.listdir()
. os.walk()
implements os.scandir()
.
There are some action to do:
1- in pubspec.yaml press "packages get" or in terminal type " flutter packages get" and wait seconds.
if this doesn't work :
2-type flutter clean then do step(1)
if this doesn't work too :
3-type killtask /f /im dart.exe
if this doesn't work too :
4- close android studio and then restart your pc.
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
A little optimization of the class before. In this version the files are not totally loaded into memory.
Security advice: a check for the boundary is missing, if the file contains the bounday it will crash.
namespace WindowsFormsApplication1
{
public static class FormUpload
{
private static string NewDataBoundary()
{
Random rnd = new Random();
string formDataBoundary = "";
while (formDataBoundary.Length < 15)
{
formDataBoundary = formDataBoundary + rnd.Next();
}
formDataBoundary = formDataBoundary.Substring(0, 15);
formDataBoundary = "-----------------------------" + formDataBoundary;
return formDataBoundary;
}
public static HttpWebResponse MultipartFormDataPost(string postUrl, IEnumerable<Cookie> cookies, Dictionary<string, string> postParameters)
{
string boundary = NewDataBoundary();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
// Set up the request properties
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.UserAgent = "PhasDocAgent 1.0";
request.CookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
request.CookieContainer.Add(cookie);
}
#region WRITING STREAM
using (Stream formDataStream = request.GetRequestStream())
{
foreach (var param in postParameters)
{
if (param.Value.StartsWith("file://"))
{
string filepath = param.Value.Substring(7);
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
Path.GetFileName(filepath) ?? param.Key,
MimeTypes.GetMime(filepath));
formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);
// Write the file data directly to the Stream, rather than serializing it to a string.
byte[] buffer = new byte[2048];
FileStream fs = new FileStream(filepath, FileMode.Open);
for (int i = 0; i < fs.Length; )
{
int k = fs.Read(buffer, 0, buffer.Length);
if (k > 0)
{
formDataStream.Write(buffer, 0, k);
}
i = i + k;
}
fs.Close();
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
boundary,
param.Key,
param.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);
}
}
// Add the end of the request
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
formDataStream.Write(footer, 0, footer.Length);
request.ContentLength = formDataStream.Length;
formDataStream.Close();
}
#endregion
return request.GetResponse() as HttpWebResponse;
}
}
}
This is something of a religious debate. Both approaches have their problems.
Bloch has another relevant piece of advice in Effective Java Second Edition:
You can have multiple CTE
s in one query, as well as reuse a CTE
:
WITH cte1 AS
(
SELECT 1 AS id
),
cte2 AS
(
SELECT 2 AS id
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1
Note, however, that SQL Server
may reevaluate the CTE
each time it is accessed, so if you are using values like RAND()
, NEWID()
etc., they may change between the CTE
calls.
All JSON.parse
implementations most likely use eval()
JSON.parse
is based on Douglas Crockford's solution, which uses eval()
right there on line 497.
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
The advantage of JSON.parse
is that it verifies the argument is correct JSON syntax.
I had to change:
function start_lvl(&$output, $depth)
to:
function start_lvl( &$output, $depth = 0, $args = array() )
Because I was getting an incompatibility error:
Strict Standards: Declaration of My_Walker_Nav_Menu::start_lvl() should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array)
To be fair the question pre-dates this answer.
I add it not to criticise the OP, but to help anyone still asking this question.
The correct way to determine whether something is visible is to consult your view-model;
If you don't know what that means then you are about to embark on a journey of discovery that will make your work a great deal less difficult.
Here's an overview of the model-view-view-model architecture (MVVM).
KnockoutJS is a binding library that will let you try this stuff out without learning an entire framework.
And here's some JavaScript code and a DIV that may or may not be visible.
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<script>
var vm = {
IsDivVisible: ko.observable(true);
}
vm.toggle = function(data, event) {
// Get current visibility state for the div
var x = IsDivVisible();
// Set it to the opposite
IsDivVisible(!x);
}
ko.applyBinding(vm);
</script>
<div data-bind="visible: IsDivVisible">Peekaboo!</div>
<button data-bind="click: toggle">Toggle the div's visibility</button>
</body>
</html>
Notice that the toggle function does not consult the DOM to determine the visibility of the div; it consults the view-model.
I would create a session variable and randomize it. Then build the id and name values based on the session variable. Then on login interrogate the session var you created.
if (!isset($_SESSION['autoMaskPassword'])) {
$bytes = random_bytes(16);
$_SESSION['autoMask_password'] = bin2hex($bytes);
}
<input type="password" name="<?=$_SESSION['autoMaskPassword']?>" placeholder="password">
The delete
operator allows you to remove a property from an object.
The following examples all do the same thing.
// Example 1
var key = "Cow";
delete thisIsObject[key];
// Example 2
delete thisIsObject["Cow"];
// Example 3
delete thisIsObject.Cow;
If you're interested, read Understanding Delete for an in-depth explanation.
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
Here is my variation on rbp's answer, which bypasses "editable" and development distributions. It shares two flaws of the original: it re-downloads and reinstalls unnecessarily; and an error on one package will prevent the upgrade of every package after that.
pip freeze |sed -ne 's/==.*//p' |xargs pip install -U --
Related bug reports, a bit disjointed after the migration from Bitbucket:
if you like to use for URLRequest httpBody
extension Dictionary {
func toString() -> String? {
return (self.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
}
}
// print: Fields=sdad&ServiceId=1222
ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.
Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.
Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.
Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT
or ROLLBACK
statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT
applies the changes (if any) made within the transaction. ROLLBACK
disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.
Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:
SET autocommit = 0
An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION
. It also requires an explicitly made COMMIT
or ROLLBACK
statement at the end of the transaction. Nested transactions is beyond the scope of this topic.
Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT
or ROLLBACK
statement to be supplied.
Explicit transactions are the most ideal solution - they require a statement, COMMIT
or ROLLBACK
, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT
statements should only be specified once results have been tested & thoroughly determined to be valid.
That means you should use:
SET autocommit = 0;
START TRANSACTION;
UPDATE ...;
...and only use COMMIT;
when the results are correct.
That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.
DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.
You can do it like this:
declare @results varchar(500)
select @results = coalesce(@results + ',', '') + convert(varchar(12),col)
from t
order by col
select @results as results
| RESULTS |
-----------
| 1,3,5,9 |
There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)
You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.
UNAME := $(shell uname -m)
all:
$(info Checking if custom header is needed)
ifeq ($(UNAME), x86_64)
... do some things to build unistd_32.h
endif
@make -C $(KDIR) M=$(PWD) modules
So you want unistd_32.h built (maybe) before you invoke the second make
, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:
ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif
all:
@make -C $(KDIR) M=$(PWD) modules
unistd_32.h:
... do some things to build unistd_32.h
Now for building unistd_32.h
:
F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else
F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
ifeq ($(F2_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
else
$(error asm/unistd_32.h and asm-386/unistd.h does not exist)
endif
endif
You are trying to build unistd.h
from unistd_32.h
; the only trick is that unistd_32.h
could be in either of two places. The simplest way to clean this up is to use a vpath
directive:
vpath unistd.h /usr/include/asm /usr/include/asm-i386
unistd_32.h: unistd.h
sed -e 's/__NR_/__NR32_/g' $< > $@
This isn't a function of bash
, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.
In Perl for example, this could be accomplished by setting:
$| = 1;
See perlvar for more information on this.
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install IIS URL Rewrite on server.
Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api
because of the third input (third line of condition).
If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.
Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/
That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples
EDIT: http://jsfiddle.net/2ZzZB/16/ to http://jsfiddle.net/2ZzZB/56/ (won't show "1/4.5" if there is 45 results)
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
You should be catching NullPointerException
with the code above, but that doesn't change the fact that your Check_Circular
is wrong. If you fix Check_Circular
, your code won't throw NullPointerException
in the first place, and work as intended.
Try:
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode curNode = head;
do
{
curNode = curNode.next;
if(curNode == head)
return true;
}
while(curNode != null);
return false;
}
For me what worked is having it like this
style={{ backgroundImage: `url(${require("./resources/img/banners/3.jpg")})` }}
Use this FAQ page: Apache log4net Frequently Asked Questions
About 3/4 of the way down it tells you how to enable log4net debugging by using application tracing. This will tell you where your issue is.
The basics are:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
And you see the trace in the standard output
Remove the function and check the output of:
var_dump(function_exists('parseDate'));
In which case, change the name of the function.
If you get false, you're including the file with that function twice, replace :
include
by
include_once
And replace :
require
by
require_once
EDIT : I'm just a little too late, post before beat me to it !
Let me illustrate you from my personal example in a very redundant way.
Sometimes macOS or Linux automatically sets up environment variable for you unlike Windows. But that's not the case always. So let's check it. The line immediately after echo $JAVA_HOME would be empty if the environment variable is not set. It must be empty in your case.
Now we need to check if we have bash_profile file. You saw that in my case we already have bash_profile. If not we have to create a bash_profile file.
Now let's open bash_profile file. macOS opens it using it's default TextEdit program.
This is the file where environment variables are kept. If you have opened a new bash_profile file, it must be empty. In my case, it was already set for python programming language and Anaconda distribution. Now, i need to add environment variable for Java which is just adding the first line. YOU MUST TYPE the first line VERBATIM. JUST the first line. Save and close the TextEdit. Then close the terminal.
Open the terminal again. Let's check if the environment variable is set up.
Here :name
is the symbol which point to the method name
of tag object.
When we pass &:name
to map
, it will treat name
as a proc object.
For short, tags.map(&:name)
acts as:
tags.map do |tag|
tag.name
end
A little anecdote to illustrate the use of array_key_exists
.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit
<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
{{$index}} - {{day.iso}} - {{day.name}}
Temperature: {{f.temperature}}<br>
Humidity: {{f.humidity}}<br>
...
</div>
Example: http://jsfiddle.net/coma/UV4qF/
It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). I found this answer to this question helpful. However, I didn't entirely use it to solve my problem. Instead, I decided it'd be much easier and almost as aesthetic to color a panel next to the button.
import java.io.*;
class Initials {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.print("Enter any sentence: ");
s = br.readLine();
s = " " + s; //adding a space infront of the inputted sentence or a name
s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
l = s.length(); //finding the length of the sentence
System.out.print("Output = ");
for (int i = 0; i < l; i++) {
x = s.charAt(i); //taking out one character at a time from the sentence
if (x == ' ') //if the character is a space, printing the next Character along with a fullstop
System.out.print(s.charAt(i + 1) + ".");
}
}
}
The package @angular/router
has the Resolve
property for routes. So you can easily resolve data before rendering a route view.
See: https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
Example from docs as of today, August 28, 2017:
class Backend {
fetchTeam(id: string) {
return 'someTeam';
}
}
@Injectable()
class TeamResolver implements Resolve<Team> {
constructor(private backend: Backend) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
return this.backend.fetchTeam(route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
resolve: {
team: TeamResolver
}
}
])
],
providers: [TeamResolver]
})
class AppModule {}
Now your route will not be activated until the data has been resolved and returned.
Accessing Resolved Data In Your Component
To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:
route.snapshot.paramMap
which returns a string, or the route.paramMap
which returns an Observable you can .subscribe()
to. Example:
// the no-observable method
this.dataYouResolved= this.route.snapshot.paramMap.get('id');
// console.debug(this.licenseNumber);
// or the observable method
this.route.paramMap
.subscribe((params: ParamMap) => {
// console.log(params);
this.dataYouResolved= params.get('id');
return params.get('dataYouResolved');
// return null
});
console.debug(this.dataYouResolved);
I hope that helps.
With previously proposed solutions, I have struggled to get multiple npm commands executed in a loop and get all outputs on the console window.
It finally started to work after I have combined everything from the previous comments, but rearranged the code execution flow.
What I have noticed is that event subscribing was done too late (after the process has already started) and therefore some outputs were not captured.
The code below now does the following:
The code has been tested against the deadlocks, although it is synchronous (one process execution at the time) so I cannot guarantee what would happen if this was run in parallel.
static void RunCommand(string command, string workingDirectory)
{
Process process = new Process
{
StartInfo = new ProcessStartInfo("cmd.exe", $"/c {command}")
{
WorkingDirectory = workingDirectory,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
}
};
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine("output :: " + e.Data);
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine("error :: " + e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine("ExitCode: {0}", process.ExitCode);
process.Close();
}
Use mysqli_fetch_row()
. Try this,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail = $row['ssemail'];
Experience counts for a lot, but in terms of table design you can learn a lot from how ORMs like Hibernate and Grails operate to see why they do things. In addition:
Keep different types of data separate - don't store addresses in your order table, link to an address in a separate addresses table, for example.
I personally like having an integer or long surrogate key on each table (that holds data, not those that link different tables together, e,g., m:n relationships) that is the primary key.
I also like having a created and modified timestamp column.
Ensure that every column that you do "where column = val" in any query has an index. Maybe not the most perfect index in the world for the data type, but at least an index.
Set up your foreign keys. Also set up ON DELETE and ON MODIFY rules where relevant, to either cascade or set null, depending on your object structure (so you only need to delete once at the 'head' of your object tree, and all that object's sub-objects get removed automatically).
If you want to modularise your code, you might want to modularise your DB schema - e.g., this is the "customers" area, this is the "orders" area, and this is the "products" area, and use join/link tables between them, even if they're 1:n relations, and maybe duplicate the important information (i.e., duplicate the product name, code, price into your order_details table). Read up on normalisation.
Someone else will recommend exactly the opposite for some or all of the above :p - never one true way to do some things eh!
I found a free plugin that can generate class diagrams with android studio. It's called SimpleUML.
Update Android Studio 2.2+: To install the plugin, follow steps in this answer: https://stackoverflow.com/a/36823007/1245894
Older version of Android Studio
On Mac: go to Android Studio
-> Preferences
-> Plugins
On Windows: go to Android Studio
-> File
-> Settings
-> Plugins
Click on Browse repositories...
and search for SimpleUMLCE
(CE means Community Edition, this is what android studio is based on).
Install it, restart, then you can do a right click on the folder containing the classes you want to visualize, and select Add to simpleUML Diagram
.
That's it; you have you fancy class diagram generated from your code!
for foo in *.gz
do
tar xf "$foo"
rm "$foo"
done
What you wrote sends a list of newline separated file names (and paths) to rm
, but rm doesn't know what to do with that input. It's only expecting command line parameters.
xargs
takes input, usually separated by newlines, and places them on the command line, so adding xargs makes what you had work:
find . -name .svn | xargs rm -fr
xargs
is intelligent enough that it will only pass as many arguments to rm
as it can accept. Thus, if you had a million files, it might run rm
1,000,000/65,000 times (if your shell could accept 65,002 arguments on the command line {65k files + 1 for rm + 1 for -fr}).
As persons have adeptly pointed out, the following also work:
find . -name .svn -exec rm -rf {} \;
find . -depth -name .svn -exec rm -fr {} \;
find . -type d -name .svn -print0|xargs -0 rm -rf
The first two -exec
forms both call rm
for each folder being deleted, so if you had 1,000,000 folders, rm
would be invoked 1,000,000 times. This is certainly less than ideal. Newer implementations of rm
allow you to conclude the command with a +
indicating that rm
will accept as many arguments as possible:
find . -name .svn -exec rm -rf {} +
The last find/xargs version uses print0, which makes find generate output that uses \0
as a terminator rather than a newline. Since POSIX systems allow any character but \0
in the filename, this is truly the safest way to make sure that the arguments are correctly passed to rm
or the application being executed.
In addition, there's a -execdir
that will execute rm
from the directory in which the file was found, rather than at the base directory and a -depth
that will start depth first.
I have a PowerShell script I have to run on a computer so out of date that it doesn't have [String]::IsNullOrWhiteSpace(), so I wrote my own.
function IsNullOrWhitespace($str)
{
if ($str)
{
return ($str -replace " ","" -replace "`t","").Length -eq 0
}
else
{
return $TRUE
}
}
Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).
octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.
Note: Only use this method for local development, it's not secure.
You can setup password and ssh config while provisioning the box. For example with debian/stretch64
box this is my provision script:
config.vm.provision "shell", inline: <<-SHELL
echo -e "vagrant\nvagrant" | passwd root
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
sed -in 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
service ssh restart
SHELL
This will set root password to vagrant
and permit root login with password. If you are using private_network
say with ip address 192.168.10.37
then you can ssh with ssh [email protected]
You may need to change that echo
and sed
commands depending on the default sshd_config
file.
You should use something like this:
<div style="text-align:center">
<input type="submit" />
</div>
Or you could use something like this. By giving the element a width and specifying auto
for the left and right margins the element will center itself in its parent.
<input type="submit" style="width: 300px; margin: 0 auto;" />
The answer is no, but you can use collections.OrderedDict
from the Python standard library with just keys (and values as None
) for the same purpose.
Update: As of Python 3.7 (and CPython 3.6), standard dict
is guaranteed to preserve order and is more performant than OrderedDict
. (For backward compatibility and especially readability, however, you may wish to continue using OrderedDict
.)
Here's an example of how to use dict
as an ordered set to filter out duplicate items while preserving order, thereby emulating an ordered set. Use the dict
class method fromkeys()
to create a dict, then simply ask for the keys()
back.
>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']
>>> list(dict.fromkeys(keywords))
['foo', 'bar', 'baz']
Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.
Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.
Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.
Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.
When using JSON dictionaries:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .
router.navigateByUrl() is used for absolute path navigation.
ie,
If we need to navigate to entirely different route in that case we can use router.navigateByUrl
For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()
Syntax :
router.navigateByUrl(' ---- String ----');
router.navigate([], {relativeTo: route})
This worked for me:
static void ClearLine(){
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
We have M2_HOME,MAVEN_HOME,M3_HOME all are available in market
Previously M2_HOME is the only environment variable used by all as a standard.
But,due latest releases the MAVEN_Home came as standard but some old tools are still trying to find only M2_HOME
so we should have both M2_HOME,MAVEN_HOME to sustain with old and new tools.
M2_HOME can be used for both as well
You can define a context
for your application say ExampleContext
which will hold the context of your application and then use it to instantiate an activity like this:
var intent = new Intent(Application.ApplicationContext, typeof(Activity2));
intent.AddFlags(ActivityFlags.NewTask);
Application.ApplicationContext.StartActivity(intent);
Please bear in mind that this code is written in C#
as I use MonoDroid, but I believe it is very similar to Java
. For how to create an ApplicationContext
look at this thread
This is how I made my Application Class
[Application]
public class Application : Android.App.Application, IApplication
{
public Application(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
}
public object MyObject { get; set; }
}
mystring.replace (" ", "_")
if you assign this value to any variable, it will work
s = mystring.replace (" ", "_")
by default mystring wont have this
Example to get the last input element:
document.querySelector(".groups-container >div:last-child input")
This should get you for starting with two letters and ending with two numbers.
[A-Za-z]{2}(.*)[0-9]{2}
If you know it will always be just two and two you can
[A-Za-z]{2}[0-9]{2}
It happens because of the reason mentioned below :
If you see the mvn script: The code fails here ---
Steps for debugging and fixing:
Step 1: Open the mvn script /Users/Username/apache-maven-3.0.5/bin/mvn (Open with the less command like: less /Users/Username/apache-maven-3.0.5/bin/mvn)
Step 2: Find out the below code in the script:
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly."
echo " We cannot execute $JAVACMD"
exit 1
fi
Step3: It is happening because JAVACMD
variable was not set. So it displays the error.
Note: To Fix it
export JAVACMD=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin/java
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/
Key: If you want it to be permanent open emacs .profile
post the commands and press Ctrl-x Ctrl-c ( save-buffers-kill-terminal ).
I assume you are using Java, but look under the settings for your particular language.
Under the Window menu, select Preferences.
Under Java->Editor->Folding. Select "Enable Folding".
I had similar problems as well. I put the following line of code in the head of my layout file and all seems to be fine.
<meta http-equiv="X-UA-Compatible" content="IE=9">
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:
$('#fruit').append(veggies);
or to append it to the end of a form value like in your example:
$('#fruit').val($('#fruit').val()+veggies);
In your case, fruitvegbasket
is a string that contains the current value of #fruit
, not an array.
jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val()
returns the value
attribute of an input
element as a string. You can't push something onto a string.
You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.
Here is my solution:
Firstly, import pandas as pd:
import pandas as pd
Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.
df = pd.read_excel('testexcel.xlsx', index_col=0)
At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd
.
For visual inspection, read the dataframe using df.head()
which will print the following output
Now you can fetch the values of the desired columns of the dataframe and print it
Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox (desktop and iOS versions). First we need to detect Apple
vendor and then exclude Chrome and Firefox (for iOS).
let isSafari = navigator.vendor.match(/apple/i) &&
!navigator.userAgent.match(/crios/i) &&
!navigator.userAgent.match(/fxios/i);
if (isSafari) {
//
} else {
//
}
<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic & modern design.</span></p>
Remove <br>
effect using CSS.
<style> p br{ display:none; } </style>
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
For Internet Explorer, there is another solution:
I don't use PDO for MySQL and PgSQL, but I do for SQLite. Is there a way (without completely changing the dbal back) to count rows like this in PDO?
Accordingly to this comment, the SQLite issue was introduced by an API change in 3.x.
That said, you might want to inspect how PDO actually implements the functionality before using it.
I'm not familiar with its internals but I'd be suspicious at the idea that PDO parses your SQL (since an SQL syntax error would appear in the DB's logs) let alone tries to make the slightest sense of it in order to count rows using an optimal strategy.
Assuming it doesn't indeed, realistic strategies for it to return a count of all applicable rows in a select statement include string-manipulating the limit clause out of your SQL statement, and either of:
A much better way to count, however, would be to execute the fully optimized query that will do so. More often than not, this means rewriting meaningful chunks of the initial query you're trying to paginate -- stripping unneeded fields and order by operations, etc.
Lastly, if your data sets are large enough that counts any kind of lag, you might also want to investigate returning the estimate derived from the statistics instead, and/or periodically caching the result in Memcache. At some point, having precisely correct counts is no longer useful...
In iOS 12, Swift 4.2 & XCode 10.1
//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
// button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
// button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)
@objc func buttonClicked(sender:UIButton) {
print("Button \(sender.tag) clicked")
}
//You can add UIButton properties like this also
extension UIButton {
func btnProperties() {
layer.cornerRadius = 10//Set button corner radious
clipsToBounds = true
backgroundColor = .blue//Set background colour
//titleLabel?.textAlignment = .center//add properties like this
}
}
When it is on server side, use web services - maybe RESTful with JSON.
When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.
Below is example from documentation. Look at methodReturningString
.
Java code:
public class MethodInvocation extends Applet {
public void noArgMethod() { ... }
public void someMethod(String arg) { ... }
public void someMethod(int arg) { ... }
public int methodReturningInt() { return 5; }
public String methodReturningString() { return "Hello"; }
public OtherClass methodReturningObject() { return new OtherClass(); }
}
public class OtherClass {
public void anotherMethod();
}
Web page and JavaScript code:
<applet id="app"
archive="examples.jar"
code="MethodInvocation" ...>
</applet>
<script language="javascript">
app.noArgMethod();
app.someMethod("Hello");
app.someMethod(5);
var five = app.methodReturningInt();
var hello = app.methodReturningString();
app.methodReturningObject().anotherMethod();
</script>
Use negative lookaround: (?!
pattern
)
Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.
These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):
The only subquery appears to be this - try adding a ROWNUM
limit to the where to be sure:
(SELECT C.I_WORKDATE
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
AND C.I_EMPID = A.I_EMPID)
You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE
on the matched date.
For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.
SELECT
...
REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
...
INNER JOIN T_EMPLOYEE_MS E
...
LEFT OUTER JOIN T_COMPENSATION C
ON C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID
...
Use empty()
. It checks for both empty strings and null.
if (!empty($_POST['user'])) {
// do stuff
}
From the manual:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
String[] token=s.split("[.-]");
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
A fast way to convert strings to an integer is to use a bitwise or, like so:
x | 0
While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x
) since it will first cast x
to a number and then perform a very efficient or.
One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.
below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
The controllers are
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.
$broadcast vs $emit
Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.
The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.
Adding $rootScope and lets $broadcast
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.
Receiving our broadcast
In our second controller, we need to set up code to listen to our broadcast
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
It's really that simple. Live Example
Other ways to achieve similar results
Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.
You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.
Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.
In my case, I just added this class and use @EnableAutConfiguration
:
@Component
public class SimpleCORSFilter extends GenericFilterBean {
/**
* The Logger for this class.
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
logger.info("> doFilter");
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
//response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, resp);
logger.info("< doFilter");
}
}
The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it's a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.
$total = count((array)$obj);
Simply casting an object as an array won't always work but being a simple stdClass object it should get the job done here.
var_export will give you a nice output. Examples from the docs:
$a = array (1, 2, array ("a", "b", "c"));
echo '<pre>' . var_export($a, true) . '</pre>';
Will output:
array (
0 => 1,
1 => 2,
2 =>
array (
0 => 'a',
1 => 'b',
2 => 'c',
),
)
The practical way is setting font-family
to a value that is the specific name of the semibold version, such as
font-family: "Myriad pro Semibold"
if that’s the name. (Personally I use my own font listing tool, which runs on Internet Explorer only to see the fonts in my system by names as usable in CSS.)
In this approach, font-weight
is not needed (and probably better not set).
Web browsers have been poor at implementing font weights by the book: they largely cannot find the specific weight version, except bold. The workaround is to include the information in the font family name, even though this is not how things are supposed to work.
Testing with Segoe UI, which often exists in different font weight versions on Windows systems, I was able to make Internet Explorer 9 select the proper version when using the logical approach (of using the font family name Segoe UI and different font-weight
values), but it failed on Firefox 9 and Chrome 16 (only normal and bold work). On all of these browsers, for example, setting font-family: Segoe UI Light
works OK.
I vote for Karthik T's answer. you don't need to open a terminal to run commands.
For example,
// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunShellCommandFromJava {
public static void main(String[] args) {
String command = "ping -c 3 www.google.com";
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
The output:
$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms
--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms
You can use comments like in regular JavaScript:
[...] TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax.
[...] This document describes the syntactic grammar added by TypeScript [...]
Source: TypeScript Language Specification
The only two mentions of the word "comments" in the spec are:
[...] TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables.
11.1.1 Source Files Dependencies
[...] A comment of the form
/// <reference path="..."/>
adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
You are missing the parent constructor. When your controller is loaded you must Call the parent CI_Controller class constructor in your controller constructor
Here's a simple lock mechanism, implemented via closure
const createLock = () => {
let lockStatus = false
const release = () => {
lockStatus = false
}
const acuire = () => {
if (lockStatus == true)
return false
lockStatus = true
return true
}
return {
lockStatus: lockStatus,
acuire: acuire,
release: release,
}
}
lock = createLock() // create a lock
lock.acuire() // acuired a lock
if (lock.acuire()){
console.log("Was able to acuire");
} else {
console.log("Was not to acuire"); // This will execute
}
lock.release() // now the lock is released
if(lock.acuire()){
console.log("Was able to acuire"); // This will execute
} else {
console.log("Was not to acuire");
}
lock.release() // Hey don't forget to release
_x000D_
In Xcode 8 - Swift 3:
button.setTitle( "entertext" , for: .normal )
There is a second paragraph in your footer that contains a script. It is this that is causing the issue.
I posted too soon however the ways to configure are given in below link
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
and way to get access keys are given in below link
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html#cli-signup
As per dart 2.6
The optional onError
parameter of int.parse
is deprecated. Therefore, you should use int.tryParse
instead.
Note:
The same applies to double.parse
. Therefore, use double.tryParse
instead.
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
The difference is that int.tryParse
returns null
if the source string is invalid.
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
So, in your case it should look like:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
Actually the easiest way to do that would be to pass kill arguments like below:
ps -ef | grep your_process_name | grep -v grep | awk '{print $2}' | xargs kill
Hope it helps.
The accepted answer changes shape for 2d arrays.
I present a solution here, using the Pandas dropna() functionality.
It works for 1D and 2D arrays. In the 2D case you can choose weather to drop the row or column containing np.nan
.
import pandas as pd
import numpy as np
def dropna(arr, *args, **kwarg):
assert isinstance(arr, np.ndarray)
dropped=pd.DataFrame(arr).dropna(*args, **kwarg).values
if arr.ndim==1:
dropped=dropped.flatten()
return dropped
x = np.array([1400, 1500, 1600, np.nan, np.nan, np.nan ,1700])
y = np.array([[1400, 1500, 1600], [np.nan, 0, np.nan] ,[1700,1800,np.nan]] )
print('='*20+' 1D Case: ' +'='*20+'\nInput:\n',x,sep='')
print('\ndropna:\n',dropna(x),sep='')
print('\n\n'+'='*20+' 2D Case: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna (rows):\n',dropna(y),sep='')
print('\ndropna (columns):\n',dropna(y,axis=1),sep='')
print('\n\n'+'='*20+' x[np.logical_not(np.isnan(x))] for 2D: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna:\n',x[np.logical_not(np.isnan(x))],sep='')
Result:
==================== 1D Case: ====================
Input:
[1400. 1500. 1600. nan nan nan 1700.]
dropna:
[1400. 1500. 1600. 1700.]
==================== 2D Case: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna (rows):
[[1400. 1500. 1600.]]
dropna (columns):
[[1500.]
[ 0.]
[1800.]]
==================== x[np.logical_not(np.isnan(x))] for 2D: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna:
[1400. 1500. 1600. 1700.]
I'm using something like this to only trigger on ListViewItem double-click and not for example when you double-click on the header of the ListView.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DependencyObject obj = (DependencyObject)e.OriginalSource;
while (obj != null && obj != myListView)
{
if (obj.GetType() == typeof(ListViewItem))
{
// Do something here
MessageBox.Show("A ListViewItem was double clicked!");
break;
}
obj = VisualTreeHelper.GetParent(obj);
}
}
(rewritten 2015-07-28)
The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac
from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn
command, this may happen.
The cure is to fix the errors and recompile, before running again.
The setting is marked with a red box in this screendump:
I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)
Here's the script:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
Here are the results:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate
is not the most readable; the other three are more obvious, though slower to varying degrees.
The question was what @_
means in Perl. The answer to that question is that, insofar as $_
means it in Perl, @_
similarly means they.
No one seems to have mentioned this critical aspect of its meaning — as well as theirs.
They’re consequently both used as pronouns, or sometimes as topicalizers.
They typically have nominal antecedents, although not always.
This works fine. just insert your jquery code in document.ready function.
$(document).ready(function(e) {
// your code here
});
example:
$(document).ready(function(e) {
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
});
});
<div>
<select id='canselect_code' name='canselect_code' multiple class='fl'>
<option value='1'>toto</option>
<option value='2'>titi</option>
</select>
<input type='button' id='btnRight_code' value=' > ' />
<br>
<input type='button' id='btnLeft_code' value=' < ' />
<select id='isselect_code' name='isselect_code' multiple class='fr'>
<option value='3'>tata</option>
<option value='4'>tutu</option>
</select>
</div>
As an alternative, if you put a space between the date and time, DateTime.Parse
will recognize the format for you. That's about as simple as you can get it. (If ParseExact
was still not being recognized)
I tried to remove the Image of the ImageView too by using ImageView.setImageRessource(0)
but it didn't work for me.
Luckily I got this message in the logs:
Caused by: java.lang.IllegalStateException: The specified child already has a parent.
You must call removeView() on the child's parent first.
So let's say, layoutmanager
is your instance for the layout, than you need to do that:
RelativeLayout layoutManager = new RelativeLayout(this);
ImageView image = new ImageView(this);
// this line worked for me
layoutManager.removeView(image);
Yes, you can use Yarn or NPM to edit your package.json.
yarn upgrade [package | package@tag | package@version | @scope/]... [--ignore-engines] [--pattern]
Something like:
yarn upgrade react@^16.0.0
Then I'd see what warns or errors out and then run yarn upgrade [package]
. No need to edit the file manually. Can do everything from the CLI.
Or just run yarn upgrade
to update all packages to latest, probably a bad idea for a large project. APIs may change, things may break.
Alternatively, with NPM run npm outdated
to see what packages will be affected. Then
npm update
https://yarnpkg.com/lang/en/docs/cli/upgrade/
https://docs.npmjs.com/getting-started/updating-local-packages
Two ways to delete the image from public folder without changing laravel filesystems config file or messing with pure php unlink function:
- Using the default local storage you need to specify public subfolder:
Storage::delete('public/'.$image_path);
- Use public storage directly:
Storage::disk('public')->delete($image_path);
I would suggest second way as the best one.
Hope this help other people.
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
Update: Some people say one should -never- use eval. I disagree. I think the risk arises when corrupt input can be passed to eval
. However there are many common situations where that is not a risk, and therefore it is worth knowing how to use eval in any case. This stackoverflow answer explains the risks of eval and alternatives to eval. Ultimately it is up to the user to determine if/when eval is safe and efficient to use.
The bash eval
statement allows you to execute lines of code calculated or acquired, by your bash script.
Perhaps the most straightforward example would be a bash program that opens another bash script as a text file, reads each line of text, and uses eval
to execute them in order. That's essentially the same behavior as the bash source
statement, which is what one would use, unless it was necessary to perform some kind of transformation (e.g. filtering or substitution) on the content of the imported script.
I rarely have needed eval
, but I have found it useful to read or write variables whose names were contained in strings assigned to other variables. For example, to perform actions on sets of variables, while keeping the code footprint small and avoiding redundancy.
eval
is conceptually simple. However, the strict syntax of the bash language, and the bash interpreter's parsing order can be nuanced and make eval
appear cryptic and difficult to use or understand. Here are the essentials:
The argument passed to eval
is a string expression that is calculated at runtime. eval
will execute the final parsed result of its argument as an actual line of code in your script.
Syntax and parsing order are stringent. If the result isn't an executable line of bash code, in scope of your script, the program will crash on the eval
statement as it tries to execute garbage.
When testing you can replace the eval
statement with echo
and look at what is displayed. If it is legitimate code in the current context, running it through eval
will work.
Example 1:
eval
statement in front of 'normal' code is a NOP$ eval a=b
$ eval echo $a
b
In the above example, the first eval
statements has no purpose and can be eliminated. eval
is pointless in the first line because there is no dynamic aspect to the code, i.e. it already parsed into the final lines of bash code, thus it would be identical as a normal statement of code in the bash script. The 2nd eval
is pointless too, because, although there is a parsing step converting $a
to its literal string equivalent, there is no indirection (e.g. no referencing via string value of an actual bash noun or bash-held script variable), so it would behave identically as a line of code without the eval
prefix.
Example 2:
$ key="mykey"
$ val="myval"
$ eval $key=$val
$ echo $mykey
myval
If you were to echo $key=$val
, the output would be:
mykey=myval
That, being the final result of string parsing, is what will be executed by eval, hence the result of the echo statement at the end...
Example 3:
$ keyA="keyB"
$ valA="valB"
$ keyB="that"
$ valB="amazing"
$ eval eval \$$keyA=\$$valA
$ echo $that
amazing
The above is a bit more complicated than the previous example, relying more heavily on the parsing-order and peculiarities of bash. The eval
line would roughly get parsed internally in the following order (note the following statements are pseudocode, not real code, just to attempt to show how the statement would get broken down into steps internally to arrive at the final result).
eval eval \$$keyA=\$$valA # substitution of $keyA and $valA by interpreter
eval eval \$keyB=\$valB # convert '$' + name-strings to real vars by eval
eval $keyB=$valB # substitution of $keyB and $valB by interpreter
eval that=amazing # execute string literal 'that=amazing' by eval
If the assumed parsing order doesn't explain what eval is doing enough, the third example may describe the parsing in more detail to help clarify what is going on.
Example 4:
a="User-provided"
b="Another user-provided optional value"
c=""
myvarname_a="a"
myvarname_b="b"
myvarname_c="c"
for varname in "myvarname_a" "myvarname_b" "myvarname_c"; do
eval varval=\$$varname
if [ -z "$varval" ]; then
read -p "$varname? " $varname
fi
done
In the first iteration:
varname="myvarname_a"
Bash parses the argument to eval
, and eval
sees literally this at runtime:
eval varval=\$$myvarname_a
The following pseudocode attempts to illustrate how bash interprets the above line of real code, to arrive at the final value executed by eval
. (the following lines descriptive, not exact bash code):
1. eval varval="\$" + "$varname" # This substitution resolved in eval statement
2. .................. "$myvarname_a" # $myvarname_a previously resolved by for-loop
3. .................. "a" # ... to this value
4. eval "varval=$a" # This requires one more parsing step
5. eval varval="User-provided" # Final result of parsing (eval executes this)
Once all the parsing is done, the result is what is executed, and its effect is obvious, demonstrating there is nothing particularly mysterious about eval
itself, and the complexity is in the parsing of its argument.
varval="User-provided"
The remaining code in the example above simply tests to see if the value assigned to $varval is null, and, if so, prompts the user to provide a value.
Here is part of my program related to plotting confidence interval.
ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)
sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
tmp <- 1.96*sqrt(tmp)
y_e_minus[i] <- y_e[i] - tmp
y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')
Actually there is no built in function similar to string.Format function of .NET is available in SQL server.
There is a function FORMATMESSAGE() in SQL server but it mimics to printf() function of C not string.Format function of .NET.
SELECT FORMATMESSAGE('This is the %s and this is the %s.', 'first variable', 'second variable') AS Result
Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.
When you pass an instance as an argument to the method it passes the copy
of the instance. Now, if the instance you pass is a value type
(resides in the stack
) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack
) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.
I like to iterate backward using a for
loop, but this can get tedious compared to foreach
. One solution I like is to create an enumerator that traverses the list backward. You can implement this as an extension method on ArrayList
or List<T>
. The implementation for ArrayList
is below.
public static IEnumerable GetRemoveSafeEnumerator(this ArrayList list)
{
for (int i = list.Count - 1; i >= 0; i--)
{
// Reset the value of i if it is invalid.
// This occurs when more than one item
// is removed from the list during the enumeration.
if (i >= list.Count)
{
if (list.Count == 0)
yield break;
i = list.Count - 1;
}
yield return list[i];
}
}
The implementation for List<T>
is similar.
public static IEnumerable<T> GetRemoveSafeEnumerator<T>(this List<T> list)
{
for (int i = list.Count - 1; i >= 0; i--)
{
// Reset the value of i if it is invalid.
// This occurs when more than one item
// is removed from the list during the enumeration.
if (i >= list.Count)
{
if (list.Count == 0)
yield break;
i = list.Count - 1;
}
yield return list[i];
}
}
The example below uses the enumerator to remove all even integers from an ArrayList
.
ArrayList list = new ArrayList() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foreach (int item in list.GetRemoveSafeEnumerator())
{
if (item % 2 == 0)
list.Remove(item);
}
You can define a class
or id
for input fields.
Or
input {
line-height: 20px;
}
Hope this helps you.
I am using MySQL 5.5.40. This version has the option --all-databases
mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql
This command will create a complete backup of all databases in MySQL server to file named to current date-time.
It might be possible to do this with box-shadow
however, I can't get it to actually apply to an image. Only on solid color backgrounds
body {_x000D_
background: #131418;_x000D_
color: #999;_x000D_
text-align: center;_x000D_
}_x000D_
.mycooldiv {_x000D_
width: 400px;_x000D_
height: 300px;_x000D_
margin: 2% auto;_x000D_
border-radius: 100%;_x000D_
}_x000D_
.red {_x000D_
background: red_x000D_
}_x000D_
.blue {_x000D_
background: blue_x000D_
}_x000D_
.yellow {_x000D_
background: yellow_x000D_
}_x000D_
.green {_x000D_
background: green_x000D_
}_x000D_
#darken {_x000D_
box-shadow: inset 0px 0px 400px 110px rgba(0, 0, 0, .7);_x000D_
/*darkness level control - change the alpha value for the color for darken/ligheter effect */_x000D_
}
_x000D_
Red_x000D_
<div class="mycooldiv red"></div>_x000D_
Darkened Red_x000D_
<div class="mycooldiv red" id="darken"></div>_x000D_
Blue_x000D_
<div class="mycooldiv blue"></div>_x000D_
Darkened Blue_x000D_
<div class="mycooldiv blue" id="darken"></div>_x000D_
Yellow_x000D_
<div class="mycooldiv yellow"></div>_x000D_
Darkened Yellow_x000D_
<div class="mycooldiv yellow" id="darken"></div>_x000D_
Green_x000D_
<div class="mycooldiv green"></div>_x000D_
Darkened Green_x000D_
<div class="mycooldiv green" id="darken"></div>
_x000D_
You might get better results if you try:
console.log(JSON.stringify(functor));
in your action performed method, call:
label1.setText(nameField.getText());
This way, when the button is clicked, label will be updated to the nameField text.
If you need to duplicate more than a few redirects, you might consider using a map:
# map is outside of server block
map $uri $redirect_uri {
~^/issue1/?$ http://example.com/shop/issues/custom_isse_name1;
~^/issue2/?$ http://example.com/shop/issues/custom_isse_name2;
~^/issue3/?$ http://example.com/shop/issues/custom_isse_name3;
# ... or put these in an included file
}
location / {
try_files $uri $uri/ @redirect-map;
}
location @redirect-map {
if ($redirect_uri) { # redirect if the variable is defined
return 301 $redirect_uri;
}
}
I vote for RazorSQL also. It's very powerful in many respects and practically supports most databases out there. I mostly use it for SQL Server, MySQL and PostgreSQL.
Default value doesn't mean default value of data type .Here default value mean value defined at the time of defining function. we have to declare default value of variable while defining variable in function.
HotelsCombined has an easy-to-access and useful service to download the data feed files with hotels. Not exactly API, but something you can get, parse and use. Here is how you do it:
If you are interested in details, you may find the sample Python code to filter CSV file to get hotels for a specific city here:
http://mikhail.io/2012/05/17/api-to-get-the-list-of-hotels/
Update:
Unfortunately, HotelsCombined.com has introduced the new regulations: they've restricted the access to data feeds by default. To get the access, a partner must submit some information on why one needs the data. The HC team will review it and then (maybe) will grant access.
You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup
event, as suggested, and use a regular expression to ensure the value is as you require:
<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
function formatTextArea(textArea) {
textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
}
window.onload = function() {
var textArea = document.getElementById("t");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 13) {
formatTextArea(this);
}
};
};
</script>
There are many suggestions but I found two of them most common.
I first tried export JAVA_OPTS="-Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2"
on command line before startup of program but it didn't work for me.
Then I added the following code in the startup class constructor and it worked for me.
try {
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, null, null);
SSLContext.setDefault(ctx);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Frankly, I don't know in detail why ctx.init(null, null, null);
but all (SSL/TLS) is working fine for me.
There is one more option: System.setProperty("https.protocols", "SSLv3,TLSv1,TLSv1.1,TLSv1.2");
. It will also go in code but I've not tried it.
Yes it is possible in theory as defined by the specification. However there is no practical implementation as yet that would allow this.
Refer: NFC Forum Connection Handover Technical Specification http://www.nfc-forum.org/specs/spec_list/
Quoting from the specification regarding the security - "The Handover Protocol requires transmission of network access data and credentials (the carrier configuration data) to allow one device to connect to a wireless network provided by another device. Because of the close proximity needed for communication between NFC Devices and Tags, eavesdropping of carrier configuration data is difficult, but not impossible, without recognition by the legitimate owner of the devices. Transmission of carrier configuration data to devices that can be brought to close proximity is deemed legitimate within the scope of this specification."
Assuming you have Xcode installed in /Applications
, then you can do this from the command line to start the iPhone Simulator:
$ open /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app
(Xcode 6+):
$ open /Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app
You could create a symbolic-link from your Desktop to make this easier:
$ ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app ~/Desktop
(Xcode 6+):
$ ln -s /Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app ~/Desktop
As pointed out by @JackHahoney, you could also add an alias
to your ~/.bash_profile
:
$ alias simulator='open /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/De??veloper/Applications/iPhone\ Simulator.app'
(Xcode 6+):
$ alias simulator='open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app'
(Xcode 7+):
$ alias simulator='open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app'
Which would mean you could start the iPhone Simulator from the command line with one easy-to-remember word:
$ simulator
Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.
You can modify your query to use double quotes at the beginning and end, and single quotes around $somename
:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";
There's a special function n()
in dplyr to count rows (potentially within groups):
library(dplyr)
mtcars %>%
group_by(cyl, gear) %>%
summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
# cyl gear n
# (dbl) (dbl) (int)
#1 4 3 1
#2 4 4 8
#3 4 5 2
#4 6 3 2
#5 6 4 4
#6 6 5 1
#7 8 3 12
#8 8 5 2
But dplyr also offers a handy count
function which does exactly the same with less typing:
count(mtcars, cyl, gear) # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
# cyl gear n
# (dbl) (dbl) (int)
#1 4 3 1
#2 4 4 8
#3 4 5 2
#4 6 3 2
#5 6 4 4
#6 6 5 1
#7 8 3 12
#8 8 5 2
It means to group by the first column regardless of what it's called. You can do the same with ORDER BY
.