All work perfectly :)
NSString *test = @"test";
unichar a;
int index = 5;
@try {
a = [test characterAtIndex:index];
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
NSLog(@"Char at index %d cannot be found", index);
NSLog(@"Max index is: %lu", [test length] - 1);
}
@finally {
NSLog(@"Finally condition");
}
Log:
[__NSCFConstantString characterAtIndex:]: Range or index out of bounds
Char at index 5 cannot be found
Max index is: 3
Finally condition
A simple solution:
<a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>
Or
<script>
/** Change the style **/
function overStyle(object){
object.style.color = 'orange';
// Change some other properties ...
}
/** Restores the style **/
function outStyle(object){
object.style.color = 'orange';
// Restore the rest ...
}
</script>
<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>
Assuming that you are using UTF-8 encoding:
string convert = "This is the string to be converted";
// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);
// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
If you are using a Canvas
or Grid
in your layout, give the control to be put on top a higher ZIndex
.
From MSDN:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="ZIndex Sample">
<Canvas>
<Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue"/>
<Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow"/>
<Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green"/>
<!-- Reverse the order to illustrate z-index property -->
<Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green"/>
<Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow"/>
<Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue"/>
</Canvas>
</Page>
If you don't specify ZIndex
, the children of a panel are rendered in the order they are specified (i.e. last one on top).
If you are looking to do something more complicated, you can look at how ChildWindow
is implemented in Silverlight. It overlays a semitransparent background and popup over your entire RootVisual
.
All string functions as lower
, upper
, strip
are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable
, it will fail.
x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them
Another solution:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule implementation="org.jacoco.maven.RuleConfiguration">
<excludes>
<exclude>com.mypackage1</exclude
<exclude>com.mypackage2</exclude>
</excludes>
<element>PACKAGE</element>
<limits>
<limit implementation="org.jacoco.report.check.Limit">
<counter>COMPLEXITY</counter>
<value>COVEREDRATIO</value>
<minimum>0.85</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
Please note that, we are using "<element>PACKAGE</element>"
in the configuration which then helps us to exclude at package level.
The JPA 2.0 Specification states that:
- The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
- The entity class must a be top-level class. An enum or interface must not be designated as an entity.
- The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
- If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
- Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.
The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.
I use the ManagementObjectSearcher
of namespace System.Management
Example:
string r = "";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
{
ManagementObjectCollection information = searcher.Get();
if (information != null)
{
foreach (ManagementObject obj in information)
{
r = obj["Caption"].ToString() + " - " + obj["OSArchitecture"].ToString();
}
}
r = r.Replace("NT 5.1.2600", "XP");
r = r.Replace("NT 5.2.3790", "Server 2003");
MessageBox.Show(r);
}
Do not forget to add the reference to the Assembly
System.Management.dll
and put the using:using System.Management;
Result:
div's and CSS positioning allow a more flexible design, leading to easier modification and templating of your web pages.
That said, if you aren't interested in the flexibility then using a table rather than some divs that are morphed into a table by CSS is definitely a lot easier and quicker to knock up. I tend to use tables when knocking up a design just to get it looking right that bit quicker.
JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
If you have this in your CSS file:
.myApp
{
border-bottom-color:#FF0000;
}
and a div for instance of:
<div id="myDiv">test text</div>
you can use:
$("#myDiv").addClass('myApp');// to add the style
$("#myDiv").removeClass('myApp');// to remove the style
or you can just use
$("#myDiv").css( 'border-bottom-color','#FF0000');
I prefer the first example, keeping all the CSS related items in the CSS files.
Here the XAML Version
<Window.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="//your source .."/>
</ImageBrush.ImageSource>
</ImageBrush>
</Window.Background>
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
The Stripes Framework is an excellent framework. The only configuration involved is pasting a few lines in your web.xml.
It's a very straight forward request based Java web framework.
Here are couple ways of doing it:
>>> t = ((1, 'a'), (2, 'b'))
>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}
>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}
For pip >= 20.3 use:
pip install --use-deprecated=legacy-resolver pylibmc==
For updates see: https://github.com/pypa/pip/issues/9139
For pip >= 9.0 use:
$ pip install pylibmc==
Collecting pylibmc==
Could not find a version that satisfies the requirement pylibmc== (from
versions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6,
0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9,
1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==
– all the available versions will be printed without actually downloading or installing any additional packages.
For pip < 9.0 use:
pip install pylibmc==blork
where blork
can be any string that is not a valid version number.
Would've commented on @ianmunoz's post but I don't have enough reputation. You can combine dplyr
's mutate_each
and replace
to take care of the NA
to 0
replacement. Using the dataframe from @aL3xa's answer...
> m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
> d <- as.data.frame(m)
> d
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 8 1 9 6 9 NA 8 9 8
2 8 3 6 8 2 1 NA NA 6 3
3 6 6 3 NA 2 NA NA 5 7 7
4 10 6 1 1 7 9 1 10 3 10
5 10 6 7 10 10 3 2 5 4 6
6 2 4 1 5 7 NA NA 8 4 4
7 7 2 3 1 4 10 NA 8 7 7
8 9 5 8 10 5 3 5 8 3 2
9 9 1 8 7 6 5 NA NA 6 7
10 6 10 8 7 1 1 2 2 5 7
> d %>% mutate_each( funs_( interp( ~replace(., is.na(.),0) ) ) )
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 8 1 9 6 9 0 8 9 8
2 8 3 6 8 2 1 0 0 6 3
3 6 6 3 0 2 0 0 5 7 7
4 10 6 1 1 7 9 1 10 3 10
5 10 6 7 10 10 3 2 5 4 6
6 2 4 1 5 7 0 0 8 4 4
7 7 2 3 1 4 10 0 8 7 7
8 9 5 8 10 5 3 5 8 3 2
9 9 1 8 7 6 5 0 0 6 7
10 6 10 8 7 1 1 2 2 5 7
We're using standard evaluation (SE) here which is why we need the underscore on "funs_
." We also use lazyeval
's interp
/~
and the .
references "everything we are working with", i.e. the data frame. Now there are zeros!
Intellij 2021.3.2 Basic Shortcuts
Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:
var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
Ok, if you are using Windows OS
Go to C:\Program Files\Java\jdk1.8.0_40\lib (jdk Version might be different for you)
Make sure tools.jar is present (otherwise download it)
Copy this path "C:\Program Files\Java\jdk1.8.0_40"
In pom.xml
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.8.0_40</version>
<scope>system</scope>
<systemPath>C:/Program Files/Java/jdk1.8.0_40/lib/tools.jar</systemPath>
</dependency>
Rebuild and run! BINGO!
I have two get methods with same or no parameters
[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}
[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}
Just define custom routes in AppStart=>WebApiConfig.cs
=> under register method
config.Routes.MapHttpRoute(
name: "GetFirstList",
routeTemplate: "api/Controllername/FirstList"
);
config.Routes.MapHttpRoute(
name: "GetSecondList",
routeTemplate: "api/Controllername/SecondList"
);
To be precise, a ||= b
means "if a
is undefined or falsy (false
or nil
), set a
to b
and evaluate to (i.e. return) b
, otherwise evaluate to a
".
Others often try to illustrate this by saying that a ||= b
is equivalent to a || a = b
or a = a || b
. These equivalencies can be helpful for understanding the concept, but be aware that they are not accurate under all conditions. Allow me to explain:
a ||= b
? a || a = b
?
The behavior of these statements differs when a
is an undefined local variable. In that case, a ||= b
will set a
to b
(and evaluate to b
), whereas a || a = b
will raise NameError: undefined local variable or method 'a' for main:Object
.
a ||= b
? a = a || b
?
The equivalency of these statements are often assumed, since a similar equivalence is true for other abbreviated assignment operators (i.e. +=
,-=
,*=
,/=
,%=
,**=
,&=
,|=
,^=
,<<=
, and >>=
). However, for ||=
the behavior of these statements may differ when a=
is a method on an object and a
is truthy. In that case, a ||= b
will do nothing (other than evaluate to a
), whereas a = a || b
will call a=(a)
on a
's receiver. As others have pointed out, this can make a difference when calling a=a
has side effects, such as adding keys to a hash.
a ||= b
? a = b unless a
??
The behavior of these statements differs only in what they evaluate to when a
is truthy. In that case, a = b unless a
will evaluate to nil
(though a
will still not be set, as expected), whereas a ||= b
will evaluate to a
.
a ||= b
? defined?(a) ? (a || a = b) : (a = b)
????
Still no. These statements can differ when a method_missing
method exists which returns a truthy value for a
. In this case, a ||= b
will evaluate to whatever method_missing
returns, and not attempt to set a
, whereas defined?(a) ? (a || a = b) : (a = b)
will set a
to b
and evaluate to b
.
Okay, okay, so what is a ||= b
equivalent to? Is there a way to express this in Ruby?
Well, assuming that I'm not overlooking anything, I believe a ||= b
is functionally equivalent to... (drumroll)
begin
a = nil if false
a || a = b
end
Hold on! Isn't that just the first example with a noop before it? Well, not quite. Remember how I said before that a ||= b
is only not equivalent to a || a = b
when a
is an undefined local variable? Well, a = nil if false
ensures that a
is never undefined, even though that line is never executed. Local variables in Ruby are lexically scoped.
Change the less-than operator to a greater-than-or-equal-to operator:
}elseif($("#seats").val() >= 99999){
Ruby 2.7+
There is now!
Ruby 2.7 is introducing filter_map
for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.
For example:
numbers = [1, 2, 5, 8, 10, 13]
enum.filter_map { |i| i * 2 if i.even? }
# => [4, 16, 20]
In your case, as the block evaluates to falsey, simply:
items.filter_map { |x| process_x url }
"Ruby 2.7 adds Enumerable#filter_map" is a good read on the subject, with some performance benchmarks against some of the earlier approaches to this problem:
N = 100_000
enum = 1.upto(1_000)
Benchmark.bmbm do |x|
x.report("select + map") { N.times { enum.select { |i| i.even? }.map{ |i| i + 1 } } }
x.report("map + compact") { N.times { enum.map { |i| i + 1 if i.even? }.compact } }
x.report("filter_map") { N.times { enum.filter_map { |i| i + 1 if i.even? } } }
end
# Rehearsal -------------------------------------------------
# select + map 8.569651 0.051319 8.620970 ( 8.632449)
# map + compact 7.392666 0.133964 7.526630 ( 7.538013)
# filter_map 6.923772 0.022314 6.946086 ( 6.956135)
# --------------------------------------- total: 23.093686sec
#
# user system total real
# select + map 8.550637 0.033190 8.583827 ( 8.597627)
# map + compact 7.263667 0.131180 7.394847 ( 7.405570)
# filter_map 6.761388 0.018223 6.779611 ( 6.790559)
you can do:
<div style="float: left;"></div>
or
<div style="display: inline;"></div>
Either one will cause the divs to tile horizontally.
Since nobody posted the modern C++ approach yet,
#include <iostream>
#include <random>
int main()
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(25, 63); // define the range
for(int n=0; n<40; ++n)
std::cout << distr(gen) << ' '; // generate numbers
}
Oops. Original answer was specific to a similar question. This has been revised:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
with the value in IMG you can write it out as a new Image like so:
document.write('<img src="'+img+'"/>');
CSTR({number_field}, 0, '')
The second placeholder is for decimals.
The last placeholder is for thousands separator.
A simple and very usefull example, is....
Imagine:
you have a uint32_t array[2]
and want to access the 3rd and 4th Byte of the Byte chain.
you could do *((uint16_t*) &array[1])
.
But this sadly breaks the strict aliasing rules!
But known compilers allow you to do the following :
union un
{
uint16_t array16[4];
uint32_t array32[2];
}
technically this is still a violation of the rules. but all known standards support this usage.
This is what has to occur.
You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\
Then in the Run dialog, type this in:
C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll
and you will get the message:
DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.
files directory:
Project->
-functions.php
-main.php
functions.php
function sum(a,b){
return a+b;
}
function product(a,b){
return a*b;
}
main.php
require_once "functions.php";
echo "sum of two numbers ". sum(4,2);
echo "<br>"; // create break line
echo "product of two numbers ".product(2,3);
The Output Is :
sum of two numbers 6 product of two numbers 6
Note: don't write public before function. Public, private, these modifiers can only use when you create class.
If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.
#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1
It's ok to have comment and blank lines before them.
I'd like to share this little hack:
A click on the Eclipse's icon indicated a problem with the JRE. So, I put this command in the destination field of the icon's properties:
C:\...\eclipse.exe -vm c:\'Program Files'\Java\jdk1.7.0_51\jre\bin\javaw
Thinking that the "'" would solve the problem with the space in the path. That did not function. Then, I tried this command:
C:\...\eclipse.exe -vm c:\Progra~1\Java\jdk1.7.0_51\jre\bin\javaw
with success
WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));
you can use this as some time before loading whole page code gets executed and throws and error. time is in second
If you want to focus on each letter
you can do like that, I refer to this question
function truncate(source, size) {_x000D_
return source.length > size ? source.slice(0, size - 1) + "…" : source;_x000D_
}_x000D_
_x000D_
var text = truncate('Truncate text to fit in 3 lines', 14);_x000D_
console.log(text);
_x000D_
If you want to focus on each word
you can do like that + space
const truncate = (title, limit = 14) => { // 14 IS DEFAULT ARGUMENT _x000D_
const newTitle = [];_x000D_
if (title.length > limit) {_x000D_
title.split(' ').reduce((acc, cur) => {_x000D_
if (acc + cur.length <= limit) {_x000D_
newTitle.push(cur);_x000D_
}_x000D_
return acc + cur.length;_x000D_
}, 0);_x000D_
_x000D_
return newTitle.join(' ') + '...'_x000D_
}_x000D_
return title;_x000D_
}_x000D_
_x000D_
var text = truncate('Truncate text to fit in 3 lines', 14);_x000D_
console.log(text);
_x000D_
If you want to focus on each word
you can do like that + without space
const truncate = (title, limit = 14) => { // 14 IS DEFAULT ARGUMENT _x000D_
const newTitle = [];_x000D_
if (title.length > limit) {_x000D_
Array.prototype.slice.call(title).reduce((acc, cur) => {_x000D_
if (acc + cur.length <= limit) {_x000D_
newTitle.push(cur);_x000D_
}_x000D_
return acc + cur.length;_x000D_
}, 0);_x000D_
_x000D_
return newTitle.join('') + '...'_x000D_
}_x000D_
return title;_x000D_
}_x000D_
_x000D_
var text = truncate('Truncate text to fit in 3 lines', 14);_x000D_
console.log(text);
_x000D_
<div class="rmz-srchbg">
<input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
<input type="submit" value=" " id="srchbtn" class="rmz-srchico">
<br style="clear:both;">
</div>
$(document).ready(function() {
$('#globalsearchstr').bind('mouseenter', function() {
$(this).parent().css("background", "black");
});
});
I would use a div to center align an image. As in:
<div align="center"><img src="your_image_source"/></div>
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
$ mysql -u root -p -e "grant all privileges on dbTest.* to
`{user}`@`{host}` identified by '{long-password}'; flush privileges;"
ignore -p option, if mysql user has no password or just press "[Enter]" button to by-pass. strings surrounded with curly braces need to replaced with actual values.
Try this below code, Its very short and simple.
transalate_anim.xml
<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2013 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="4000"
android:fromXDelta="0"
android:fromYDelta="0"
android:repeatCount="infinite"
android:toXDelta="0"
android:toYDelta="-90%p" />
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="4000"
android:fromAlpha="0.0"
android:repeatCount="infinite"
android:toAlpha="1.0" />
</set>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.naveen.congratulations.MainActivity">
<ImageView
android:id="@+id/image_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:srcCompat="@drawable/balloons" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView1 = (ImageView) findViewById(R.id.image_1);
imageView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startBottomToTopAnimation(imageView1);
}
});
}
private void startBottomToTopAnimation(View view) {
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_anim));
}
}
We have a simple argument in Pandas read_csv for this:
Use:
df = pd.read_csv('test.csv', na_filter= False)
Pandas documentation clearly explains how the above argument works.
a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat
some formatting examples
/** delta: 1234567890, @locale: 'en-US', @style: 'long' */
/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds
/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890
/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms
/* D,h:m:s.f */
14,06:56:07.890
/* D~, h:m:s.f */
14 days, 06:56:07.890
/* h~ m~ s~ */
342 hours 56 minutes 7 seconds
/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days
/* up D~, h:m */
up 14 days, 06:56
the code & test
/**
Init locale formatter:
timespan.locale(@locale, @style)
Example:
timespan.locale('en-US', 'long');
timespan.locale('es', 'narrow');
Format time delta:
timespan.format(@pattern, @milliseconds)
@pattern tokens:
D: days, h: hours, m: minutes, s: seconds, f: millis
@pattern token extension:
h => '0'-padded value,
h# => raw value,
h~ => locale formatted value
Example:
timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
output: 14 days 6 hours 56 minutes 7 seconds 890 millis
NOTES:
* milliseconds unit have no locale translation
* may encounter declension issues for some locales
* use quoted text for raw inserts
*/
const timespan = (() => {
let rtf, tokensRtf;
const
tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
map = [
{t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
{t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
{t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
{t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
{t: [['f', 3], ['f#'], ['f~']], u: 1}
],
locale = (value, style = 'long') => {
try {
rtf = new Intl.RelativeTimeFormat(value, {style});
} catch (e) {
if (rtf) throw e;
return;
}
const h = rtf.format(1, 'hour').split(' ');
tokensRtf = new Set(rtf.format(1, 'day').split(' ')
.filter(t => t != 1 && h.indexOf(t) > -1));
return true;
},
fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
mapper = {
number: (t, u) => (u + '').padStart(t.fmt, '0'),
string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
.filter(t => !tokensRtf.has(t)).join(' ')
.trim().replace(/[+-]/g, '') : fallback(t, u),
},
replace = (out, t) => out[t] || t.slice(1, t.length - 1),
format = (pattern, value) => {
if (typeof pattern !== 'string')
throw Error('invalid pattern');
if (!Number.isFinite(value))
throw Error('invalid value');
if (!pattern)
return '';
const out = {};
value = Math.abs(value);
pattern.match(tokens)?.forEach(t => out[t] = null);
map.forEach(m => {
let u = null;
m.t.forEach(t => {
if (out[t.token] !== null)
return;
if (u === null) {
u = Math.floor(value / m.u);
value %= m.u;
}
out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
})
});
return pattern.replace(tokens, replace.bind(null, out));
};
map.forEach(m => m.t = m.t.map(t => ({
token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
})));
locale('en');
return {format, locale};
})();
/************************** test below *************************/
const
cfg = {
locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
try {
const tv = new Date(td.value);
if (isNaN(tv)) throw Error('invalid "datetime2" value');
timespan.locale(loc.value || locale.value, style.value);
const delta = fd.getTime() - tv.getTime();
out.innerHTML = timespan.format(fmt.value, delta);
} catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
const elm = el(id);
value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
Your error shows you are not compiling file with the definition of the insert
function. Update your command to include the file which contains the definition of that function and it should work.
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:
#### 1.1 My Subtitle \
1.1 My Subtitle
Next paragraph text.
An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).
### My Subtitle
1.1 My Subtitle
Next paragraph text.
There is another code that's works for me (jQuery).
$(".datepicker").datepicker({_x000D_
format: "dd/mm/yyyy",_x000D_
autoHide: true_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />_x000D_
Date: <input type="text" readonly="true" class="datepicker">
_x000D_
I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.
My solution was a little bit different and faster :)
Go to VSCode and in Terminal write:
config credential.helper wincred
Go to Visual Studio (no VSCode) and make a git pull. A popup will show asking for credentials. Put your credentials for the repo
Go to VSCode and make a git pull. Credentials were automatically fetched from wincred store
Credentials are automatically created and stored in wincredentials, so the next time you cannot be asked for credentials. (also a Personal Access Token will be provided from visualstudio.com if you are using DevOps hosted git repo).
Both syntaxes are correct. But the result would be Array
. You probably want to do something like this:
foreach ($tmpArray[1] as $value) {
echo $value[0];
foreach($value[1] as $val){
echo $val;
}
}
This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).
In my instance, the error was generated because one of my complex types had a property with no set method.
The serializer threw an exception because of that fact. Added internal set methods and it all worked fine.
Best way to find out why this is happening (in my opinion) is to enable trace logging.
I achieved this by adding the following section to my web.config
:
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
<add type="System.Diagnostics.DefaultTraceListener" name="Default" />
</listeners>
</source>
<source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
<add type="System.Diagnostics.DefaultTraceListener" name="Default" />
</listeners>
</source>
</sources>
<trace autoflush="true" />
</system.diagnostics>
Once set, I ran my client, got exception and checked the 'Traces.svclog' file. From there, I only needed to find the exception.
Here are both fixes.
First, regarding the fixed sidebar, you need to give it a height for it to overflow:
HTML Code:
<div id="sidebar">Menu</div>
<div id="content">Text</div>
CSS Code:
body {font:76%/150% Arial, Helvetica, sans-serif; color:#666; width:100%; height:100%;}
#sidebar {position:fixed; top:0; left:0; width:20%; height:100%; background:#EEE; overflow:auto;}
#content {width:80%; padding-left:20%;}
@media screen and (max-height:200px){
#sidebar {color:blue; font-size:50%;}
}
Live example: http://jsfiddle.net/RWxGX/3/
It's impossible NOT to get a scroll bar if your content overflows the height of the div. That's why I've added a media query for screen height. Maybe you can adjust your styles for short screen sizes so the scroll doesn't need to appear.
Cheers, Ignacio
'this' refers to the DOM object to which the event listener has been attached. 'event.target' refers to the DOM object for which the event listener got triggered. A natural question arises as, why the event listener is triggering for other DOM objects. This is because event listener attached parent triggers for child object too.
I'm implementing it in Play Framework and for me it worked like this:
1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1. The code section of userform in my Modal:
<div class="form-group">
<label for="pass1">@Messages("authentication.password")</label>
<input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
<label for="pass2">@Messages("authentication.password2")</label>
<input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>
2)Since I used validator within a Modal
$(document).on("click", ".createUserModal", function () {
$(this).find('#userform').validate({
rules: {
firstName: "required",
lastName: "required",
nationalId: {
required: true,
digits:true
},
email: {
required: true,
email: true
},
optradio: "required",
password :{
required: true,
minlength: 5
},
password2: {
required: true
}
},
highlight: function (element) {
$(element).parent().addClass('error')
},
unhighlight: function (element) {
$(element).parent().removeClass('error')
},
onsubmit: true
});
});
Hope it helps someone :).
In my opinion, the simpler and most elegant way to add a delay in a loop is like this:
names = ['John', 'Ana', 'Mary'];
names.forEach((name, i) => {
setTimeout(() => {
console.log(name);
}, i * 1000); // one sec interval
});
@{
string datein = Convert.ToDateTime(item.InDate).ToString("dd/MM/yyyy");
@datein
}
These posts apparently are in the wrong order! This is #1 in a series of 3 posts. Sorry.
In attempting to use Lie Ryan's code, I had problems retrieving stored information. The vector's elements are not stored contiguously,as you can see by "cheating" a bit and storing the pointer to each element's address (which of course defeats the purpose of the dynamic array concept) and examining them.
With a bit of tinkering, via:
ss_vector* vector; // pull this out to be a global vector
// Then add the following to attempt to recover stored values.
int return_id_value(int i,apple* aa) // given ptr to component,return data item
{ printf("showing apple[%i].id = %i and other_id=%i\n",i,aa->id,aa->other_id);
return(aa->id);
}
int Test(void) // Used to be "main" in the example
{ apple* aa[10]; // stored array element addresses
vector = ss_init_vector(sizeof(apple));
// inserting some items
for (int i = 0; i < 10; i++)
{ aa[i]=init_apple(i);
printf("apple id=%i and other_id=%i\n",aa[i]->id,aa[i]->other_id);
ss_vector_append(vector, aa[i]);
}
// report the number of components
printf("nmbr of components in vector = %i\n",(int)vector->size);
printf(".*.*array access.*.component[5] = %i\n",return_id_value(5,aa[5]));
printf("components of size %i\n",(int)sizeof(apple));
printf("\n....pointer initial access...component[0] = %i\n",return_id_value(0,(apple *)&vector[0]));
//.............etc..., followed by
for (int i = 0; i < 10; i++)
{ printf("apple[%i].id = %i at address %i, delta=%i\n",i, return_id_value(i,aa[i]) ,(int)aa[i],(int)(aa[i]-aa[i+1]));
}
// don't forget to free it
ss_vector_free(vector);
return 0;
}
It's possible to access each array element without problems, as long as you know its address, so I guess I'll try adding a "next" element and use this as a linked list. Surely there are better options, though. Please advise.
$sql = "select column_name from information_schema.columns where table_name = 'myTable'";
PHP function credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html
function getColumnNames(){
$sql = "select column_name from information_schema.columns where table_name = 'myTable'";
#$sql = 'SHOW COLUMNS FROM ' . $this->table;
$stmt = $this->connection->prepare($sql);
try {
if($stmt->execute()){
$raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($raw_column_data as $outer_key => $array){
foreach($array as $inner_key => $value){
if (!(int)$inner_key){
$this->column_names[] = $value;
}
}
}
}
return $this->column_names;
} catch (Exception $e){
return $e->getMessage(); //return exception
}
}
First, your HTML markup looks like this:
<video id="awesome_video" src="first_video.mp4" autoplay />
Second, your JavaScript code will look like this:
<script type="text/javascript">
var index = 1,
playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
video = document.getElementById('awesome_video');
video.addEventListener('ended', rotate_video, false);
function rotate_video() {
video.setAttribute('src', playlist[index]);
video.load();
index++;
if (index >= playlist.length) { index = 0; }
}
</script>
And last but not least, your CSS:
#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.
one way is to convert it to list
>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)
I also had this issue and it was resolved after modifying the *.xsd to reflect the revised size of the column changed in the underlying SQL server.
I was doing a search for this to see if the solution I wrote could be optimised for speed. What I wanted was a countdown timer, not just updating the current line. Here's what I came up with. Might be useful to someone
int sleepTime = 5 * 60; // 5 minutes
for (int secondsRemaining = sleepTime; secondsRemaining > 0; secondsRemaining --)
{
double minutesPrecise = secondsRemaining / 60;
double minutesRounded = Math.Round(minutesPrecise, 0);
int seconds = Convert.ToInt32((minutesRounded * 60) - secondsRemaining);
Console.Write($"\rProcess will resume in {minutesRounded}:{String.Format("{0:D2}", -seconds)} ");
Thread.Sleep(1000);
}
Console.WriteLine("");
Your code is fine. There's no problem with returning Strings
in this manner.
In Java, a String
is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String
around without worrying that it would disapper on you, or that someone somewhere would modify it.
If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:
public String time_to_string(long t) // time in milliseconds
{
if (t < 0)
{
return "-";
}
else
{
int secs = (int)(t/1000);
int mins = secs/60;
secs = secs - (mins * 60);
return String.format("%d:%02d", mins, secs);
}
}
As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans
and have replaced the mix of string concatenation and String.format()
with a single call to String.format()
.
Here is how to do it using TCP IP protocol :
// Printer IP Address and communication port
string ipAddress = "10.3.14.42";
int port = 9100;
// ZPL Command(s)
string ZPLString =
"^XA" +
"^FO50,50" +
"^A0N50,50" +
"^FDHello, World!^FS" +
"^XZ";
try
{
// Open connection
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
client.Connect(ipAddress, port);
// Write ZPL String to connection
System.IO.StreamWriter writer =
new System.IO.StreamWriter(client.GetStream());
writer.Write(ZPLString);
writer.Flush();
// Close Connection
writer.Close();
client.Close();
}
catch (Exception ex)
{
// Catch Exception
}
Source : ZEBRA WEBSITE
The magic happens when calling SaveChanges()
and depends on the current EntityState
. If the entity has an EntityState.Added
, it will be added to the database, if it has an EntityState.Modified
, it will be updated in the database. So you can implement an InsertOrUpdate()
method as follows:
public void InsertOrUpdate(Blog blog)
{
using (var context = new BloggingContext())
{
context.Entry(blog).State = blog.BlogId == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
}
}
If you can't check on Id = 0
to determine if it's a new entity or not, check the answer of Ladislav Mrnka.
You need to understand the content in M2E_plugin_execution_not_covered and follow the steps mentioned below:
<ignore/>
under <action>
tags.eg: for write-project-properties error, add this snippet under the <pluginExecutions>
section of the lifecycle-mapping-metadata.xml file:
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<versionRange>1.0-alpha-2</versionRange>
<goals>
<goal>write-project-properties</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
You should see no errors in the future for any project.
Here's a solution that works with fixed backgrounds, if you have a fixed background and you have some overlayed elements and you need blured backgrounds for them, this solution works:
Image we have this simple HTML:
<body> <!-- or any wrapper -->
<div class="content">Some Texts</div>
</body>
A fixed background for <body>
or the wrapper element:
body {
background-image: url(http://placeimg.com/640/360/any);
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
}
And here for example we have a overlayed element with a white transparent background:
.content {
background-color: rgba(255, 255, 255, 0.3);
position: relative;
}
Now we need to use the exact same background image of our wrapper for our overlay elements too, i use it as a :before
psuedo-class:
.content:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
filter: blur(5px);
background-image: url(http://placeimg.com/640/360/any);
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
}
Since the fixed background works in a same way in both wrapper and overlayed elements, we have the background in exactly same scroll position of the overlayed element and we can simply blur it. Here's a working fiddle, tested in Firefox, Chrome, Opera and Edge: https://jsfiddle.net/0vL2rc4d/
NOTE: In firefox there's a bug that makes screen flicker when scrolling and there are fixed blurred backgrounds. if there's any fix, let me know
Following solution is very basic and simple approach to send data from VC2 to VC1 using delegate .
PS: This solution is made in Xcode 9.X and Swift 4
Declared a protocol and created a delegate var into ViewControllerB
import UIKit
//Declare the Protocol into your SecondVC
protocol DataDelegate {
func sendData(data : String)
}
class ViewControllerB : UIViewController {
//Declare the delegate property in your SecondVC
var delegate : DataDelegate?
var data : String = "Send data to ViewControllerA."
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnSendDataPushed(_ sender: UIButton) {
// Call the delegate method from SecondVC
self.delegate?.sendData(data:self.data)
dismiss(animated: true, completion: nil)
}
}
ViewControllerA confirms the protocol and expected to receive data via delegate method sendData
import UIKit
// Conform the DataDelegate protocol in ViewControllerA
class ViewControllerA : UIViewController , DataDelegate {
@IBOutlet weak var dataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func presentToChild(_ sender: UIButton) {
let childVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"ViewControllerB") as! ViewControllerB
//Registered delegate
childVC.delegate = self
self.present(childVC, animated: true, completion: nil)
}
// Implement the delegate method in ViewControllerA
func sendData(data : String) {
if data != "" {
self.dataLabel.text = data
}
}
}
does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!
In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):
-Droot.log.level=TRACE
The real problem is that the default owner(dbo) doesn't have a login mapped to it at all.As I tried to map the sa login to the database owner I received another error stating "User,group, or role 'dbo' already exists...".However if you try this code it will actually works :
EXEC sp_dbcmptlevel 'yourDB', '90';
go
ALTER AUTHORIZATION ON DATABASE::yourDB TO "yourLogin"
go
use [yourDB]
go
EXECUTE AS USER = N'dbo' REVERT
go
--Try this script it works to my needs. Reformat to read it.
SELECT
SERVERPROPERTY('ComputerNamePhysicalNetBios') as 'Is_Current_Owner'
,SERVERPROPERTY('MachineName') as 'MachineName'
,case when @@ServiceName =
Right (@@Servername,len(@@ServiceName)) then @@Servername
else @@servername +' \ ' + @@Servicename
end as '@@Servername \ Servicename',
CONNECTIONPROPERTY('net_transport') AS net_transport,
CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
dec.local_tcp_port,
CONNECTIONPROPERTY('local_net_address') AS local_net_address,
dec.local_net_address as 'dec.local_net_address'
FROM sys.dm_exec_connections AS dec
WHERE dec.session_id = @@SPID;
One liner for callstack:
begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace; end
One liner for callstack without all the gems's:
begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//); end
One liner for callstack without all the gems's and relative to current directory
begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//).map { |l| l.gsub(`pwd`.strip + '/', '') }; end
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T
Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a random 32 or 64 bit integer between those two values. This should be a one liner in any language.
On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation). The same principle applies except you're dealing with single or double precision floating point numbers ("floats" or "doubles" in C, Java and other languages). Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.
you can generate curl error after its execution
$url = 'http://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);
}
and here are curl error code
if someone need more information about curl errors
<?php
$error_codes=array(
[1] => 'CURLE_UNSUPPORTED_PROTOCOL',
[2] => 'CURLE_FAILED_INIT',
[3] => 'CURLE_URL_MALFORMAT',
[4] => 'CURLE_URL_MALFORMAT_USER',
[5] => 'CURLE_COULDNT_RESOLVE_PROXY',
[6] => 'CURLE_COULDNT_RESOLVE_HOST',
[7] => 'CURLE_COULDNT_CONNECT',
[8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
[9] => 'CURLE_REMOTE_ACCESS_DENIED',
[11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
[13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
[14]=>'CURLE_FTP_WEIRD_227_FORMAT',
[15] => 'CURLE_FTP_CANT_GET_HOST',
[17] => 'CURLE_FTP_COULDNT_SET_TYPE',
[18] => 'CURLE_PARTIAL_FILE',
[19] => 'CURLE_FTP_COULDNT_RETR_FILE',
[21] => 'CURLE_QUOTE_ERROR',
[22] => 'CURLE_HTTP_RETURNED_ERROR',
[23] => 'CURLE_WRITE_ERROR',
[25] => 'CURLE_UPLOAD_FAILED',
[26] => 'CURLE_READ_ERROR',
[27] => 'CURLE_OUT_OF_MEMORY',
[28] => 'CURLE_OPERATION_TIMEDOUT',
[30] => 'CURLE_FTP_PORT_FAILED',
[31] => 'CURLE_FTP_COULDNT_USE_REST',
[33] => 'CURLE_RANGE_ERROR',
[34] => 'CURLE_HTTP_POST_ERROR',
[35] => 'CURLE_SSL_CONNECT_ERROR',
[36] => 'CURLE_BAD_DOWNLOAD_RESUME',
[37] => 'CURLE_FILE_COULDNT_READ_FILE',
[38] => 'CURLE_LDAP_CANNOT_BIND',
[39] => 'CURLE_LDAP_SEARCH_FAILED',
[41] => 'CURLE_FUNCTION_NOT_FOUND',
[42] => 'CURLE_ABORTED_BY_CALLBACK',
[43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
[45] => 'CURLE_INTERFACE_FAILED',
[47] => 'CURLE_TOO_MANY_REDIRECTS',
[48] => 'CURLE_UNKNOWN_TELNET_OPTION',
[49] => 'CURLE_TELNET_OPTION_SYNTAX',
[51] => 'CURLE_PEER_FAILED_VERIFICATION',
[52] => 'CURLE_GOT_NOTHING',
[53] => 'CURLE_SSL_ENGINE_NOTFOUND',
[54] => 'CURLE_SSL_ENGINE_SETFAILED',
[55] => 'CURLE_SEND_ERROR',
[56] => 'CURLE_RECV_ERROR',
[58] => 'CURLE_SSL_CERTPROBLEM',
[59] => 'CURLE_SSL_CIPHER',
[60] => 'CURLE_SSL_CACERT',
[61] => 'CURLE_BAD_CONTENT_ENCODING',
[62] => 'CURLE_LDAP_INVALID_URL',
[63] => 'CURLE_FILESIZE_EXCEEDED',
[64] => 'CURLE_USE_SSL_FAILED',
[65] => 'CURLE_SEND_FAIL_REWIND',
[66] => 'CURLE_SSL_ENGINE_INITFAILED',
[67] => 'CURLE_LOGIN_DENIED',
[68] => 'CURLE_TFTP_NOTFOUND',
[69] => 'CURLE_TFTP_PERM',
[70] => 'CURLE_REMOTE_DISK_FULL',
[71] => 'CURLE_TFTP_ILLEGAL',
[72] => 'CURLE_TFTP_UNKNOWNID',
[73] => 'CURLE_REMOTE_FILE_EXISTS',
[74] => 'CURLE_TFTP_NOSUCHUSER',
[75] => 'CURLE_CONV_FAILED',
[76] => 'CURLE_CONV_REQD',
[77] => 'CURLE_SSL_CACERT_BADFILE',
[78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
[79] => 'CURLE_SSH',
[80] => 'CURLE_SSL_SHUTDOWN_FAILED',
[81] => 'CURLE_AGAIN',
[82] => 'CURLE_SSL_CRL_BADFILE',
[83] => 'CURLE_SSL_ISSUER_ERROR',
[84] => 'CURLE_FTP_PRET_FAILED',
[84] => 'CURLE_FTP_PRET_FAILED',
[85] => 'CURLE_RTSP_CSEQ_ERROR',
[86] => 'CURLE_RTSP_SESSION_ERROR',
[87] => 'CURLE_FTP_BAD_FILE_LIST',
[88] => 'CURLE_CHUNK_FAILED');
?>
This worked for me
scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();
where filter is following function and scan is the input string:
public String filter(String scan, String regex, String replace) {
StringBuffer sb = new StringBuffer();
Pattern pt = Pattern.compile(regex);
Matcher m = pt.matcher(scan);
while (m.find()) {
m.appendReplacement(sb, replace);
}
m.appendTail(sb);
return sb.toString();
}
What I think that he only wants to know the X/Y positions of cursor than why answer is that complicated.
// Getting 'Info' div in js hands_x000D_
var info = document.getElementById('info');_x000D_
_x000D_
// Creating function that will tell the position of cursor_x000D_
// PageX and PageY will getting position values and show them in P_x000D_
function tellPos(p){_x000D_
info.innerHTML = 'Position X : ' + p.pageX + '<br />Position Y : ' + p.pageY;_x000D_
}_x000D_
addEventListener('mousemove', tellPos, false);
_x000D_
* {_x000D_
padding: 0:_x000D_
margin: 0;_x000D_
/*transition: 0.2s all ease;*/_x000D_
}_x000D_
#info {_x000D_
position: absolute;_x000D_
top: 10px;_x000D_
right: 10px;_x000D_
background-color: black;_x000D_
color: white;_x000D_
padding: 25px 50px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<div id='info'></div>_x000D_
</body>_x000D_
</html>
_x000D_
In my case I had to specify the Port Number using
scp -P 2222 username@hostip:/directory/ /localdirectory/
Here's what I do,
before_action :validate_presence
and then following methods:
def check_presence
params[:param1].present? && params[:param2].present?
end
def validate_presence
if !check_presence
render json: {
error: {
message: "Bad Request, parameters missing.",
status: 500
}
}
end
end
The While statement will not execute until after form1 is closed - as it is outside the main message loop.
Remove it and change the first bit of code to:
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
this.Visible=false;
Form2 form2 = new Form2();
form2.show();
}
else MessageBox.Show("Insert Attributes First !");
}
This is not the best way to achieve what you are looking to do though. Instead consider the Wizard design pattern.
Alternatively you could implement a custom ApplicationContext that handles the lifetime of both forms. An example to implement a splash screen is here, which should set you on the right path.
http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx?display=Print
For me these was my problem, solution from https://unix.stackexchange.com/questions/282908/server-refused-public-key-signature-despite-accepting-key-putty
"Looking at the log /var/log/secure showed that it was just downright refused. I'm somewhat new to centos since I'm mainly a debian kind of guy, so I was unaware of /var/log/secure
After checking this and doing a bit of searching, it turns out PermitRootLogin no needs to be PermitRootLogin without-password if you want to specifically use just keys for root login. That did the trick. Thanks everyone for contributing."
You might want to look into the DateTime.ToShortTimeString() method.
Also, there many other methods and properties on the DateTime object that can help you in formating the date or time in any way you like. Just take a look at the documentation.
It is simpler to use a file (req.xml
in my case) with content you want to send -- like this:
curl -H "Content-Type: text/xml" -d @req.xml -X POST http://localhost/asdf
You should consider using type 'application/xml', too (differences explained here)
Alternatively, without needing making curl actually read the file, you can use cat
to spit the file into the stdout and make curl
to read from stdout like this:
cat req.xml | curl -H "Content-Type: text/xml" -d @- -X POST http://localhost/asdf
Both examples should produce identical service output.
Limit the length of characters in a regular expression? ^[a-z]{6,15}$'
Limit length of characters or Numbers in a regular expression? ^[a-z | 0-9]{6,15}$'
use git stash push -m aNameForYourStash
to save it. Then use git stash list
to learn the index of the stash that you want to apply. Then use git stash pop --index 0
to pop the stash and apply it.
note: I'm using git version 2.21.0.windows.1
I had the same problem.
system configuration:-single system with window 7 sp1 server and client both are installed on same system
I was trying to access the window desktop. As some the answer say that your Sqlserver service don't have full access to the directory. This is totally right.
I solved this problem by doing a few simple steps
Steps 3 and 4 in image are demo with accessing the folder
Use the display: inline
CSS property.
Ideal: In the stylesheet:
#container p { display: inline }
Bad/Extreme situation: Inline:
<p style="display:inline">...</p>
I created a reusable Angular service to handle high quality resizing of images / canvases for anyone who's interested: https://gist.github.com/transitive-bullshit/37bac5e741eaec60e983
The service includes two solutions because they both have their own pros / cons. The lanczos convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.
Example usage:
angular.module('demo').controller('ExampleCtrl', function (imageService) {
// EXAMPLE USAGE
// NOTE: it's bad practice to access the DOM inside a controller,
// but this is just to show the example usage.
// resize by lanczos-sinc filter
imageService.resize($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
// resize by stepping down image size in increments of 2x
imageService.resizeStep($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
})
You should better verify where you get that list from.
An empty list is all you need, because an empty list won't fail.
If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:
for( Object o : safe( list ) ) {
// do whatever
}
And of course safe
would be:
public static List safe( List other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
Turns out 499's really does mean "client interrupted connection."
I had a client "read timeout" setting of 60s (and nginx also has a default proxy_read_timeout of 60s). So what was happening in my case is that nginx would error.log an upstream timed out (110: Connection timed out) while reading upstream
and then nginx retries "the next proxy server in the backend server group you configured." That's if you have more than one.
Then it tries the next and next till (by default) it has exhausted all of them. As each one times out, it removes them from the list of "live" backend servers, as well. After all are exhausted, it returns a 504 gateway timeout.
So in my case nginx marked the server as "unavailable", re-tried it on the next server, then my client's 60s
timeout (immediately) occurred, so I'd see a upstream timed out (110: Connection timed out) while reading upstream
log, immediately followed by a 499 log. But it was just timing coincidence.
Related:
If all servers in the group are marked as currently unavailable, then it returns a 502 Bad Gateway.
for 10s as well. See here max_fails
and fail_timeout. Inn the logs it will say no live upstreams while connecting to upstream.
If you only have one proxy backend in your server group, it just try's the one server, and returns a 504 Gateway Time-out
and doesn't remove the single server from the list of "live" servers, if proxy_read_timeout
is surpassed. See here "If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable."
The really tricky part is that if you specify proxy_pass to "localhost" and your box happens to also have ipv6 and ipv4 "versions of location" on it at the same time (most boxes do by default), it will count as if you had a "list" of multiple servers in your server group, which means you can get into the situation above of having it return "502 for 10s" even though you list only one server. See here "If a domain name resolves to several addresses, all of them will be used in a round-robin fashion."
One workaround is to declare it as proxy_pass http://127.0.0.1:5001;
(its ipv4 address) to avoid it being both ipv6 and ipv4. Then it counts as "only a single server" behavior.
There's a few different settings you can tweak to make this "less" of a problem. Like increasing timeouts or making it so it doesn't mark servers as "disabled" when they timeout...or fixing the list so it's only size 1, see above :)
See also: https://serverfault.com/a/783624/27813
Number(new Date(2010, 6, 26))
Works the same way as things above. If you need seconds don't forget to / 1000
You can do it like you assumed. But your HashMap has to be templated:
Map<String, Map<String, String>> map =
new HashMap<String, Map<String, String>>();
Otherwise you have to do a cast to Map
after you retrieve the second map from the first.
Map map = new HashMap();
((Map)map.get( "keyname" )).get( "nestedkeyname" );
In Android, How to use a Cursor with a raw query in sqlite:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
"where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
c.close();
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
I've found my own solution.
Download FreeDOS from here: http://chtaube.eu/computers/freedos/bootable-usb/
Then using my Counter.exe file (which basically generates a Counter.txt file and increments the number inside every time it's being called), I can assign the value of the number to a variable using:
Set /P Variable =< Counter.txt
Then, I can check if it has run 250 cycles by doing:
if %variable%==250 echo PASS
BTW, I still can't use Set /A since FreeDOS doesn't support this command, but at least it supports the Set /P command.
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.
As for me here the most easily way to add text(Tab -> \t) in textarea by cursor position and save the focus on cursor:
$('#text').keyup(function () {
var cursor = $('#text').prop('selectionStart');
//if cursot is first in textarea
if (cursor == 0) {
//i will add tab in line
$('#text').val('\t' + $('#text').val());
//here we set the cursor position
$('#text').prop('selectionEnd', 1);
} else {
var value = $('#text').val();
//save the value before cursor current position
var valToCur = value.substring(0, cursor);
//save the value after cursor current position
var valAfter = value.substring(cursor, value.length);
//save the new value with added tab in text
$('#text').val(valToCur + '\t' + valAfter);
//set focus of cursot after insert text (1 = because I add only one symbol)
$('#text').prop('selectionEnd', cursor + 1);
}
});
Okay, my 2 cents, using the default value of Laravel's old() function.
<select name="type">
@foreach($options as $key => $text)
<option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
@endforeach
</select>
I ended up removing the submodule directory and initializing it once again
cd my-submodule
git push
cd ../
rm -rf my-submodule
git submodule init
git submodule update
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
It can be caused by:
Please, post your code.
malloc
is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:
char *literal = "foo";
However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc
:
char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
You have to close all of the streams or use try-with-resource block
static public String head(File file) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
final String readLine;
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
LineNumberReader lnr = new LineNumberReader(isr))
{
readLine = lnr.readLine();
}
return readLine;
}
$("#display").load("?control=msgs", {}, function() {
$('#header').focus();
});
i tried it but it doesn't work, please give me more advice to resolve this problem. thanks for your help
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
$pdf->Output()
takes a second parameter $dest
, which accepts a single character. The default, $dest='I'
opens the PDF in the browser.
Use F
to save to file
$pdf->Output('/path/to/file.pdf', 'F')
thanks patrice-n! this code worked to get both queued and running jobs and their parameters:
import hudson.model.Job
import hudson.model.ParametersAction
import hudson.model.Queue
import jenkins.model.Jenkins
println("================================================")
for (Job job : Jenkins.instanceOrNull.getAllItems(Job.class)) {
if (job.isInQueue()) {
println("------------------------------------------------")
println("InQueue " + job.name)
Queue.Item queue = job.getQueueItem()
if (queue != null) {
println(queue.params)
}
}
if (job.isBuilding()) {
println("------------------------------------------------")
println("Building " + job.name)
def build = job.getBuilds().getLastBuild()
def parameters = build?.getAllActions().find{ it instanceof ParametersAction }?.parameters
parameters.each {
def dump = it.dump()
println "parameter ${it.name}: ${dump}"
}
}
}
println("================================================")
Create Globals class in app/globals.ts:
import { Injectable } from '@angular/core';
Injectable()
export class Globals{
VAR1 = 'value1';
VAR2 = 'value2';
}
In your component:
import { Globals } from './globals';
@Component({
selector: 'my-app',
providers: [ Globals ],
template: `<h1>My Component {{globals.VAR1}}<h1/>`
})
export class AppComponent {
constructor(private globals: Globals){
}
}
Note: You can add Globals service provider directly to the module instead of the component, and you will not need to add as a provider to every component in that module.
@NgModule({
imports: [...],
declarations: [...],
providers: [ Globals ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.
You can use the Lambda functions of Java 8 to achieve this without looping
String string = "1, 2, 3, 4";
List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*")
to get a list of all the filenames, loop over the list and use shutil.copy
to copy each file.
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
That way you haven't installed pip, you installed just the easy_install
i.e. setuptools
.
First you should remove all the packages you installed with easy_install
using (see uninstall):
easy_install -m PackageName
This includes pip
if you installed it using easy_install pip
.
After this you remove the setuptools
following the instructions from here:
If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:
setuptools-*.egg
If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:
pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
I had this problem when I was trying to connect my phone and trying to use adb. I did the following
export PATH=$PATH{}:/path/to/android-sdk/tools:/path/to/android/platform-tools
apt-get install ia32-libs
Connected my phone in USB debug mode and In the terminal type lsusb to get a list of all usb devices. Noted the 9 character (xxxx:xxxx) ID to the left of my phone.
sudo gedit /etc/udev/rules.d/99-android.rules
Add [ SUBSYSTEM=="usb", ATTRS{idVendor}=="####:####", SYMLINK+="android_adb", MODE="0666" GROUP="plugdev" TEST=="/var/run/ConsoleKit/database", \ RUN+="udev-acl --action=$env{action} --device=$env{DEVNAME}" ] (whatever is in [...] )to the file and replace "####:####" with the number from step 3cop
sudo service udev restart
Restarted my System
open terminal browse to adb directory and run ./adb devices
And it shows my phone hence adb starts working without error.
I hope it helps others
Build up a JavaScript data structure with the required information, then turn it into the json string at the end.
Based on what I think you're doing, try something like this:
var result = [];
for (var name in goals) {
if (goals.hasOwnProperty(name)) {
result.push({name: name, goals: goals[name]});
}
}
res.contentType('application/json');
res.send(JSON.stringify(result));
or something along those lines.
It is a conditional statement.
If browser supprts e.keyCode then take e.keyCode else e.charCode.
It is similar to
var code = event.keyCode || event.charCode
event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.
event.charCode: Returns the Unicode value of a character key pressed during a keypress event.
As of 17.0 from_csv
is discouraged.
Use pd.read_csv(fpath, sep='\t')
or pd.read_table(fpath)
.
Quote from there:
the rules for index usage with LIKE are loosely like this:
If your filter criteria uses equals = and the field is indexed, then most likely it will use an INDEX/CLUSTERED INDEX SEEK
If your filter criteria uses LIKE, with no wildcards (like if you had a parameter in a web report that COULD have a % but you instead use the full string), it is about as likely as #1 to use the index. The increased cost is almost nothing.
If your filter criteria uses LIKE, but with a wildcard at the beginning (as in Name0 LIKE '%UTER') it's much less likely to use the index, but it still may at least perform an INDEX SCAN on a full or partial range of the index.
HOWEVER, if your filter criteria uses LIKE, but starts with a STRING FIRST and has wildcards somewhere AFTER that (as in Name0 LIKE 'COMP%ER'), then SQL may just use an INDEX SEEK to quickly find rows that have the same first starting characters, and then look through those rows for an exact match.
(Also keep in mind, the SQL engine still might not use an index the way you're expecting, depending on what else is going on in your query and what tables you're joining to. The SQL engine reserves the right to rewrite your query a little to get the data in a way that it thinks is most efficient and that may include an INDEX SCAN instead of an INDEX SEEK)
But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.
Umm. Just change the string passed to the prompt()
function.
While searching, I found that there we CANNOT change the content of popup Prompt Box
You can't change the title. You can change the content, it is the first argument passed to the prompt()
function.
you want this?
employees.ForEach(emp =>
{
collection.AddRange(emp.Departments.Where(dept => { dept.SomeProperty = null; return true; }));
});
The solution
angular.element(document.getElementById('ID')).scope().get()
stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also.
I fixed it by storing the scope in a global variable:
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope = function bar(){
console.log("foo");
};
scopeHolder = $scope;
})
call from custom code:
scopeHolder.bar()
if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope.bar = function(){
console.log("foo");
};
scopeHolder = $scope.bar;
})
call from custom code:
scopeHolder()
The second question is actually easier to answer. Look at the stringWithContentsOfURL:encoding:error:
method of NSString - it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:
NSString *googleString = @"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL
encoding:NSASCIIStringEncoding
error:&error];
After running this code, googlePage
will contain the HTML for www.google.com, and error
will contain any errors encountered in the fetch. (You should check the contents of error
after the fetch.)
Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You'll have to pull the request from the view, then do the fetch as before:
NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
EDIT: Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its stringByEvaluatingJavascriptFromString:
method, as such:
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:
@"document.body.innerHTML"];
This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.
Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let's say you take the second example above, where you have NSString *page
as the result of a call to stringWithContentsOfURL:encoding:error:
. You can then push that string into the web view using loadHTMLString:baseURL:
, assuming you also held on to the NSURL you requested:
[yourWebView loadHTMLString:page baseURL:requestURL];
I'm not sure, however, if this will run JavaScript found in the page you load (the method name, loadHTMLString
, is somewhat ambiguous, and the docs don't say much about it).
For more info:
With image class name:
$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image
With image Id :
$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image
i have same problem, i open several dialog my problem was what the content should be removed to prevent the form data stay with same data, then the dialog is created these paramters
var dialog = $("#dummy-1");
dialog.html('<div style="position:absolute; top:15px; left:0px; right:0px; bottom:0px; text-align:center;"><img align="middle" src="cargando.gif"></div>');
dialog.html(mensaje);
dialog.dialog(
{
title:'Ventana de Confirmacion',
width:400,
height:200,
modal:true,
resizable: false,
draggable:false,
position: { my: "center center", at: "center center", of: window },
buttons:
[
{
text: "Eliminar",
click: function() {
functionCall(dialog,var1,var2);
}
},
{
text: "Cerrar",
click: function() {
dialog.dialog("close");
}
}
],
close: function(event, ui)
{
dialog.dialog("close").dialog("destroy").remove();
}
});
and the dialog is passed as a parameter to the function to do action:
function functionCall(dialogFormulario,var1,var2)
{
//same action
dialogFormulario.dialog("close");
}
Here it is necessary only to use .dialog("close") and no .dialog("destroy") because the dialog will call its function close: and the element will not exist
First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
as a dependency in project.json
. Use beta5 or 6 if you don't have 7 installed.
Then you can do something like this in Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
If you then want to retrieve a variable from the config.json you can get it right away using:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
or you can create a class called AppSettings like this:
public class AppSettings
{
public string token { get; set; }
}
and configure the services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
and then access it through e.g. a controller like this:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
Whoa. You're really over-complicating it by a very long distance. Try:
>>> print hex(0x12ef ^ 0xabcd)
0xb922
You seem to be ignoring these handy facts, at least:
0x
prefix.hex()
function can be used to convert any number into a hexadecimal string for display.If you already have the numbers as strings, you can use the int()
function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):
>>> print int("12ef", 16)
4874
So you can do two conversions, perform the XOR, and then convert back to hex:
>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922
2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010
#define fe(EL, CONTAINER) for each (auto EL in CONTAINER) //VS2010
Flo stdDev(VFlo CR crVec) {
SZ n = crVec.size(); if (n < 2) return 0.0f;
Flo fSqSum = 0.0f, fSum = 0.0f;
fe(f, crVec) fSqSum += f * f; // EDIT: was Cit(VFlo, crVec) {
fe(f, crVec) fSum += f;
Flo fSumSq = fSum * fSum;
Flo fSumSqDivN = fSumSq / n;
Flo fSubSqSum = fSqSum - fSumSqDivN;
Flo fPreSqrt = fSubSqSum / (n - 1);
return sqrt(fPreSqrt);
}
The way i did in Android Studio which is also based on IntelliJ was like this. In commit dialog, I reverted the change for workspace.xml, then it was moved to unversioned file. After that I deleted this from commit dialog. Now it won't appear in the changelist. Note that my gitignore was already including .idea/workspace.xml
Simply invoke orderBy()
as many times as you need it. For instance:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
Produces the following query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
(Note 29/08/2017: live
was deprecated many versions ago and removed in v1.9. delegate
was deprecated in v3.0. In both cases, use the delegating signature of on
instead [also covered below].)
live
happens by capturing the event when it's bubbled all the way up the DOM to the document root, and then looking at the source element. click
happens by capturing the event on the element itself. So if you're using live
, and one of the ancestor elements is hooking the event directly (and preventing it continuing to bubble), you'll never see the event on your element. Whereas normally, the element nearest the event (click or whatever) gets first grab at it, the mix of live
and non-live
events can change that in subtle ways.
For example:
jQuery(function($) {_x000D_
_x000D_
$('span').live('click', function() {_x000D_
display("<tt>live</tt> caught a click!");_x000D_
});_x000D_
_x000D_
$('#catcher').click(function() {_x000D_
display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
function display(msg) {_x000D_
$("<p>").html(msg).appendTo(document.body);_x000D_
}_x000D_
_x000D_
});
_x000D_
<div>_x000D_
<span>Click me</span>_x000D_
<span>or me</span>_x000D_
<span>or me</span>_x000D_
<div>_x000D_
<span>I'm two levels in</span>_x000D_
<span>so am I</span>_x000D_
</div>_x000D_
<div id='catcher'>_x000D_
<span>I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span>me too</span>_x000D_
</div>_x000D_
</div>_x000D_
<!-- Using an old version because `live` was removed in v1.9 -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">_x000D_
</script>
_x000D_
I'd recommend using delegate
over live
when you can, so you can more thoroughly control the scope; with delegate
, you control the root element that captures the bubbling event (e.g., live
is basically delegate
using the document root as the root). Also, recommend avoiding (where possible) having delegate
or live
interacting with non-delegated, non-live event handling.
Here several years later, you wouldn't use either live
or delegate
; you'd use the delegating signature of on
, but the concept is still the same: The event is hooked on the element you call on
on, but then fired only when descendants match the selector given after the event name:
jQuery(function($) {_x000D_
_x000D_
$(document).on('click', 'span', function() {_x000D_
display("<tt>live</tt> caught a click!");_x000D_
});_x000D_
_x000D_
$('#catcher').click(function() {_x000D_
display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
function display(msg) {_x000D_
$("<p>").html(msg).appendTo(document.body);_x000D_
}_x000D_
_x000D_
});
_x000D_
<div>_x000D_
<span>Click me</span>_x000D_
<span>or me</span>_x000D_
<span>or me</span>_x000D_
<div>_x000D_
<span>I'm two levels in</span>_x000D_
<span>so am I</span>_x000D_
</div>_x000D_
<div id='catcher'>_x000D_
<span>I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span>me too</span>_x000D_
</div>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
You can try the following code to convert the image to hex string
<?php
$image = 'sample.bmp';
$file = fopen($image, 'r') or die("Could not open $image");
while ($file && !feof($file)){
$chunk = fread($file, 1000000); # You can affect performance altering
this number. YMMV.
# This loop will be dog-slow, almost for sure...
# You could snag two or three bytes and shift/add them,
# but at 4 bytes, you violate the 7fffffff limit of dechex...
# You could maybe write a better dechex that would accept multiple bytes
# and use substr... Maybe.
for ($byte = 0; $byte < strlen($chunk); $byte++)){
echo dechex(ord($chunk[$byte]));
}
}
?>
Somehow your requirement sounds a bit contradictory ..
group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP
What do you think should happen if two people (names) worked from the same IP within the time period specified?
Did you try this?
SELECT name, COUNT(name), time, price, ip, SUM(price)
FROM tablename
WHERE time >= $yesterday AND time <$today
GROUP BY name,ip
<%= Html.Partial("PartialName", Model) %>
SELECT
T.NAME AS [TABLE NAME]
,C.NAME AS [COLUMN NAME]
,P.NAME AS [DATA TYPE]
,P.MAX_LENGTH AS [Max_SIZE]
,C.[max_length] AS [ActualSizeUsed]
,CAST(P.PRECISION AS VARCHAR) +'/'+ CAST(P.SCALE AS VARCHAR) AS [PRECISION/SCALE]
FROM SYS.OBJECTS AS T
JOIN SYS.COLUMNS AS C
ON T.OBJECT_ID = C.OBJECT_ID
JOIN SYS.TYPES AS P
ON C.SYSTEM_TYPE_ID = P.SYSTEM_TYPE_ID
AND C.[user_type_id] = P.[user_type_id]
WHERE T.TYPE_DESC='USER_TABLE'
AND T.name = 'InventoryStatus'
ORDER BY 2
Set the [Console]::OuputEncoding
as encoding whatever you want, and print out with [Console]::WriteLine
.
If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)
Each python object has a __dict__
atttribute which is a dictionary containing all other attributes. e.g. when you type self.attr
python is actually doing self.__dict__['attr']
. As you can imagine using a dictionary to store attribute takes some extra space & time for accessing it.
However, when you use __slots__
, any object created for that class won't have a __dict__
attribute. Instead, all attribute access is done directly via pointers.
So if want a C style structure rather than a full fledged class you can use __slots__
for compacting size of the objects & reducing attribute access time. A good example is a Point class containing attributes x & y. If you are going to have a lot of points, you can try using __slots__
in order to conserve some memory.
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
var myList = [_x000D_
{ "name": "abc", "age": 50 },_x000D_
{ "age": "25", "hobby": "swimming" },_x000D_
{ "name": "xyz", "hobby": "programming" }_x000D_
];_x000D_
_x000D_
// Builds the HTML Table out of myList._x000D_
function buildHtmlTable(selector) {_x000D_
var columns = addAllColumnHeaders(myList, selector);_x000D_
_x000D_
for (var i = 0; i < myList.length; i++) {_x000D_
var row$ = $('<tr/>');_x000D_
for (var colIndex = 0; colIndex < columns.length; colIndex++) {_x000D_
var cellValue = myList[i][columns[colIndex]];_x000D_
if (cellValue == null) cellValue = "";_x000D_
row$.append($('<td/>').html(cellValue));_x000D_
}_x000D_
$(selector).append(row$);_x000D_
}_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records._x000D_
function addAllColumnHeaders(myList, selector) {_x000D_
var columnSet = [];_x000D_
var headerTr$ = $('<tr/>');_x000D_
_x000D_
for (var i = 0; i < myList.length; i++) {_x000D_
var rowHash = myList[i];_x000D_
for (var key in rowHash) {_x000D_
if ($.inArray(key, columnSet) == -1) {_x000D_
columnSet.push(key);_x000D_
headerTr$.append($('<th/>').html(key));_x000D_
}_x000D_
}_x000D_
}_x000D_
$(selector).append(headerTr$);_x000D_
_x000D_
return columnSet;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body onLoad="buildHtmlTable('#excelDataTable')">_x000D_
<table id="excelDataTable" border="1">_x000D_
</table>_x000D_
</body>
_x000D_
@Column
AnnotationThe nullable
attribute of the @Column
annotation has two purposes:
The HBM2DDL schema generation tool translates the @Column(nullable = false)
entity attribute to a NOT NULL
constraint for the associated table column when generating the CREATE TABLE
statement.
As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.
When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false)
entity attribute:
new Nullability( session ).checkNullability( values, persister, true );
If the validation fails, Hibernate will throw a PropertyValueException
, and prevents the INSERT or UPDATE statement to be executed needesly:
if ( !nullability[i] && value == null ) {
//check basic level one nullablilty
throw new PropertyValueException(
"not-null property references a null or transient value",
persister.getEntityName(),
persister.getPropertyNames()[i]
);
}
@NotNull
AnnotationThe @NotNull
annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.
When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation
when validating the entity.
try out this it is much simpler ,this will help u:
// Open your local db as the input stream
InputStream myInput = _context.getAssets().open(YOUR FILE NAME);
// Path to the just created empty db
String outFileName =SDCARD PATH + YOUR FILE NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
There is no such thing as the "last" row in a table, as an Oracle table has no concept of order.
However, assuming that you wanted to find the last inserted primary key and that this primary key is an incrementing number, you could do something like this:
select *
from ( select a.*, max(pk) over () as max_pk
from my_table a
)
where pk = max_pk
If you have the date that each row was created this would become, if the column is named created
:
select *
from ( select a.*, max(created) over () as max_created
from my_table a
)
where created = max_created
Alternatively, you can use an aggregate query, for example:
select *
from my_table
where pk = ( select max(pk) from my_table )
Here's a little SQL Fiddle to demonstrate.
Here's a simple way using ngModel
(final Angular 2)
<!-- my.component.html -->
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options">
<label>
<input type="checkbox"
name="options"
value="{{option.value}}"
[(ngModel)]="option.checked"/>
{{option.name}}
</label>
</div>
</div>
// my.component.ts
@Component({ moduleId:module.id, templateUrl:'my.component.html'})
export class MyComponent {
options = [
{name:'OptionA', value:'1', checked:true},
{name:'OptionB', value:'2', checked:false},
{name:'OptionC', value:'3', checked:true}
]
get selectedOptions() { // right now: ['1','3']
return this.options
.filter(opt => opt.checked)
.map(opt => opt.value)
}
}
The PIL distribution is mispackaged for egg installation.
Install Pillow instead, the friendly PIL fork.
In my case I received a message like this: See this picture
I just commented the snipped code below in the project file (.csproj) and the problem was fixed.
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
Figured out quick solution, update your @NgModule code like this :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Source: Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’
IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.
Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.
Hello I am trying to add new session values in node js like
req.session.portal = false
Passport.authenticate('facebook', (req, res, next) => {
next()
})(req, res, next)
On passport strategies I am not getting portal value in mozilla request but working fine with chrome and opera
FacebookStrategy: new PassportFacebook.Strategy({
clientID: Configuration.SocialChannel.Facebook.AppId,
clientSecret: Configuration.SocialChannel.Facebook.AppSecret,
callbackURL: Configuration.SocialChannel.Facebook.CallbackURL,
profileFields: Configuration.SocialChannel.Facebook.Fields,
scope: Configuration.SocialChannel.Facebook.Scope,
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
console.log(JSON.stringify(req.session));
from datetime import datetime
date_today = datetime.now()
month_first_day = date_today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
print(month_first_day)
To add to the above correct answer :-
For my case in shell, this code worked (working on sqoop
)
ROOT_PATH="path/to/the/folder"
--options-file $ROOT_PATH/query.txt
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
Use the For-Each loop which came with Java 1.5, and it work on Types which are iterable.
ArrayList<String> data = new ArrayList<String>();
data.add("Vivek");
data.add("Vadodara");
data.add("Engineer");
data.add("Feelance");
for (String s : data){
System.out.prinln("Data of "+data.indexOf(s)+" "+s);
}
I usually use XmlDocument
for this. The interface is pretty straight forward:
var doc = new XmlDocument();
doc.LoadXml(xmlString);
You can access nodes similar to a dictionary:
var tasks = doc["Tasks"];
and loop over all children of a node.
For me, ddkkp
did it (instead of ddkP
with an uppercase P, which would work too).
Try this. The following considers checkbox and label as a unique element:
<style>
.item {white-space: nowrap;display:inline }
</style>
<fieldset>
<div class="item">
<input type="checkbox" id="a">
<label for="a">aaaaaaaaaaaa aaaa a a a a a a aaaaaaaaaaaaa</label>
</div>
<div class="item">
<input type="checkbox" id="b">
<!-- depending on width, a linebreak NEVER occurs here. -->
<label for="b">bbbbbbbbbbbb bbbbbbbbbbbbbbbbb b b b b bb</label>
</div>
<div class="item">
<input type="checkbox" id="c">
<label for="c">ccccc c c c c ccccccccccccccc cccc</label>
</div>
</fieldset>
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
package secondhighestno;
import java.util.Scanner;
/**
*
* @author Laxman
*/
public class SecondHighestno {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int max1=a[0],max2=a[0];
for(int j=0;j<n;j++){
if(a[j]>max1){
max1=a[j];
}
}
for(int k=0;k<n;k++){
if(a[k]>max2 && max1>a[k]){
max2=a[k];
}
}
System.out.println(max1+" "+max2);
}
}
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
I would guess it makes an infinite loop bc you skip the number 100. If you set the critera to be less than 101 it should do the trick :)
def gukan(count):
while count<100:
print(count)
count=count+3;
gukan(0)
No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
For Local module usenpm list --depth 0
Foe Global module npm list -g --depth 0
Here's a simple scraper I created in c# to get streaming quote data printed out to a console. It should be easily converted to java. Based on the following post:
http://blog.underdog-projects.net/2009/02/bringing-the-yahoo-finance-stream-to-the-shell/
Not too fancy (i.e. no regex etc), just a fast & dirty solution.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace WebDataAddin
{
public class YahooConstants
{
public const string AskPrice = "a00";
public const string BidPrice = "b00";
public const string DayRangeLow = "g00";
public const string DayRangeHigh = "h00";
public const string MarketCap = "j10";
public const string Volume = "v00";
public const string AskSize = "a50";
public const string BidSize = "b60";
public const string EcnBid = "b30";
public const string EcnBidSize = "o50";
public const string EcnExtHrBid = "z03";
public const string EcnExtHrBidSize = "z04";
public const string EcnAsk = "b20";
public const string EcnAskSize = "o40";
public const string EcnExtHrAsk = "z05";
public const string EcnExtHrAskSize = "z07";
public const string EcnDayHigh = "h01";
public const string EcnDayLow = "g01";
public const string EcnExtHrDayHigh = "h02";
public const string EcnExtHrDayLow = "g11";
public const string LastTradeTimeUnixEpochformat = "t10";
public const string EcnQuoteLastTime = "t50";
public const string EcnExtHourTime = "t51";
public const string RtQuoteLastTime = "t53";
public const string RtExtHourQuoteLastTime = "t54";
public const string LastTrade = "l10";
public const string EcnQuoteLastValue = "l90";
public const string EcnExtHourPrice = "l91";
public const string RtQuoteLastValue = "l84";
public const string RtExtHourQuoteLastValue = "l86";
public const string QuoteChangeAbsolute = "c10";
public const string EcnQuoteAfterHourChangeAbsolute = "c81";
public const string EcnQuoteChangeAbsolute = "c60";
public const string EcnExtHourChange1 = "z02";
public const string EcnExtHourChange2 = "z08";
public const string RtQuoteChangeAbsolute = "c63";
public const string RtExtHourQuoteAfterHourChangeAbsolute = "c85";
public const string RtExtHourQuoteChangeAbsolute = "c64";
public const string QuoteChangePercent = "p20";
public const string EcnQuoteAfterHourChangePercent = "c82";
public const string EcnQuoteChangePercent = "p40";
public const string EcnExtHourPercentChange1 = "p41";
public const string EcnExtHourPercentChange2 = "z09";
public const string RtQuoteChangePercent = "p43";
public const string RtExtHourQuoteAfterHourChangePercent = "c86";
public const string RtExtHourQuoteChangePercent = "p44";
public static readonly IDictionary<string, string> CodeMap = typeof(YahooConstants).GetFields().
Where(field => field.FieldType == typeof(string)).
ToDictionary(field => ((string)field.GetValue(null)).ToUpper(), field => field.Name);
}
public static class StringBuilderExtensions
{
public static bool HasPrefix(this StringBuilder builder, string prefix)
{
return ContainsAtIndex(builder, prefix, 0);
}
public static bool HasSuffix(this StringBuilder builder, string suffix)
{
return ContainsAtIndex(builder, suffix, builder.Length - suffix.Length);
}
private static bool ContainsAtIndex(this StringBuilder builder, string str, int index)
{
if (builder != null && !string.IsNullOrEmpty(str) && index >= 0
&& builder.Length >= str.Length + index)
{
return !str.Where((t, i) => builder[index + i] != t).Any();
}
return false;
}
}
public class WebDataAddin
{
public const string ScriptStart = "<script>";
public const string ScriptEnd = "</script>";
public const string MessageStart = "try{parent.yfs_";
public const string MessageEnd = ");}catch(e){}";
public const string DataMessage = "u1f(";
public const string InfoMessage = "mktmcb(";
protected static T ParseJson<T>(string json)
{
// parse json - max acceptable value retrieved from
//http://forums.asp.net/t/1343461.aspx
var deserializer = new JavaScriptSerializer { MaxJsonLength = 2147483647 };
return deserializer.Deserialize<T>(json);
}
public static void Main()
{
const string symbols = "GBPUSD=X,SPY,MSFT,BAC,QQQ,GOOG";
// these are constants in the YahooConstants enum above
const string attrs = "b00,b60,a00,a50";
const string url = "http://streamerapi.finance.yahoo.com/streamer/1.0?s={0}&k={1}&r=0&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb®ion=US&lang=en-US&localize=0&mu=1";
var req = WebRequest.Create(string.Format(url, symbols, attrs));
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
var missingCodes = new HashSet<string>();
var response = req.GetResponse();
if(response != null)
{
var stream = response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var builder = new StringBuilder();
var initialPayloadReceived = false;
while (!reader.EndOfStream)
{
var c = (char)reader.Read();
builder.Append(c);
if(!initialPayloadReceived)
{
if (builder.HasSuffix(ScriptStart))
{
// chop off the first part, and re-append the
// script tag (this is all we care about)
builder.Clear();
builder.Append(ScriptStart);
initialPayloadReceived = true;
}
}
else
{
// check if we have a fully formed message
// (check suffix first to avoid re-checking
// the prefix over and over)
if (builder.HasSuffix(ScriptEnd) &&
builder.HasPrefix(ScriptStart))
{
var chop = ScriptStart.Length + MessageStart.Length;
var javascript = builder.ToString(chop,
builder.Length - ScriptEnd.Length - MessageEnd.Length - chop);
if (javascript.StartsWith(DataMessage))
{
var json = ParseJson<Dictionary<string, object>>(
javascript.Substring(DataMessage.Length));
// parse out the data. key should be the symbol
foreach(var symbol in json)
{
Console.WriteLine("Symbol: {0}", symbol.Key);
var symbolData = (Dictionary<string, object>) symbol.Value;
foreach(var dataAttr in symbolData)
{
var codeKey = dataAttr.Key.ToUpper();
if (YahooConstants.CodeMap.ContainsKey(codeKey))
{
Console.WriteLine("\t{0}: {1}", YahooConstants.
CodeMap[codeKey], dataAttr.Value);
} else
{
missingCodes.Add(codeKey);
Console.WriteLine("\t{0}: {1} (Warning! No Code Mapping Found)",
codeKey, dataAttr.Value);
}
}
Console.WriteLine();
}
} else if(javascript.StartsWith(InfoMessage))
{
var json = ParseJson<Dictionary<string, object>>(
javascript.Substring(InfoMessage.Length));
foreach (var dataAttr in json)
{
Console.WriteLine("\t{0}: {1}", dataAttr.Key, dataAttr.Value);
}
Console.WriteLine();
} else
{
throw new Exception("Cannot recognize the message type");
}
builder.Clear();
}
}
}
}
}
}
}
}
}
with()
is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
whereHas()
works basically the same as has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
Of course, the accepted answer of Arrays.equal( byte[] first, byte[] second ) is correct. I like to work at a lower level, but I was unable to find a low level efficient function to perform equality test ranges. I had to whip up my own, if anyone needs it:
public static boolean ArraysAreEquals(
byte[] first,
int firstOffset,
int firstLength,
byte[] second,
int secondOffset,
int secondLength
) {
if( firstLength != secondLength ) {
return false;
}
for( int index = 0; index < firstLength; ++index ) {
if( first[firstOffset+index] != second[secondOffset+index]) {
return false;
}
}
return true;
}
To answer the questions directly:
Will
collect()
behave the same way if called on a dataframe?
Yes, spark.DataFrame.collect
is functionally the same as spark.RDD.collect
. They serve the same purpose on these different objects.
What about the
select()
method?
There is no such thing as spark.RDD.select
, so it cannot be the same as spark.DataFrame.select
.
Does it also work the same way as
collect()
if called on a dataframe?
The only thing that is similar between select
and collect
is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.
Here's my own description: collect
is the opposite of sc.parallelize
. select
is the same as the SELECT
in any SQL statement.
If you are still having trouble understanding what collect
actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:
You need to set an own WebViewClient for your WebView by extending the WebViewClient class.
You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).
More guidance for this topic can be found in Google's WebView tutorial
Note the extra comments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
class JavaPaintUI extends JFrame {
private int tool = 1;
int currentX, currentY, oldX, oldY;
public JavaPaintUI() {
initComponents();
}
private void initComponents() {
// we want a custom Panel2, not a generic JPanel!
jPanel2 = new Panel2();
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
jPanel2.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
jPanel2MousePressed(evt);
}
public void mouseReleased(MouseEvent evt) {
jPanel2MouseReleased(evt);
}
});
jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
jPanel2MouseDragged(evt);
}
});
// add the component to the frame to see it!
this.setContentPane(jPanel2);
// be nice to testers..
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}// </editor-fold>
private void jPanel2MouseDragged(MouseEvent evt) {
if (tool == 1) {
currentX = evt.getX();
currentY = evt.getY();
oldX = currentX;
oldY = currentY;
System.out.println(currentX + " " + currentY);
System.out.println("PEN!!!!");
}
}
private void jPanel2MousePressed(MouseEvent evt) {
oldX = evt.getX();
oldY = evt.getY();
System.out.println(oldX + " " + oldY);
}
//mouse released//
private void jPanel2MouseReleased(MouseEvent evt) {
if (tool == 2) {
currentX = evt.getX();
currentY = evt.getY();
System.out.println("line!!!! from" + oldX + "to" + currentX);
}
}
//set ui visible//
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new JavaPaintUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JPanel jPanel2;
// End of variables declaration
// This class name is very confusing, since it is also used as the
// name of an attribute!
//class jPanel2 extends JPanel {
class Panel2 extends JPanel {
Panel2() {
// set a preferred size for the custom panel.
setPreferredSize(new Dimension(420,420));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("BLAH", 20, 20);
g.drawRect(200, 200, 200, 200);
}
}
}
HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage
in the Custom Painting Approaches article.
See also this approach using painting in a BufferedImage
.
The "netstat --programs"
command will give you the process information, assuming you're the root
user. Then you will have to kill the "offending" process which may well start up again just to annoy you.
Depending on what you're actually trying to achieve, solutions to that problem will vary based on the processes holding those ports. For example, you may need to disable services (assuming they're unneeded) or configure them to use a different port (if you do need them but you need that port more).
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
without what? do you mean
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
?
If anyone is looking for a simple solution in Laravel 5.3:
timestamps()
be saved as is i.e. '2016-11-14 12:19:49'In your views, format the field as below (or as required):
date('F d, Y', strtotime($list->created_at))
It worked for me very well for me.
For httpclient 4.1.x you can set the proxy like this (taken from this example):
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via " + proxy);
HttpResponse rsp = httpclient.execute(target, req);
...
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
If the Array class meets your needs, you could also use the List.ToArray method, which copies elements to a new array.
Reference: http://msdn.microsoft.com/en-us/library/x303t819(v=vs.110).aspx
Unfortunately, AFAIK you cannot run multiple SQL statements under one named query in Access in the traditional sense.
You can make several queries, then string them together with VBA (DoCmd.OpenQuery
if memory serves).
You can also string a bunch of things together with UNION if you wish.
For users of SQL 2000, the actual command that will provide this information is:
select c.text
from sysobjects o
join syscomments c on c.id = o.id
where o.name = '<view_name_here>'
and o.type = 'V'
This script demonstrates a few ways to show the local timezone using astimezone()
:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
from tzlocal import get_localzone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone('US/Pacific')
EST = pytz.timezone('US/Eastern')
JST = pytz.timezone('Asia/Tokyo')
NZST = pytz.timezone('Pacific/Auckland')
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat()))
print("UTC time {}".format(utc_dt.isoformat()))
print("Japan time {}".format(utc_dt.astimezone(JST).isoformat()))
# Use astimezone() without an argument
print("Local time {}".format(utc_dt.astimezone().isoformat()))
# Use tzlocal get_localzone
print("Local time {}".format(utc_dt.astimezone(get_localzone()).isoformat()))
# Explicitly create a pytz timezone object
# Substitute a pytz.timezone object for your timezone
print("Local time {}".format(utc_dt.astimezone(NZST).isoformat()))
It outputs the following:
$ ./timezones.py
Pacific time 2019-02-22T17:54:14.957299-08:00
Eastern time 2019-02-22T20:54:14.957299-05:00
UTC time 2019-02-23T01:54:14.957299+00:00
Japan time 2019-02-23T10:54:14.957299+09:00
Local time 2019-02-23T14:54:14.957299+13:00
Local time 2019-02-23T14:54:14.957299+13:00
Local time 2019-02-23T14:54:14.957299+13:00
As of python 3.6 calling astimezone()
without a timezone object defaults to the local zone (docs). This means you don't need to import tzlocal
and can simply do the following:
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
print("Local time {}".format(utc_dt.astimezone().isoformat()))
To show vertical scroll bar in your div you need to add
height: 100px;
overflow-y : scroll;
or
height: 100px;
overflow-y : auto;
To squash the last 10 commits into 1 single commit:
git reset --soft HEAD~10 && git commit -m "squashed commit"
If you also want to update the remote branch with the squashed commit:
git push -f
Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
It will round up so be aware of that.
I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.
Source: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
Don't let white space fool you. Just test this in a console browser.
Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.
How to get around white space with querySelector()
then childNodes[]
js fiddle link: https://jsfiddle.net/aparadise/56njekdo/
var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';
<ul class="list">
<li>8</li>
<li>9</li>
<li>100</li>
</ul>
<ul class="list">
<li>ABC</li>
<li>DEF</li>
<li>XYZ</li>
</ul>
Copy the image then paste it to drawables in the resource folder of you project in android studio.Make sure the name of your image is not too long and does not have any spacial characters.Then click SRC(source) under properties and look for your image click on it then it will automatically get imported to you image view on you emulator.
UPDATE
In Android Studio Version 3.5 and Above
Now Instant Run is removed, It has "Apply Changes". See official blog for more about the change.
we removed Instant Run and re-architectured and implemented from the ground-up a more practical approach in Android Studio 3.5 called Apply Changes.Apply Changes uses platform-specific APIs from Android Oreo and higher to ensure reliable and consistent behavior; unlike Instant Run, Apply Changes does not modify your APK. To support the changes, we re-architected the entire deployment pipeline to improve deployment speed, and also tweaked the run and deployment toolbar buttons for a more streamlined experience.
Now, As per stable available version 3.0 of Android studio,
If you need to turn off Instant Run, go to
File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.
The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync()
is an asynchronous method, the Cancel
operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...)
exitst. You should wait for cmdDataSourceExtractor
to complete before calling RunWorkerAsync
again. How to do this is explained in this SO question.
$('#field-function_purpose')
will get you the element with ID field-function_purpose
, which is your div element. text()
returns you the content of the div.
var x = $('#field-function_purpose').text();
Nope, no difference. It's just syntactic sugar. Arrays.asList(..)
creates an additional list.
Consider the following link to minify Javascript/CSS files: https://github.com/mrclay/minify
Tell Apache to deliver HTML with GZip - this generally reduces the response size by about 70%. (If you use Apache, the module configuring gzip depends on your version: Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate.)
Accept-Encoding: gzip, deflate
Content-Encoding: gzip
Use the following snippet to remove white-spaces from the HTML with the help ob_start's buffer:
<?php
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/' // Remove HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
?>
And using the joiner
from http://jinja.pocoo.org/docs/dev/templates/#joiner
{% set comma = joiner(",") %}
{% for user in userlist %}
{{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}
It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.
A more complex example on why you would use it.
{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
<a href="?action=edit">Edit</a>
{% endif %}
Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet
extends java.util.HashSet
. The method add()
is overridden in LinkedHashSet
. If you have a variable that is of type HashSet
, and you call its add()
method, it will call the appropriate implementation of add()
, based on whether it is a HashSet
or a LinkedHashSet
. This is called polymorphism.
Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println()
is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.
As has been said previously, assertions should be used when your code SHOULD NOT ever reach a point, meaning there is a bug there. Probably the most useful reason I can see to use an assertion is an invariant/pre/postcondition. These are something that must be true at the start or end of each iteration of a loop or a function.
For example, a recursive function (2 seperate functions so 1 handles bad input and the other handles bad code, cause it's hard to distinguish with recursion). This would make it obvious if I forgot to write the if statement, what had gone wrong.
def SumToN(n):
if n <= 0:
raise ValueError, "N must be greater than or equal to 0"
else:
return RecursiveSum(n)
def RecursiveSum(n):
#precondition: n >= 0
assert(n >= 0)
if n == 0:
return 0
return RecursiveSum(n - 1) + n
#postcondition: returned sum of 1 to n
These loop invariants often can be represented with an assertion.
Is there a way to set the session timeout programatically
There are basically three ways to set the session timeout value:
session-timeout
in the standard web.xml
file ~or~session-timeout
value (and thus configuring it at the server level) ~or~HttpSession. setMaxInactiveInterval(int seconds)
method in your Servlet or JSP. But note that the later option sets the timeout value for the current session, this is not a global setting.
Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.
Maybe i dont understand , why cant you just get the element.text and then convert it before using it ? for instance (dont know why you would do this but...) find all label elements of the web page and iterate between them until you find one called MyText
avail = []
avail = driver.find_elements_by_class_name("label");
for i in avail:
if i.text == "MyText":
Convert the string from i and do whatever you wanted to do ... maybe im missing something in the original message ? or was this what you were looking for ?
If the text is retrieved from a mysql database you may try adding this after BD connection.
mysqli_set_charset($con, "utf8");
The simplest way as you have explained is this link this is for 'Dow Jones Industrial Average'
Link 2 is for 'NASDAQ-100'
and for all related to NASDAQ link 3
I think this should be it, else you want same in JSON notations the same as Microsoft
Please refer this old post I think this will help,
Update:
To know the details of volume and other details, I have created a vbscript that is using IE object to fetch details from the link, and alerts the content in the particular id(Create a .vbs file and run it..
Set IE = CreateObject("InternetExplorer.Application")
while IE.readyState = 4: WScript.Sleep 10: wend
IE.Navigate "https://www.google.com/finance?q=INDEXNASDAQ%3ANDX&sq=NASDAQ&sp=2&ei=B3UoUsiIH5DIlgPEsQE"
IE.visible = true
while IE.readyState = 4: WScript.Sleep 10: wend
dim ht
ht= IE.document.getElementById("market-data-div").innerText
msgBox ht
IE.quit
this will alert the values from page like this
3,124.54 0.00 (0.00%)
Sep 4 - Close
INDEXNASDAQ real-time data - Disclaimer
Range -
52 week 2,494.38 - 3,149.24
Open -
Vol. 0.00
I am sure this will help..
A combination of TRANSCRIPT_MODE_ALWAYS_SCROLL and setSelection made it work for me
ChatAdapter adapter = new ChatAdapter(this);
ListView lv = (ListView) findViewById(R.id.chatList);
lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lv.setAdapter(adapter);
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
lv.setSelection(adapter.getCount() - 1);
}
});
It may also be the case that the library containing the class in question is not properly signed with a strong name.
As of 10/22/2019, I think the best answer is simply
conda install opencv
It appears opencv
is now in the main Anaconda
channel.
To see which packages (including opencv
) are in the main Anaconda
channel go to Anaconda Package Lists and follow the link corresponding to your python version and os version.
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.