There is no extension methods in Java, but you can have it by manifold as below,
You define "echo" method for strings by below sample,
@Extension
public class MyStringExtension {
public static void echo(@This String thiz) {
System.out.println(thiz);
}
}
And after that, you can use this method (echo) for strings anywhere like,
"Hello World".echo(); //prints "Hello World"
"Welcome".echo(); //prints "Welcome"
String name = "Jonn";
name.echo(); //prints "John"
You can also, of course, have parameters like,
@Extension
public class MyStringExtension {
public static void echo(@This String thiz, String suffix) {
System.out.println(thiz + " " + suffix);
}
}
And use like this,
"Hello World".echo("programming"); //prints "Hello World programming"
"Welcome".echo("2021"); //prints "Welcome 2021"
String name = "Jonn";
name.echo("Conor"); //prints "John Conor"
You can take a look at this sample also, Manifold-sample
Trying to combine the overloading, I tried to use generics but couldn't make it work. I finally figured to use NSNumber instead of trying to overload or use generics. This simplifies to the following:
typealias Dbl = Double // Shorter form
infix operator ** {associativity left precedence 160}
func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {return pow(Dbl(lhs), Dbl(rhs))}
The following code is the same function as above but implements error checking to see if the parameters can be converted to Doubles successfully.
func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {
// Added (probably unnecessary) check that the numbers converted to Doubles
if (Dbl(lhs) ?? Dbl.NaN) != Dbl.NaN && (Dbl(rhs) ?? Dbl.NaN) != Dbl.NaN {
return pow(Dbl(lhs), Dbl(rhs))
} else {
return Double.NaN
}
}
Sub Scrape()
Dim Browser As InternetExplorer
Dim Document As htmlDocument
Dim Elements As IHTMLElementCollection
Dim Element As IHTMLElement
Set Browser = New InternetExplorer
Browser.Visible = True
Browser.navigate "http://www.stackoverflow.com"
Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Set Document = Browser.Document
Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
For Each Element In Elements
Debug.Print Element.innerText
'Questions
'Tags
'Users
'Badges
'Unanswered
'Ask Question
Next Element
Set Document = Nothing
Set Browser = Nothing
End Sub
Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.
MyJar1.jar\META-INF\MANIFEST.MF
Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar
MyJar2.jar\META-INF\MANIFEST.MF
Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar
etc.
Then just run it with java -jar MyJar2.jar
This is my code - by calling the function play()
the video plays or pauses and the button image is changed.
By calling the function volume()
the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You need to use the .toFixed()
method
It takes as a parameter the number of digits to show after the decimal point.
$(document).ready(function() {
$('.add').click(function() {
var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
$('#total').text( value.toFixed(2) );
});
})
strong: assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable
weak: will assign the incoming value to it without retaining it.
So the basic difference is the retaining of the new variable. Generaly you want to retain it but there are situations where you don't want to have it otherwise you will get a retain cycle and can not free the memory the objects. Eg. obj1 retains obj2 and obj2 retains obj1. To solve this kind of situation you use weak references.
mMyTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(m_txtSearchText.getWindowToken(),
InputMethodManager.RESULT_UNCHANGED_SHOWN);
return true;
}
return false;
}
});
I just wanted to add this answer specifically for Mac Users.
My server was running perfectly fine until I updated my xcode. The while starting my rails server the error was shown like this
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/user/.rvm/rubies/ruby-1.9.3-p448/bin/ruby extconf.rb --with-mysql-
checking for rb_thread_blocking_region()... /Users/user/.rvm/rubies/ruby-1.9.3-
p448/lib/ruby/1.9.1/mkmf.rb:381:in `try_do': The compiler failed to generate an
executable file. (RuntimeError)
And there was suggestion to install mysql2 gem at the end of the error message. So when i tried installing it I got the error as above mentioned in this question. The error I got is as follows
ERROR: Error installing mysql2:
ERROR: Failed to build gem native extension.
So as suggested in this post I tried 'brew install mysql' and that quitted saying that mysql version so and so already installed. But there was warning before it saying
Warning: You have not agreed to the Xcode license.
Builds will fail! Agree to the license by opening Xcode.app or running:
xcodebuild -license
Then I tried this sudo xcodebuild -license
and type 'agree' at the end. You have to be root to agree to the license.
After this, I again tried bundle install and then everything is working fine as normal. [ Even due to this xcode updation, I had problem with my tower also.]
The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?
It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.
Dictionary in python has a get('key', default) method. So you can just set a default value in case there is no key.
values = {...}
myValue = values.get('Key', None)
Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:
(function($) {
$.fn.getAttributes = function () {
var elem = this,
attr = {};
if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) {
n = n.nodeName||n.name;
v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
if(v != undefined && v !== false) attr[n] = v
})
return attr
}
})(jQuery);
Usage:
var attribs = $('#some_id').getAttributes();
I figured it out myself with the help of someone's answer. But he deleted it for some reason.
Here's the solution:
Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact
$(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
if(windowH > wrapperH) {
$('#wrapper').css({'height':($(window).height())+'px'});
}
$(window).resize(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
var differenceH = windowH - wrapperH;
var newH = wrapperH + differenceH;
var truecontentH = $('#truecontent').height();
if(windowH > truecontentH) {
$('#wrapper').css('height', (newH)+'px');
}
})
});
While this may not be the ideal answer but try this:
style={{top:'0', bottom:'0', left:'0', right:'0', position: 'absolute'}}
It keeps the size attached to borders which is not what you want but gives you somewhat same effect.
There is no elegant way of getting the last element of a list in Java (compared to e.g. items[-1]
in Python).
You have to use list.get(list.size()-1)
.
When working with lists obtained by complicated method calls, the workaround lies in temporary variable:
List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);
This is the only option to avoid ugly and often expensive or even not working version:
return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);
It would be nice if fix for this design flaw was introduced to Java API.
Here's a Kotlin Extension Function I have for this
fun TextView.setColouredSpan(word: String, color: Int) {
val spannableString = SpannableString(text)
val start = text.indexOf(word)
val end = text.indexOf(word) + word.length
try {
spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannableString
} catch (e: IndexOutOfBoundsException) {
println("'$word' was not not found in TextView text")
}
}
Use it after you have set your text to the TextView like so
private val blueberry by lazy { getColor(R.color.blueberry) }
textViewTip.setColouredSpan("Warning", blueberry)
According to the Python doc, we can also use class.__mro__
attribute or class.mro()
method:
class Suit:
pass
class Heart(Suit):
pass
class Spade(Suit):
pass
class Diamond(Suit):
pass
class Club(Suit):
pass
>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)
Suit in Heart.mro() # True
object in Heart.__mro__ # True
Spade in Heart.mro() # False
Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.
Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:
$ uname -a
armv7l
Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.
You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.
You can follow the GitHub issue for 64-bit support here, if you're interested.
In my case I used the option android:isolatedProcess="true"
for a service
in the AndroidManifest.xml
.
As soon as I removed it, the error disappeared...
Here is something I used to drop files and/or folders full of files. In my case I was filtering for *.dwg
files only and chose to include all subfolders.
fileList
is an IEnumerable
or similar In my case was bound to a WPF control...
var fileList = (IList)FileList.ItemsSource;
See https://stackoverflow.com/a/19954958/492 for details of that trick.
The drop Handler ...
private void FileList_OnDrop(object sender, DragEventArgs e)
{
var dropped = ((string[])e.Data.GetData(DataFormats.FileDrop));
var files = dropped.ToList();
if (!files.Any())
return;
foreach (string drop in dropped)
if (Directory.Exists(drop))
files.AddRange(Directory.GetFiles(drop, "*.dwg", SearchOption.AllDirectories));
foreach (string file in files)
{
if (!fileList.Contains(file) && file.ToLower().EndsWith(".dwg"))
fileList.Add(file);
}
}
SELECT CAST(FLOOR(CAST(DATEADD(d, 1 - DAY(GETDATE()), GETDATE()) AS FLOAT)) AS DATETIME)
I got this error when I forgot to add new form fields/database columns to the $fillable
array in the Laravel model - the model was stripping them out.
If its SQL Server you can do it on the column properties within design view
Try this?:
ALTER TABLE dbo.TableName
ADD CONSTRAINT DF_TableName_ColumnName
DEFAULT '01/01/2000' FOR ColumnName
In my case it was a Chrome extension and Firefox add-on by Avira called "Avira Browser Safety". I had problems with version 1.7.4. In my specific case I wanted to login to a website called gliffy.com for making diagrams, but after logging in I got an blank page. If you use F12 (console) in Chrome you can see all these ERR_BLOCKED_BY_CLIENT (and other) errors.
The main difference is that appendChild
is a DOM method and append
is a jQuery method. The second one uses the first as you can see on jQuery source code
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
If you're using jQuery library on your project, you'll be safe always using append
when adding elements to the page.
For only a small amount of objects the update_or_create works well, but if you're doing over a large collection it won't scale well. update_or_create always first runs a SELECT and thereafter an UPDATE.
for the_bar in bars:
updated_rows = SomeModel.objects.filter(bar=the_bar).update(foo=100)
if not updated_rows:
# if not exists, create new
SomeModel.objects.create(bar=the_bar, foo=100)
This will at best only run the first update-query, and only if it matched zero rows run another INSERT-query. Which will greatly increase your performance if you expect most of the rows to actually be existing.
It all comes down to your use case though. If you are expecting mostly inserts then perhaps the bulk_create() command could be an option.
You could use only delegate which is best for callback functions:
public class ServerRequest
{
public delegate void CallBackFunction(string input);
public void DoRequest(string request, CallBackFunction callback)
{
// do stuff....
callback(request);
}
}
and consume this like below:
public class Class1
{
private void btn_click(object sender, EventArgs e)
{
ServerRequest sr = new ServerRequest();
var callback = new ServerRequest.CallBackFunction(CallbackFunc);
sr.DoRequest("myrequest",callback);
}
void CallbackFunc(string something)
{
}
}
These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)
Dockerfile
FROM swiftdocker/swift
MAINTAINER Nobody
RUN apt-get update && apt-get -y install openssh-server supervisor
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 22
CMD ["/usr/bin/supervisord"]
supervisord.conf
[supervisord]
nodaemon=true
[program:sshd]
command=/usr/sbin/sshd -D
to build / run start daemon / jump into shell.
docker build -t swift3-ssh .
docker run -p 2222:22 -i -t swift3-ssh
docker ps # find container id
docker exec -i -t <containerid> /bin/bash
Awk examples looks complex here, here is simple Bash shell syntax:
command | while read -a cols; do echo ${cols[@]:1}; done
Where 1
is your nth column counting from 0.
Given this content of file (in.txt
):
c1
c1 c2
c1 c2 c3
c1 c2 c3 c4
c1 c2 c3 c4 c5
here is the output:
$ while read -a cols; do echo ${cols[@]:1}; done < in.txt
c2
c2 c3
c2 c3 c4
c2 c3 c4 c5
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
If the checkbox is checked you will get a value for it in your $_POST
array. If it isn't the element will be omitted from the array altogether.
The easiest way to test it is like this:
if (isset($_POST['myCheckbox'])) {
$checkBoxValue = "yes";
} else {
$checkBoxValue = "no";
}
For your code, add it immediately below the other preprocessing:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
$newsletter = "yes";
} else {
$newsletter = "no";
}
You'll also need to change the HTML slightly. Change this line:
<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter<br>
to this:
<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up for newsletter<br>
^^^ remove square brackets here.
Your local branch doensn't know about the remote branch. If you don't tell git that your local branch (master) is supposed to compare itself to the remote counterpart (origin/master in this case); then git status won't tell you the difference between your branch and the remote one. So you should use:
git branch --set-upstream-to origin/master
or with the short option:
git branch -u origin/master
This options --set-upstream-to (or -u in short) was introduced in git 1.8.0.
Once you have set this option; git status
will show you something like:
# Your branch is ahead of 'origin/master' by 1 commit.
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
The scope of a variable is always the block it is inside. For example if you do something like
if(...)
{
int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
int y = 8; //y is created
} //y leaves scope, since the block ends.
cout << y << endl; //Gives error since y is not defined.
The solution is to define y outside of the if blocks
int y; //y is created
if(...)
{
y = 5;
}
else
{
y = 8;
}
cout << y << endl; //Ok
In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:
//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
int y, c;
int d=date;
if (month==1||month==2)
{
y=((year-1)%100);
c=(year-1)/100;
}
else
{
y=year%100;
c=year/100;
}
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}
You can add a form onsubmit handler, something like:
<form onsubmit="return validate();">
</form>
<script>function validate() {
// check if input is bigger than 3
var value = document.getElementById('titleeee').value;
if (value.length < 3) {
return false; // keep form from submitting
}
// else form is good let it submit, of course you will
// probably want to alert the user WHAT went wrong.
return true;
}</script>
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
import a_module
print(a_module.__file__)
Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:
import os
path = os.path.abspath(a_module.__file__)
You can also try:
path = os.path.dirname(a_module.__file__)
To get the module's directory.
In my case, I was using mkvirtualenv
, but didn't tell it I was going to be using python3. I got this error:
mkvirtualenv hug
pip3 install hug -U
....
error: could not create '/usr/lib/python3.4/site-packages': Permission denied
It worked after specifying python3:
mkvirtualenv --python=/usr/bin/python3 hug
pip3 install hug -U
Try this Demo
HTML
<table>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
</table>
CSS
td:nth-of-type(2) {
padding-right: 10px;
}
Here's the raw reference of PDF 1.7, and here's an article describing the structure of a PDF file. If you use Vim, the pdftk plugin is a good way to explore the document in an ever-so-slightly less raw form, and the pdftk utility itself (and its GPL source) is a great way to tease documents apart.
You can reset the padding (and I think everything else) with initial
to the default.
p {
padding: initial;
}
$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"<br/>";
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("script.bat");
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader logReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String logLine = null;
while ( (logLine = logReader.readLine()) != null) {
System.out.println("Script output: " + logLine);
}
}
}
By using this line: pb.redirectErrorStream(true);
we can combine InputStream and ErrorStream
The problem appear when we are using PHP 5.1 on Redhat or Cent OS
RUN: Can be many, and it is used in build process, e.g. install multiple libraries
CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"]
, ["node", "app.js"]
)
Strings aren't value types, and never will be ;-)
A function is tail recursive if each recursive case consists only of a call to the function itself, possibly with different arguments. Or, tail recursion is recursion with no pending work. Note that this is a programming-language independent concept.
Consider the function defined as:
g(a, b, n) = a * b^n
A possible tail-recursive formulation is:
g(a, b, n) | n is zero = a
| n is odd = g(a*b, b, n-1)
| otherwise = g(a, b*b, n/2)
If you examine each RHS of g(...)
that involves a recursive case, you'll find that the whole body of the RHS is a call to g(...)
, and only that. This definition is tail recursive.
For comparison, a non-tail-recursive formulation might be:
g'(a, b, n) = a * f(b, n)
f(b, n) | n is zero = 1
| n is odd = f(b, n-1) * b
| otherwise = f(b, n/2) ^ 2
Each recursive case in f(...)
has some pending work that needs to happen after the recursive call.
Note that when we went from g'
to g
, we made essential use of associativity
(and commutativity) of multiplication. This is not an accident, and most cases where you will need to transform recursion to tail-recursion will make use of such properties: if we want to eagerly do some work rather than leave it pending, we have to use something like associativity to prove that the answer will be the same.
Tail recursive calls can be implemented with a backwards jump, as opposed to using a stack for normal recursive calls. Note that detecting a tail call, or emitting a backwards jump is usually straightforward. However, it is often hard to rearrange the arguments such that the backwards jump is possible. Since this optimization is not free, language implementations can choose not to implement this optimization, or require opt-in by marking recursive calls with a 'tailcall' instruction and/or choosing a higher optimization setting.
Some languages (e.g. Scheme) do, however, require all implementations to optimize tail-recursive functions, maybe even all calls in tail position.
Backwards jumps are usually abstracted as a (while) loop in most imperative languages, and tail-recursion, when optimized to a backwards jump, is isomorphic to looping.
The solution for those who use composer is to use a volume pointing to the parent folder:
#docker-composer.yml
foo:
build: foo
volumes:
- ./:/src/:ro
But I'm pretty sure the can be done playing with volumes in Dockerfile.
StringBuilder sb = new StringBuilder();
SaveFileDialog fileSave = new SaveFileDialog();
IEnumerable<string> columnNames = tbCifSil.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in tbCifSil.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
fileSave.ShowDialog();
File.WriteAllText(fileSave.FileName, sb.ToString());
You can delete column like this:
df.drop("column Name).columns
In your case :
df.drop("id").columns
If you want to drop more than one column you can do:
dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")
You use mysql_real_escape_string() in code similar to the following one.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password)
);
As the documentation says, its purpose is escaping special characters in the string passed as argument, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). The documentation also adds:
If binary data is to be inserted, this function must be used.
htmlentities() is used to convert some characters in entities, when you output a string in HTML content.
only variable/object declaration statement are written outside of method
public class details{
public static void main(String arg[]){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
here is example try to learn java book and see the syntax then try to develop the program
You want to focus on immutability in Scala generally by eliminating any vars. Readability is still important for your fellow man so:
Try:
scala> val list = for(i <- 1 to 10) yield i
list: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
You probably don't even need to convert to a list in most cases :)
The indexed seq will have everything you need:
That is, you can now work on that IndexedSeq:
scala> list.foldLeft(0)(_+_)
res0: Int = 55
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
Found the answer:
DO NOT put a __init__.py
file in a folder containing TESTS if you plan on using pytest. I had one such file, deleting it solved the problem.
This was actually buried in the comments to the second answer of PATH issue with pytest 'ImportError: No module named YadaYadaYada' so I did not see it, hope it gets more visibility here.
Plug in your device and run adb shell
which will get you a command shell on your device. You don't have permission to read /storage/emulated/
but since you know it's in subdirectory 0 just go cd /storage/emulated/0
and you will be able to look around and interact as aspected.
Note: you can use adb
wirelessly as well
You can use Java 8 Stream API.
You can create a Stream of objects and collect them as a List.
private List<String> symbolsPresent = Stream.of("ONE", "TWO", "THREE", "FOUR")
.collect(Collectors.toList());
Possible in CSS3: http://www.w3.org/TR/css3-writing-modes/#writing-mode
Why not change the orders of the tags? Your HTML page isn't made out of stone, are they?
For coffeescript lovers
expect( => someMethodCall(arg1, arg2)).toThrow()
Referring to Spring Boot application as a Service as well, I would go for the systemd
version, since it's the easiest, least verbose, and best integrated into modern distros (and even the not-so-modern ones like CentOS 7.x).
If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk
, HH
nor hh
. I suggest that you use something like this:
DateTimeFormatter defaultTimeFormatter
= DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
System.out.format("%s: %s%n",
Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));
The point is that it gives different output in different default locales. For example:
en_SS: 12:00 AM fr_BL: 00:00 ps_AF: 0:00 es_CO: 12:00 a.m.
The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.
I furthermore suggest that you don’t use SimpleDateFormat
. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.
Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):
Symbol Meaning Presentation Examples
------ ------- ------------ -------
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-day (1-24) number 24
H hour-of-day (0-23) number 0
In practice H
and h
are used. As far as I know k
and K
are not (they may just have been included for the sake of completeness). But let’s just see them all in action:
DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("hh:mm a HH:mm kk:mm KK:mm a", Locale.ENGLISH);
System.out.println(LocalTime.of(0, 0).format(timeFormatter));
System.out.println(LocalTime.of(1, 15).format(timeFormatter));
System.out.println(LocalTime.of(11, 25).format(timeFormatter));
System.out.println(LocalTime.of(12, 35).format(timeFormatter));
System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM 00:00 24:00 00:00 AM 01:15 AM 01:15 01:15 01:15 AM 11:25 AM 11:25 11:25 11:25 AM 12:35 PM 12:35 12:35 00:35 PM 01:40 PM 13:40 13:40 01:40 PM
If you don’t want the leading zero, just specify one pattern letter, that is h
instead of hh
or H
instead of HH
. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.
DateTimeFormatter
.Use this
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
This can be used to grab the whole webpage as a string of html, i.e., "<html>...</html>"
Note
You need to declare the following 'uses-permission' in the android manifest xml file
... answer by @Squonk here
And also check this answer
Let assume i am having a RestController
with GET/POST/PUT/DELETE
operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.
@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {
@Autowired
private AppService service;
@GetMapping
public MyAppResponse<AppEntity> get() throws Exception {
MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
service.getApp().stream().forEach(x -> response.addData(x));
return response;
}
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
//Validation code
service.createApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@PutMapping
public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {
//Validation code
service.updateApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {
//Validation
service.deleteApp(request.id);
return ResponseEntity.ok(HttpStatus.OK);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
public class AppControllerTest extends BaseTest {
@MockBean
private IIdmsService service;
private static final String URI = "/myapi/myApp";
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void testGet() throws Exception {
AppEntity entity = new AppEntity();
List<AppEntity> dataList = new ArrayList<AppEntity>();
AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
entity.setId(1);
entity.setCreated_at("2020-02-21 17:01:38.717863");
entity.setCreated_by(“Abhinav Kr”);
entity.setModified_at("2020-02-24 17:01:38.717863");
entity.setModified_by(“Jyoti”);
dataList.add(entity);
dataResponse.setData(dataList);
Mockito.when(service.getApp()).thenReturn(dataList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI)
.accept(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String expectedJson = this.mapToJson(dataResponse);
String outputInJson = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals(expectedJson, outputInJson);
}
@Test
public void testCreate() throws Exception {
AppRequest request = new AppRequest();
request.createdBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “India”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
service.createApp(request);
Mockito.verify(service, Mockito.times(1)).createApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testUpdate() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
request.modifiedBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “Bharat”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
service.updateApp(request);
Mockito.verify(service, Mockito.times(1)).updateApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.put(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testDelete() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
service.deleteApp(request.id);
Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
from __future__ import division
import random
from collections import Counter
def num_gen(num_probs):
# calculate minimum probability to normalize
min_prob = min(prob for num, prob in num_probs)
lst = []
for num, prob in num_probs:
# keep appending num to lst, proportional to its probability in the distribution
for _ in range(int(prob/min_prob)):
lst.append(num)
# all elems in lst occur proportional to their distribution probablities
while True:
# pick a random index from lst
ind = random.randint(0, len(lst)-1)
yield lst[ind]
Verification:
gen = num_gen([(1, 0.1),
(2, 0.05),
(3, 0.05),
(4, 0.2),
(5, 0.4),
(6, 0.2)])
lst = []
times = 10000
for _ in range(times):
lst.append(next(gen))
# Verify the created distribution:
for item, count in Counter(lst).iteritems():
print '%d has %f probability' % (item, count/times)
1 has 0.099737 probability
2 has 0.050022 probability
3 has 0.049996 probability
4 has 0.200154 probability
5 has 0.399791 probability
6 has 0.200300 probability
Just add your own index. Keep it simple.
int i = 0;
foreach (var item in Collection)
{
item.index = i;
++i;
}
build.gradle
dependencies {
compile 'com.google.android.gms:play-services-vision:9.4.0+'
}
Set View
CameraSourcePreview mPreview = (CameraSourcePreview) findViewById(R.id.preview);
GraphicOverlay mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
CameraSource mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
mPreview.start(mCameraSource, mGraphicOverlay);
In my case php-fpm outputs 500 error without any logging because of missing php-mysql module. I moved joomla installation to another server and forgot about it. So apt-get install php-mysql
and service restart solved it.
I started with trying to fix broken logging without success. Finally with strace
i found fail message after db-related system calls. Though my case is not directly related to op's question, I hope it could be useful.
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date
if you want to compare dates, ignoring the time part, make an use of DateTime.Year
and DateTime.DayOfYear
properties.
code snippet
DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
Console.WriteLine("d1 < d2");
else
if (d1.DayOfYear < d2.DayOfYear)
Console.WriteLine("d1 < d2");
If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.
<Location />
ProxyPass http://localhost:1339/ retry=0
ProxyPassReverse http://localhost:1339/
ProxyPreserveHost On
ProxyErrorOverride Off
</Location>
To get the IP address have following options
console.log(">>>", req.ip);// this works fine for me returned a valid ip address
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address
So either use req.ip or req.headers['x-forwarded-for']
I am just adding example here because I think examples make it easier to understand.
In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().
For example:
int main()
{
int num,num2;
scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i
printf("%d\t%d",num,num2);
return 0;
}
Output:
You can see the different results for identical inputs.
num
:
We are reading num
using %d
so when we enter 010
it ignores the first 0
and treats it as decimal 10
.
num2
:
We are reading num2
using %i
.
That means it will treat decimals, octals, and hexadecimals differently.
When it give num2
010
it sees the leading 0
and parses it as octal.
When we print it using %d
it prints the decimal equivalent of octal 010
which is 8
.
there might be the situation your machine is managed by Puppet or so. Then changing root .profile or .bash_rc file does not work at all. Therefore you could add the following to your .profile file. After that you can use "mydo" instead of "sudo". It works perfectly for me.
function mydo() {
echo Executing sudo with: "$1" "${@:2}"
sudo $(which $1) "${@:2}"
}
Visit my page: http://www.danielkoitzsch.de/blog/2016/03/16/sudo-returns-xyz-command-not-found/
You can assign default parameter values inline when you first create the mixin:
@mixin clearfix($width: 'auto') {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
When passing parameters through the URL you're able to retrieve the values as GET parameters.
Use this:
$variable = $_GET['param_name'];
//Or as you have it
$ppc = $_GET['ppc'];
It is safer to check for the variable first though:
if (isset($_GET['ppc'])) {
$ppc = $_GET['ppc'];
} else {
//Handle the case where there is no parameter
}
Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php
EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from @emc who details a WordPress function which accomplishes this goal securely.
This line:
eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;
is same as:
eventCustom.DateTimeEnd = dateTimeEndResult = (true ? (DateTime?)null : dateTimeEndResult);
because the conditional operator ?
has a higher precedence than the assignment operator =
. That's why you always get null for eventCustom.DateTimeEnd
. (MSDN Ref)
Since the id of the connect button is now changed to "colab-connect-button", the following code can be used to keep clicking on the button.
function ClickConnect(){
console.log("Clicked on connect button");
document.querySelector("colab-connect-button").click()
}
setInterval(ClickConnect,60000)
If still, this doesn't work, then follow the steps given below:
function ClickConnect(){
console.log("Clicked on connect button");
document.querySelector("Put ID here").click() // Change id here
}
setInterval(ClickConnect,60000)
Case matters
I manually added a submodule :k3b-geohelper
to the
settings.gradle
file
include ':app', ':k3b-geohelper'
and everthing works fine on my mswindows build system
When i pushed the update to github the fdroid build system failed with
Cannot evaluate module k3b-geohelper : Configuration with name 'default' not found
The final solution was that the submodule folder was named k3b-geoHelper
not k3b-geohelper
.
Under MSWindows case doesn-t matter but on linux system it does
Use JSON Simple,
http://code.google.com/p/json-simple/
Which has a small foot-print, no dependencies so it's perfect for Android.
You can do something like this,
Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;
template system, useful if you want to create colorful line text without creating full style for every block
var tpl = 'background-color:greenyellow; border:3px solid orange; font-size:18px; font-weight: bold;padding:3px 5px;color:';
console.log('%cNo #1' + '.%cRed Text' + '%cBlue Text',
tpl+'magenta', tpl+'red', tpl+'blue');
In reference to the quick reference list, specifically you can use the following :
\.\ Root Directory + Current directory (Drive Letter)
IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS
IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS
Additionally we can also use LIKE but I usually don't use LIKE.
JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm
page.
One idea is to let the the browser know that it should redirect by adding a redirect
variable to to the resulting object and checking for it in JQuery:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")
and in JQuery you do on success(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Hope that helps.
My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.
As stated from David Cournapeau, use figure().
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Or subplot(121) / subplot(122) for the same plot, different position.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
If lists always have the same structure, as in the example, then a simpler solution is
mapply(c, first, second, SIMPLIFY=FALSE)
I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".
It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.
Share a Controller
Two directives can use the same controller by passing the same method to two directives, like so:
app.controller( 'MyCtrl', function ( $scope ) {
// do stuff...
});
app.directive( 'directiveOne', function () {
return {
controller: 'MyCtrl'
};
});
app.directive( 'directiveTwo', function () {
return {
controller: 'MyCtrl'
};
});
Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.
Require a Controller
If you want to share the same instance of a controller, then you use require
.
require
ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel
.
^require
, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.
In either event, you have to use the two directives together for this to work. require
is a way of communicating between components.
Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive
You should use onclick method because the function run once when the page is loaded and no button will be clicked then
So you have to add an even which run every time the user press any key to add the changes to the div background
So the function should be something like this
htmlelement.onclick() = function(){
//Do the changes
}
So your code has to look something like this :
var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");
yes.onclick = function(){
box.style.backgroundColor = "red";
}
no.onclick = function(){
box.style.backgroundColor = "green";
}
This is meaning that when #yes button is clicked the color of the div is red and when the #no button is clicked the background is green
Here is a Jsfiddle
As mentioned in Jonathan's answer, FETCH_HEAD corresponds to the file .git/FETCH_HEAD
. Typically, the file will look like this:
71f026561ddb57063681109aadd0de5bac26ada9 branch 'some-branch' of <remote URL>
669980e32769626587c5f3c45334fb81e5f44c34 not-for-merge branch 'some-other-branch' of <remote URL>
b858c89278ab1469c71340eef8cf38cc4ef03fed not-for-merge branch 'yet-some-other-branch' of <remote URL>
Note how all branches but one are marked not-for-merge
. The odd one out is the branch that was checked out before the fetch. In summary: FETCH_HEAD essentially corresponds to the remote version of the branch that's currently checked out.
body, html {
display: table;
height: 100%;
width: 100%;
}
.container {
display: table-cell;
vertical-align: middle;
}
.container .box {
width: 100px;
height: 100px;
background: red;
margin: 0 auto;
}
"width:100%" for the "body" tag is only for an example. In a real project you may remove this property.
It works with just this:
.slideContainer {
white-space: nowrap;
}
.slide {
display: inline-block;
width: 600px;
white-space: normal;
}
I did originally have float : left;
and that prevented it from working correctly.
Thanks for posting this solution.
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
Although approved answer is correct, I want to show a bit different approach (based on this answer).
Vscode can automatically choose correct anaconda environment if you start vscode from it. Just add to user/workspace settings:
{
"python.pythonPath": "C:/<proper anaconda path>/Anaconda3/envs/${env:CONDA_DEFAULT_ENV}/python"
}
It works on Windows, macOS and probably Unix. Further read on variable substitution in vscode: here.
If you really want an exe Excelsior JET is a professional level product that compiles to native code:
http://www.excelsior-usa.com/jet.html
You can also look at JSMooth:
http://jsmooth.sourceforge.net/
And if your application is compatible with its compatible with AWT/Apache classpath then GCJ compiles to native exe.
Just do System.out.println(e.getActionCommand());
inside actionPerformed(ActionEvent e)
function. This will tell you which command is just performed.
or
if(e.getActionCommand().equals("Add")){
System.out.println("Add button pressed");
}
All answers above are correct and this is my take on this:
To differentiate between frame and bounds CONCEPTS developer should read:
- relative to the superview (one parent view) it is contained within = FRAME
- relative to its own coordinate system, determines its subview location = BOUNDS
"bounds" is confusing because it gives the impression that the coordinates are the position of the view for which it is set. But these are in relations and adjusted according to the frame constants.
You can use sed
to parse the ini configuration file, especially when you've section names like:
# last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Widgets Inc.
[database]
# use IP address in case network name resolution is not working
server=192.0.2.62
port=143
file=payroll.dat
so you can use the following sed
script to parse above data:
# Configuration bindings found outside any section are given to
# to the default section.
1 {
x
s/^/default/
x
}
# Lines starting with a #-character are comments.
/#/n
# Sections are unpacked and stored in the hold space.
/\[/ {
s/\[\(.*\)\]/\1/
x
b
}
# Bindings are unpacked and decorated with the section
# they belong to, before being printed.
/=/ {
s/^[[:space:]]*//
s/[[:space:]]*=[[:space:]]*/|/
G
s/\(.*\)\n\(.*\)/\2|\1/
p
}
this will convert the ini data into this flat format:
owner|name|John Doe
owner|organization|Acme Widgets Inc.
database|server|192.0.2.62
database|port|143
database|file|payroll.dat
so it'll be easier to parse using sed
, awk
or read
by having section names in every line.
Credits & source: Configuration files for shell scripts, Michael Grünewald
Alternatively, you can use this project: chilladx/config-parser
, a configuration parser using sed
.
ngOnInit() {
const $ = window["$"];
$('.flexslider').flexslider({
animation: 'slide',
start: function (slider) {
$('body').removeClass('loading')
}
})
}
UPDATE:
[o for d in [{}] for o in lst if o.name != "" or d.setdefault("", o) == o]
or using filter
and lambda
:
flag = {}
filter(lambda o: bool(o.name) or flag.setdefault("", o) == o, lst)
Previous Answer
OK, are you stuck on using filter and lambda?
It seems like this would be better served with a dictionary comprehension,
{o.name : o for o in input}.values()
I think the reason that Python doesn't allow assignment in a lambda is similar to why it doesn't allow assignment in a comprehension and that's got something to do with the fact that these things are evaluated on the C
side and thus can give us an increase in speed. At least that's my impression after reading one of Guido's essays.
My guess is this would also go against the philosophy of having one right way of doing any one thing in Python.
There is a flag --files-from
that does exactly what you want. From man rsync
:
--files-from=FILE
Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or - for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier:
The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off).
The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off).
The --archive (-a) option’s behavior does not imply --recursive (-r), so specify it explicitly, if you want it.
These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options).
The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command:
rsync -a --files-from=/tmp/foo /usr remote:/backup
If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir’s entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a). Also note that the effect of the (enabled by default) --relative option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case).
In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example:
rsync -a --files-from=:/path/file-list src:/ /tmp/copy
This would copy all the files specified in the /path/file-list file that was located on the remote "src" host.
If the --iconv and --protect-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host’s charset to the receiving host’s charset.
NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re-visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements.
The right answer is:
android {
....
....
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
Furthermore, if your external source directory is not under src/main
, you could use a relative path like this:
sourceSets {
main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}
solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.
You can use Java's Scanner
class to parse words of a file and process them in your application, and then use a BufferedWriter
or FileWriter
to write back to the file, applying the changes.
I think there is a more efficient way of getting the iterator's position of the scanner at some point, in order to better implement editting. But since files are either open for reading, or writing, I'm not sure regarding that.
In any case, you can use libraries already available for parsing of XML files, which have all of this implemented already and will allow you to do what you want easily.
You need
test.split("\\|");
split
uses regular expression and in regex |
is a metacharacter representing the OR
operator. You need to escape that character using \
(written in String as "\\"
since \
is also a metacharacter in String literals and require another \
to escape it).
You can also use
test.split(Pattern.quote("|"));
and let Pattern.quote
create the escaped version of the regex representing |
.
An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG
in <cfloat>
). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG
to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15
) because of that.
The nextafter()
function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.
This program:
#include <cstdio>
#include <cfloat>
#include <cmath>
int main() {
double x = 1.0/7.0;
printf("FLT_RADIX = %d\n", FLT_RADIX);
printf("DBL_DIG = %d\n", DBL_DIG);
printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}
gives me this output on my system:
FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288
(You can replace %.17g
by, say, %.64g
to see more digits, none of which are significant.)
As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0
(5
) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6
, not 5
. Replacing 1.0/7.0
by 1.0/3.0
gives this output:
FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337
which shows about 16 decimal digits of precision, as you'd expect.
Try this regex:
^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$
Explanation of the regex using Perl's YAPE is as below:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
----------------------------------------------------------------------
\d{1,4} digits (0-9) (between 1 and 4 times
(matching the most amount possible))
----------------------------------------------------------------------
[\s-] any character of: whitespace (\n, \r,
\t, \f, and " "), '-'
----------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
0+ '0' (1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{10} digits (0-9) (10 times)
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Just adding a point to the whole discussion as to why this warning comes up (It wasn't clear to me before). The reason one gets this is as mentioned before is because 'a' in this case is a vector and the inequality 'a>0' produces another vector of TRUE and FALSE (where 'a' is >0 or not).
If you would like to instead test if any value of 'a>0', you can use functions - 'any' or 'all'
Best
You can delete by 1 or more properties:
//Delets an json object from array by given object properties.
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); ->
//removes all items with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
var deleted = 0;
for (var i = 0, count = indexes.length; i < count; i++) {
this.splice(indexes[i], 1);
deleted++;
}
return deleted;
}
The comment for orderBy
source code notes: Keys are field and values are the order, being either ASC or DESC.
. So you can do orderBy->(['field' => Criteria::ASC])
.
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.
I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore
(and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.
I first commited the actual changes I had made, then went about solving this - took me far too long.
I tried git rm -r --cached .
but would always get path-spec
ERRORS, with different variations of the path-spec
as well as with the -f
and -r
flags.
git status
would still show the filenames, so I tried using some of those verbatim with git rm -cached
, but no luck.
Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe).
I have finally removed these entries for good using
git reset
I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.
In a servlet based artifact, such as @WebServlet
, @WebFilter
and @WebListener
, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped
by:
Bean bean = (Bean) request.getAttribute("beanName");
and @ManagedBean @SessionScoped
by:
Bean bean = (Bean) request.getSession().getAttribute("beanName");
and @ManagedBean @ApplicationScoped
by:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null
. You'd then need to manually create the bean and use setAttribute("beanName", bean)
.
If you're able to use CDI @Named
instead of the since JSF 2.3 deprecated @ManagedBean
, then it's even more easy, particularly because you don't anymore need to manually create the beans:
@Inject
private Bean bean;
Note that this won't work when you're using @Named @ViewScoped
because the bean can only be identified by JSF view state and that's only available when the FacesServlet
has been invoked. So in a filter which runs before that, accessing an @Inject
ed @ViewScoped
will always throw ContextNotActiveException
.
Only when you're inside @ManagedBean
, then you can use @ManagedProperty
:
@ManagedProperty("#{bean}")
private Bean bean;
Note that this doesn't work inside a @Named
or @WebServlet
or any other artifact. It really works inside @ManagedBean
only.
If you're not inside a @ManagedBean
, but the FacesContext
is readily available (i.e. FacesContext#getCurrentInstance()
doesn't return null
), you can also use Application#evaluateExpressionGet()
:
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
which can be convenienced as follows:
@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
and can be used as follows:
Bean bean = findBean("bean");
For merging first branch to second one:
on first branch: git merge secondBranch
on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch
Even though is not the fastest choice, if performance is not an issue you can use:
sum(~np.isnan(data))
.
In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop
In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop
In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop
This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}
By default, an inline definition is only valid in the current translation unit.
If the storage class is extern
, the identifier has external linkage and the inline definition also provides the external definition.
If the storage class is static
, the identifier has internal linkage and the inline definition is invisible in other translation units.
If the storage class is unspecified, the inline definition is only visible in the current translation unit, but the identifier still has external linkage and an external definition must be provided in a different translation unit. The compiler is free to use either the inline or the external definition if the function is called within the current translation unit.
As the compiler is free to inline (and to not inline) any function whose definition is visible in the current translation unit (and, thanks to link-time optimizations, even in different translation units, though the C standard doesn't really account for that), for most practical purposes, there's no difference between static
and static inline
function definitions.
The inline
specifier (like the register
storage class) is only a compiler hint, and the compiler is free to completely ignore it. Standards-compliant non-optimizing compilers only have to honor their side-effects, and optimizing compilers will do these optimizations with or without explicit hints.
inline
and register
are not useless, though, as they instruct the compiler to throw errors when the programmer writes code that would make the optimizations impossible: An external inline
definition can't reference identifiers with internal linkage (as these would be unavailable in a different translation unit) or define modifiable local variables with static storage duration (as these wouldn't share state accross translation units), and you can't take addresses of register
-qualified variables.
Personally, I use the convention to mark static
function definitions within headers also inline
, as the main reason for putting function definitions in header files is to make them inlinable.
In general, I only use static inline
function and static const
object definitions in addition to extern
declarations within headers.
I've never written an inline
function with a storage class different from static
.
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
try:
[checked]="item.checked"
check out: How to Deal with Different Form Controls in Angular
You can try with textContent.
var productId = val[key].textContent;
Worth noting that ||
will also return true
if BOTH A
and B
are true
.
In JavaScript, if you're looking for A
or B
, but not both, you'll need to do something similar to:
if( (A && !B) || (B && !A) ) { ... }
var top = ($('#bottom').position().top) + ($('#bottom').height());
The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
Coming from the embedded world, I would like to add that the concept of processes only exists in "big" processors (desktop CPUs, ARM Cortex A-9) that have MMU (memory management unit) , and operating systems that support using MMUs (such as Linux). With small/old processors and microcontrollers and small RTOS operating system (real time operating system), such as freeRTOS, there is no MMU support and thus no processes but only threads.
Threads can access each others memory, and they are scheduled by OS in an interleaved manner so they appear to run in parallel (or with multi-core they really run in parallel).
Processes, on the other hand, live in their private sandbox of virtual memory, provided and guarded by MMU. This is handy because it enables:
This is by far the best solution I have been able to find on the internet.
I've used the following link https://gist.github.com/mhasby/026f02b33fcc4207b302a60645f6e217,
but it had a single error which I fixed and then it works like a charm.
Here's my code. You can easily use it as it is an independent java class.
public class CopyAssets {
public static void copyAssets(Context context) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/www/resources/" + filename);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
}
}
if (out != null) {
try {
out.flush();
out.close();
out = null;
} catch (IOException e) {
}
}
}
}
}
public static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}}
As you can see, just create an instance of CopyAssets
in your java class which has an activity. Now this part is important, as far as my testing and researching on the internet, You cannot use AssetManager if the class has no activity
. It has something to do with the context of the java class.
Now, the c.copyAssets(getApplicationContext())
is an easy way to access the method, where c
is and instance of CopyAssets
class.
As per my requirement, I allowed the program to copy all my resource files inside the asset
folder to the /www/resources/
of my internal directory.
You can easily find out the part where you need to make changes to the directory as per your use.
Feel free to ping me if you need any help.
How about using GetValueOrDefault, which is pretty self-explaining and allows to use whatever default you want:
if (nullableBool.GetValueOrDefault(false)) {
}
The way to use expr:
i=0
i=`expr $i + 1`
the way to use i++
((i++)); echo $i;
Tested in gnu bash
I think what you're trying to do can be done through templates. I'm trying to read between the lines here. What you're trying to do is to call a method from some code, where it calls a derived version but the caller doesn't specify which class. Example:
class Foo {
public:
void M() {...}
};
class Bar : public Foo {
public:
void M() {...}
};
void Try()
{
xxx::M();
}
int main()
{
Try();
}
You want Try() to call the Bar version of M without specifying Bar. The way you do that for statics is to use a template. So change it like so:
class Foo {
public:
void M() {...}
};
class Bar : public Foo {
public:
void M() {...}
};
template <class T>
void Try()
{
T::M();
}
int main()
{
Try<Bar>();
}
.span7.btn { display: block; margin-left: auto; margin-right: auto; }
I am not completely familiar with bootstrap, but something like the above should do the trick. It may not be necessary to include all of the classes. This should center the button within its parent, the span7.
on my windows machine 8 machine running IIS 8 I can run the batch file just by putting the bats name and forgettig the path to it. Or by putting the bat in c:\windows\system32 don't ask me how it works but it does. LOL
$test=shell_exec("C:\windows\system32\cmd.exe /c $streamnumX.bat");
Can't you use simply display: none;
like this
HTML
<div id="web-title">
<a href="http://website.com" title="Website" rel="home">
<span class="webname">Website Name</span>
</a>
</div>
CSS
.webname {
display: none;
}
Or how about playing with visibility if you are concerned to reserve the space
.webname {
visibility: hidden;
}
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval()
here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON .
Also I tried other solution, but some of the code executed after redirect.
public static void ResponseRedirect(HttpResponse iResponse, string iUrl)
{
ResponseRedirect(iResponse, iUrl, HttpContext.Current);
}
public static void ResponseRedirect(HttpResponse iResponse, string iUrl, HttpContext iContext)
{
iResponse.Redirect(iUrl, false);
iContext.ApplicationInstance.CompleteRequest();
iResponse.BufferOutput = true;
iResponse.Flush();
iResponse.Close();
}
So if need to prevent code execution after redirect
try
{
//other code
Response.Redirect("")
// code not to be executed
}
catch(ThreadAbortException){}//do there id nothing here
catch(Exception ex)
{
//Logging
}
First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert
if(tv.tv_usec<10)
{
printf("00000");
}
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
printf("0000");
}
and so on...
The simplest solution to call your function with delay is:
function executeWithDelay(anotherFunction) {
setTimeout(anotherFunction, delayInMilliseconds);
}
Least effort solution for me was to make use of the gradle-shadow-plugin
Besides applying the plugin all that needs to be done is:
Configure the jar task to put your Main class into manifest
jar {
manifest {
attributes 'Main-Class': 'com.my.app.Main'
}
}
Run the gradle task
./gradlew shadowJar
Take the app-version-all.jar from build/libs/
And finally execute it via:
java -jar app-version-all.jar
Linux dotnet core doesn't support namedpipes!
Try TcpListener if you deploy to Linux
This NamedPipe Client/Server code round trips a byte to a server.
DotNet Core 2.0 Server ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
var server = new NamedPipeServerStream("A", PipeDirection.InOut);
server.WaitForConnection();
for (int i =0; i < 10000; i++)
{
var b = new byte[1];
server.Read(b, 0, 1);
Console.WriteLine("Read Byte:" + b[0]);
server.Write(b, 0, 1);
}
}
}
}
DotNet Core 2.0 Client ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Client
{
class Program
{
public static int threadcounter = 1;
public static NamedPipeClientStream client;
static void Main(string[] args)
{
client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
client.Connect();
var t1 = new System.Threading.Thread(StartSend);
var t2 = new System.Threading.Thread(StartSend);
t1.Start();
t2.Start();
}
public static void StartSend()
{
int thisThread = threadcounter;
threadcounter++;
StartReadingAsync(client);
for (int i = 0; i < 10000; i++)
{
var buf = new byte[1];
buf[0] = (byte)i;
client.WriteAsync(buf, 0, 1);
Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
}
}
public static async Task StartReadingAsync(NamedPipeClientStream pipe)
{
var bufferLength = 1;
byte[] pBuffer = new byte[bufferLength];
await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
{
Console.WriteLine($@"read data {pBuffer[0]}");
await StartReadingAsync(pipe); // read the next data <--
});
}
}
}
The String#replaceAll()
interprets the argument as a regular expression. The \
is an escape character in both String
and regex
. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace()
should suffice:
string.replace("\\", "\\\\");
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript()
instead to cover more characters.
A new operator is currently being added to the browsers, ??=
. This combines the null coalescing operator ??
with the assignment operator =
.
NOTE: This is not common in public browser versions yet. Will update as availability changes.
??=
checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
Browser Support Sept 2020 - 3.7%
Use your code
public class FragmentOne extends Fragment implements OnClickListener{
View view;
Fragment fragmentTwo;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
buttonSayHi.setOnClickListener(this);
return view;
}
But I think is better handle the buttons in this way:
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonSayHi:
/** Do things you need to..
fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
*/
break;
}
}
int ot = getResources().getConfiguration().orientation;
switch(ot)
{
case Configuration.ORIENTATION_LANDSCAPE:
Log.d("my orient" ,"ORIENTATION_LANDSCAPE");
break;
case Configuration.ORIENTATION_PORTRAIT:
Log.d("my orient" ,"ORIENTATION_PORTRAIT");
break;
case Configuration.ORIENTATION_SQUARE:
Log.d("my orient" ,"ORIENTATION_SQUARE");
break;
case Configuration.ORIENTATION_UNDEFINED:
Log.d("my orient" ,"ORIENTATION_UNDEFINED");
break;
default:
Log.d("my orient", "default val");
break;
}
bringToFront()
is the right way, but, NOTE that you must call bringToFront()
and invalidate()
method on highest-level view (under your root view), for e.g.:
Your view's hierarchy is:
-RelativeLayout
|--LinearLayout1
|------Button1
|------Button2
|------Button3
|--ImageView
|--LinearLayout2
|------Button4
|------Button5
|------Button6
So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView
. To bring it over (above) the ImageView
you must call bringToFront()
and invalidate()
method on your LinearLayout
s. Then it will work :)
**NOTE: Remember to set android:clipChildren="false"
for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:
.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hw="http://schemas.android.com/apk/res-auto"
android:id="@+id/layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/common_theme_color"
android:orientation="vertical" >
<com.binh.helloworld.customviews.HWActionBar
android:id="@+id/action_bar"
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_actionbar_height"
android:layout_alignParentTop="true"
hw:titleText="@string/app_name" >
</com.binh.helloworld.customviews.HWActionBar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/action_bar"
android:clipChildren="false" >
<LinearLayout
android:id="@+id/layout_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center_horizontal"
android:orientation="horizontal" >
</LinearLayout>
<ImageView
android:id="@+id/imgv_main"
android:layout_width="@dimen/common_imgv_height"
android:layout_height="@dimen/common_imgv_height"
android:layout_centerInParent="true"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:id="@+id/layout_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
Some code in .java
private LinearLayout layoutTop, layoutBottom;
...
layoutTop = (LinearLayout) rootView.findViewById(R.id.layout_top);
layoutBottom = (LinearLayout) rootView.findViewById(R.id.layout_bottom);
...
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example)
dragedView.setVisibility(View.GONE);
layoutTop.bringToFront();
layoutTop.invalidate();
dragedView.startAnimation(animation); // TranslateAnimation
dragedView.setVisibility(View.VISIBLE);
GLuck!
Below code is nice.. It was given by somebody else named aaronbd in this forum
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database')
or die ('Cannot connect to db');
$result = $conn->query("select id, name from table");
echo "<html>";
echo "<body>";
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
echo "</body>";
echo "</html>";
?>
I had a similar problem, but I wanted to append text to the beginning of the file name of all files in a directory and used a similar method. See example below:
folder = r"R:\mystuff\GIS_Projects\Website\2017\PDF"
import os
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
fullpath = os.path.join(root, filename)
filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])
print fullpath
print filename_split[0]
print filename_split[1]
os.rename(os.path.join(root, filename), os.path.join(root, "NewText_2017_" + filename_split[0] + filename_split[1]))
<br>
and <br/>
render differently. Some browsers interpret <br/>
as <br></br>
and insert two line breaks
I was using spring boot, and for me upgrading the version from 1.4.0.RELEASE
to 1.5.6.RELEASE
solved this issue.
Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.
...
:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice
:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user@host:/home/user/Backup/blabla/"
echo done
:doonotsyncthefiles
echo Backup Complete!
...
You can have as many as you need of these blocks.
I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).
JSON.parse(JSON.stringify(json_original));
Documentation
Here is another modification of the most popular answer, but with handling of variable length of text in the first column labels: http://jsfiddle.net/ozx56n41/
Basically, I'm using the second column for creating row height, like was mentioned. But my fiddle actually works unlike most mentioned above.
HTML:
<div id="outerdiv">
<div id="innerdiv">
<table>
<tr>
<td class="headcol"><div>This is a long label</div></td>
<td class="hiddenheadcol"><div>This is a long label</div></td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
</tr>
<tr>
<td class="headcol"><div>Short label</div></td>
<td class="hiddenheadcol"><div>Short label</div></td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
<td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
</tr>
</table>
</div>
</div>
CSS:
body {
font: 16px Calibri;
}
#outerdiv {
position: absolute;
top: 0;
left: 0;
right: 0;
width: 100%;
border-top: 1px solid grey;
}
#innerdiv {
overflow-x: scroll;
margin-left: 100px;
overflow-y: visible;
padding-bottom: 1px;
}
table {
border-collapse:separate;
}
td {
margin: 0;
border: 1px solid grey;
border-top-width: 0;
border-left-width: 0px;
padding: 10px;
}
td.headcol {
/* Frozen 1st column */
position: absolute;
left: 0;
top: auto;
border-bottom-width: 1px;
padding: 0;
border-left-width: 1px;
}
td.hiddenheadcol {
/* Hidden 2nd column to create height */
max-width: 0;
visibility: hidden;
padding: 0;
}
td.headcol div {
/* Text container in the 1st column */
width: 100px;
max-width: 100px;
background: lightblue;
padding: 10px;
box-sizing: border-box;
}
td.hiddenheadcol div {
/* Text container in the 2nd column */
width: 100px;
max-width: 100px;
background: red;
padding: 10px;
}
td.long {
background:yellow;
letter-spacing:1em;
}
If one wants to support Generics (in an extension method) this is the pattern...
public static List<T> Deserialize<T>(this string SerializedJSONString)
{
var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
return stuff;
}
It is used like this:
var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();
MyClassType looks like this (must match name value pairs of JSON array)
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class MyClassType
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "Manager")]
public string Manager { get; set; }
[JsonProperty(PropertyName = "LastUpdate")]
public DateTime LastUpdate { get; set; }
}
Use NUGET to download Newtonsoft.Json add a reference where needed...
using Newtonsoft.Json;
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
>>> x = {'a':1,'b':2,'c':3}
>>> x
{'a': 1, 'b': 2, 'c': 3}
>>> y = {'a':2,'b':4,'c':3}
>>> y
{'a': 2, 'b': 4, 'c': 3}
METHOD 1:
>>> common_item = x.items()&y.items() #using union,x.item()
>>> common_item
{('c', 3)}
METHOD 2:
>>> for i in x.items():
if i in y.items():
print('true')
else:
print('false')
false
false
true
If none of the other answers work for you then try the following which was the only thing that worked for me:
Find your .csproj
file and edit it in a text editor.
Find the <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
tag in your .csproj
file and delete the whole block.
Re-install all packages in the solution:
Update-Package -reinstall
After this your nuget packages should be restored, i think this might be a fringe case that only occurs when you move your project to a different location.
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
Not simpler, but without resizing overhead:
List<String> newList = new ArrayList<>(listOne.size() + listTwo.size());
newList.addAll(listOne);
newList.addAll(listTwo);
From matplotlib 3.1 onwards you may use ax.secondary_xaxis
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000
# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1
fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')
ax2 = ax.secondary_xaxis("top", functions=(f,g))
ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()
It's a part of ISO-8601 date representation. It's incomplete because a complete date representation in this pattern should also contains the date:
2015-03-04T00:00:00.000Z //Complete ISO-8601 date
If you try to parse this date as it is you will receive an Invalid Date
error:
new Date('T00:00:00.000Z'); // Invalid Date
So, I guess the way to parse a timestamp in this format is to concat with any date
new Date('2015-03-04T00:00:00.000Z'); // Valid Date
Then you can extract only the part you want (timestamp part)
var d = new Date('2015-03-04T00:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());
I have just written the following:
public static String toDelimitedString(int[] ids, String delimiter)
{
StringBuffer strb = new StringBuffer();
for (int id : ids)
{
strb.append(String.valueOf(id) + delimiter);
}
return strb.substring(0, strb.length() - delimiter.length());
}
Try ISDATE()
function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
EDIT :
As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT
SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail
or
SELECT LEFT(LoginTime,10) FROM AuditTrail
EDIT 2 :
The major reason for the error will be in your date in WHERE clause.ie,
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('06/18/2012' AS DATE)
will be different from
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('18/06/2012' AS DATE)
CONCLUSION
In EDIT 2 the first query tries to filter in mm/dd/yyyy
format, while the second query tries to filter in dd/mm/yyyy
format. Either of them will fail and throws error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
So please make sure to filter date either with mm/dd/yyyy
or with dd/mm/yyyy
format, whichever works in your db.
No! You should avoid using HTML entities.
Instead of using HTML entities for symbols you should just put those symbols directly into your text and correctly encode your document.
£
you should use the character £
.??
which is currently the most commonly used single character for rupee. Other alternatives are using INR
, Rs.
or rupees
.When the new Unicode symbol for the Indian Rupee is introduced then could use that instead (but note that it will be a while before all browsers support it).
I faced this issue as well but in my case, I was in wrong directory. Check the directory you are working
This is an improvement on Kennebec's answer.
function get_browser() {_x000D_
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; _x000D_
if(/trident/i.test(M[1])){_x000D_
tem=/\brv[ :]+(\d+)/g.exec(ua) || []; _x000D_
return {name:'IE',version:(tem[1]||'')};_x000D_
} _x000D_
if(M[1]==='Chrome'){_x000D_
tem=ua.match(/\bOPR|Edge\/(\d+)/)_x000D_
if(tem!=null) {return {name:'Opera', version:tem[1]};}_x000D_
} _x000D_
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];_x000D_
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}_x000D_
return {_x000D_
name: M[0],_x000D_
version: M[1]_x000D_
};_x000D_
}_x000D_
_x000D_
var browser=get_browser(); // browser.name = 'Chrome'_x000D_
// browser.version = '40'_x000D_
_x000D_
console.log(browser);
_x000D_
This way you can shield yourself from the obscurity of the code.
What about using the following:
int number = input.nextInt();
if (number < 0) {
// negative
} else {
// it's a positive
}
here's it, it WORKS 100%
char* appending(char *cArr, const char c)
{
int len = strlen(cArr);
cArr[len + 1] = cArr[len];
cArr[len] = c;
return cArr;
}
I was searching for this very same thing. I had read that this was available in Bootstrap 3.0, but I was having no luck in actually implementing it. This is what I came up with and it works great. Very simple jQuery and Javascript.
Here is the JSFiddle to play around with... http://jsfiddle.net/CriddleCraddle/Wj9dD/
The solution is very similar to other solutions on the web and StackOverflow. If you do not find this one useful, search for what you need. Goodluck!
Here is the HTML...
<div id="banner">
<h2>put what you want here</h2>
<p>just adjust javascript size to match this window</p>
</div>
<nav id='nav_bar'>
<ul class='nav_links'>
<li><a href="url">Sign In</a></li>
<li><a href="url">Blog</a></li>
<li><a href="url">About</a></li>
</ul>
</nav>
<div id='body_div'>
<p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>
</div>
Here is the CSS...
html, body {
height: 4000px;
}
.navbar-fixed {
top: 0;
z-index: 100;
position: fixed;
width: 100%;
}
#body_div {
top: 0;
position: relative;
height: 200px;
background-color: green;
}
#banner {
width: 100%;
height: 273px;
background-color: gray;
overflow: hidden;
}
#nav_bar {
border: 0;
background-color: #202020;
border-radius: 0px;
margin-bottom: 0;
height: 30px;
}
//the below css are for the links, not needed for sticky nav
.nav_links {
margin: 0;
}
.nav_links li {
display: inline-block;
margin-top: 4px;
}
.nav_links li a {
padding: 0 15.5px;
color: #3498db;
text-decoration: none;
}
Now, just add the javacript to add and remove the fix class based on the scroll position.
$(document).ready(function() {
//change the integers below to match the height of your upper div, which I called
//banner. Just add a 1 to the last number. console.log($(window).scrollTop())
//to figure out what the scroll position is when exactly you want to fix the nav
//bar or div or whatever. I stuck in the console.log for you. Just remove when
//you know the position.
$(window).scroll(function () {
console.log($(window).scrollTop());
if ($(window).scrollTop() > 550) {
$('#nav_bar').addClass('navbar-fixed-top');
}
if ($(window).scrollTop() < 551) {
$('#nav_bar').removeClass('navbar-fixed-top');
}
});
});
The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.
The best way to go about it would be to get a SynchronizationContext
from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher
directly). For example:
class MyViewModel
{
private readonly SynchronizationContext _syncContext;
public MyViewModel()
{
// we assume this ctor is called from the UI thread!
_syncContext = SynchronizationContext.Current;
}
// ...
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
_syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
}
}
For one dimension json you can use this:
function exist (json, modulid) {
var ret = 0;
$(json).each(function(index, data){
if(data.modulId == modulid)
ret++;
})
return ret > 0;
}
Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
In addtion to align-self
you can also consider auto margin which will do almost the same thing
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
padding: 10px;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
padding: 10px 40px;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
To use pip, it is not mandatory that you need to install pip in the system directly. You can use it through virtualenv
. What you can do is follow these steps:
We normally need to install Python packages for one particular project. So, now create a project folder, let’s say myproject.
virtualenv
, and paste inside the myproject folderNow create a virtual environment, let’s say myvirtualenv as follows, inside the myproject folder:
python virtualenv.py myvirtualenv
It will show you:
New python executable in myvirtualenv\Scripts\python.exe
Installing setuptools....................................done.
Installing pip.........................done.
Now your virtual environment, myvirtualenv, is created inside your project folder. You might notice, pip is now installed inside you virtual environment. All you need to do is activate the virtual environment with the following command.
myvirtualenv\Scripts\activate
You will see the following at the command prompt:
(myvirtualenv) PATH\TO\YOUR\PROJECT\FOLDER>pip install package_name
Now you can start using pip, but make sure you have activated the virtualenv looking at the left of your prompt.
This is one of the easiest way to install pip i.e. inside virtual environment, but you need to have virtualenv.py file with you.
For more ways to install pip/virtualenv/virtualenvwrapper, you can refer to thegauraw.tumblr.com.
You must allow for more than a digit (the +
sign) as in:
String regex = "[0-9]+";
String data = "23343453";
System.out.println(data.matches(regex));
simply don't close in
remove in.close()
from your code.
I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.
"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206
"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206
"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156
Use global namespace or global object like Constants.
var Constants = {};
And using defineObject write function which will add all properties to that object and assign value to it.
function createConstant (prop, value) {
Object.defineProperty(Constants , prop, {
value: value,
writable: false
});
};
No, you cannot currently get location without using GPS or internet.
Location techniques based on WiFi, Cellular, or Bluetooth work with the help of a large database that is constantly being updated. A device scans for transmitter IDs and then sends these in a query through the internet to a service such as Google, Apple, or Skyhook. That service responds with a location based on previous wireless surveys from known locations. Without internet access, you have to have a local copy of such a database and keep this up to date. For global usage, this is very impractical.
Theoretically, a mobile provider could provide local data service only but no access to the internet, and then answer location queries from mobile devices. Mobile providers don't do this; no one wants to pay for this kind of restricted data access. If you have data service through your mobile provider, then you have internet access.
In short, using LocationManager.NETWORK_PROVIDER or android.hardware.location.network to get location requires use of the internet.
Using the last known position requires you to have had GPS or internet access very recently. If you just had internet, presumably you can adjust your position or settings to get internet again. If your device has not had GPS or internet access, the last known position feature will not help you.
Without GPS or internet, you could:
Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:
>>> from test import disp
>>> disp('World!')
Or with a namespace:
>>> import test
>>> test.disp('World!')
As @Bradford20000 pointed out in the comments, there might be a gradle.properties
file as well as global gradle scripts located under $HOME/.gradle
. In such case special attention must be paid when deleting the content of this directory.
The .gradle/caches
directory holds the Gradle
build cache. So if you have any error about build cache, you can delete it.
The --no-build-cache option will run gradle without the build cache.
.append()
puts data inside an element at last index
and
.prepend()
puts the prepending elem at first index
<div class='a'> //<---you want div c to append in this
<div class='b'>b</div>
</div>
.append()
executes it will look like this:$('.a').append($('.c'));
after execution:
<div class='a'> //<---you want div c to append in this
<div class='b'>b</div>
<div class='c'>c</div>
</div>
.prepend()
executes it will look like this:$('.a').prepend($('.c'));
after execution:
<div class='a'> //<---you want div c to append in this
<div class='c'>c</div>
<div class='b'>b</div>
</div>
.after()
puts the element after the element
.before()
puts the element before the element
$('.a').after($('.c'));
after execution:
<div class='a'>
<div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed here
$('.a').before($('.c'));
after execution:
<div class='c'>c</div> //<----this will be placed here
<div class='a'>
<div class='b'>b</div>
</div>
This worked fine for me (C#):
byte[] iconBytes = null;
using (var dbConnection = new SQLiteConnection(DataSource))
{
dbConnection.Open();
using (var transaction = dbConnection.BeginTransaction())
{
using (var command = new SQLiteCommand(dbConnection))
{
command.CommandText = "SELECT icon FROM my_table";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"]))
{
iconBytes = (byte[]) reader["icon"];
}
}
}
}
transaction.Commit();
}
}
No need for chunking. Just cast to a byte array.
Whenever got error -1005 then need to call API Again.
AFHTTPRequestOperationManager *manager =
[AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:<example-url>
parameters:<parameteres>
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@“Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
if (error.code == -1005) {
// Call method again...
}
}];
You need to Add your code to call function again. MakeSure that you were call method once otherwise its call recursive loop.
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
If, while using the mysql_upgrade -u root -p --force
command You get this error:
Could not create the upgrade info file '/var/lib/mysql/mysql_upgrade_info' in the MySQL Servers datadir, errno: 13
just add the sudo
before the command. That worked for me, and I solved my problem. So, it's: sudo mysql_upgrade -u root -p --force
:)
Right click on the page and choose 'inspect element'. In the screen that opens now (the developer tools), clicking the second icon from the left @ the bottom of it opens a console, where you can type javascript. The console is linked to the current page.
Actually, 37 would work pretty well! z := 37 * x can be computed as y := x + 8 * x; z := x + 4 * y
. Both steps correspond to one LEA x86 instructions, so this is extremely fast.
In fact, multiplication with the even-larger prime 73 could be done at the same speed by setting y := x + 8 * x; z := x + 8 * y
.
Using 73 or 37 (instead of 31) might be better, because it leads to denser code: The two LEA instructions only take 6 bytes vs. the 7 bytes for move+shift+subtract for the multiplication by 31. One possible caveat is that the 3-argument LEA instructions used here became slower on Intel's Sandy bridge architecture, with an increased latency of 3 cycles.
Moreover, 73 is Sheldon Cooper's favorite number.
*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.
data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}
def my_function(**data):
schoolname = data['school']
cityname = data['city']
standard = data['class']
studentname = data['name']
You can call the function like this:
my_function(**data)
Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:
<script type="text/javascript">
function kk(){
var lol = document.getElementById('lolz').value;
alert(lol);
}
</script>
If you insist var lol
to be set outside the function kk, then I propose this solution:
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" OnClick="kk()"/>
<script type="text/javascript">
var lol = document.getElementById('lolz');
function kk() {
alert(lol.value);
}
</script>
</body>
Note that the script
element must follow the input
element it refers to, because elements are only queryable with getElementById
if they already have been parsed and created.
Both examples work, tested in jsfiddler.
Edit: I removed the language="javascript"
attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:
Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
and
A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]
Instead of typing command just press:
CLTRL + L
to clear chrome console
<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">
for example :
<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
...
</div>
And make sure it's readable by your colleagues :)
Private Sub CommandButton1_Click()
Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption
Me.Hide
Run "filename"
End Sub
Private Sub MUN_Change()
Dim r As Integer
r = 2
While Range("m" & CStr(r)).Value <> ""
If Range("m" & CStr(r)).Value = MUN.Text Then
Label5.Caption = Range("n" & CStr(r)).Value
End If
r = r + 1
Wend
End Sub
Private Sub PROV_Change()
If PROV.Text = "LAGUNA" Then
MUN.Text = ""
MUN.RowSource = "Menu!M26:M56"
ElseIf PROV.Text = "CAVITE" Then
MUN.Text = ""
MUN.RowSource = "Menu!M2:M25"
ElseIf PROV.Text = "QUEZON" Then
MUN.Text = ""
MUN.RowSource = "Menu!M57:M97"
End If
End Sub
OpenId uses OAuth to deal with authentication.
By analogy, it's like .NET relies on Windows API. You could directly call Windows API but it's so wide, complex and method arguments so vast, you could easily make mistakes/bugs/security issue.
Same with OpenId/OAuth. OpenId relies on OAuth to manage Authentication but defining a specific Token (Id_token), digital signature and particular flows.
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
TLDR: This got my Python meetup group past this problem when I was running a clinic on installing docker and most of the users were on OS X:
boot2docker init
boot2docker up
run the export
commands the output gives you, then
docker info
should tell you it works.
The Context (what brought us to the problem)
I led a clinic on installing docker and most attendees had OS X, and we ran into this problem and I overcame it on several machines. Here's the steps we followed:
First, we installed homebrew (yes, some attendees didn't have it):
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then we got cask, which we used to install virtualbox, and then used brew to install docker and boot2docker (all required for OS X) Don't use sudo for brew.:
brew install caskroom/cask/brew-cask
brew cask install virtualbox
brew install docker
brew install boot2docker
The Solution
That was when we ran into the problem the asker here got. The following fixed it. I understand init
was a one-time deal, but you'll probably have to run up
every time you start docker:
boot2docker init
boot2docker up
Then when up
has been run, it gives several export
commands. Copy-paste and run those.
Finally docker info
should tell you it's properly installed.
To Demo
The rest of the commands should demo it. (on Ubuntu linux I required sudo.)
docker run hello-world
docker run -it ubuntu bash
Then you should be on a root shell in the container:
apt-get install nano
exit
Back to your native user bash:
docker ps -l
Look for the about 12 digit hexadecimal (0-9 or a-f) identifier under "Container ID", e.g. 456789abcdef
. You can then commit your change and name it some descriptive name, like descriptivename
:
docker commit 456789abcdef descriptivename`
List<object> list = myArray.Cast<Object>().ToList();
If the type of the array elements is a reference type, you can leave out the .Cast<object>()
since C#4 added interface co-variance i.e. an IEnumerable<SomeClass>
can be treated as an IEnumerable<object>
.
List<object> list = myArray.ToList<object>();
Show whitespace characters in Visual Studio Code
change the setting.json, by adding the following codes!
// Place your settings in this file to overwrite default and user settings.
{
"editor.renderWhitespace": "all"
}
just like this!
(PS: there is no "true" option!, even it also works.)
Merge replication. You can create the subscriber (2008) from the distributor (2008). After the database has fully synchronized, drop the subscription and the publication.