For boot2docker, we can set it on /var/lib/boot2docker/profile
, for instance:
ulimit -n 2018
Be warned not to set this limit too high as it will slow down apt-get! See bug #1332440. I had it with debian jessie.
I have lots of trouble getting this to work.
Using the following allows you to update it regardless of your user permission.
sudo sysctl -w fs.inotify.max_user_watches=100000
Edit
Just saw this from another user also on another stackexchange site (both work, but this version permanently updates the system setting, rather than temporarily):
echo fs.inotify.max_user_watches=100000 | sudo tee -a /etc/sysctl.conf;
sudo sysctl -p
When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.
To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s
. If we remove that limit via ulimit -s unlimited
, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.
int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.
Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.
Impact on performace is minor but does exist. Using the time
command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).
In Rails 3.2 and Rails 4, Benjamin's popular answer has a slightly different syntax.
First in your terminal:
$ rails g migration change_date_format_in_my_table
Then in your migration file:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
String[] split = data.split("\\|",-1);
This is not the actual requirement in all the time. The Drawback of above is show below:
Scenerio 1:
When all data are present:
String data = "5|6|7||8|9|10|";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 7
System.out.println(splt.length); //output: 8
When data is missing:
Scenerio 2: Data Missing
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output: 8
Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output:7
What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
Similar to @Nick's answer, but his solution did not work for me.
First install socat by doing brew install socat
, and install XQuartz (https://www.xquartz.org/)
Then followed these steps here (http://fabiorehm.com/blog/2014/09/11/running-gui-apps-with-docker/) in the comments section:
1. in one mac terminal i started:
socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\"
2. and in another mac terminal I ran:
docker run -ti --rm \
-e DISPLAY=$(ipconfig getifaddr en0):0 \
-v /tmp/.X11-unix:/tmp/.X11-unix \
firefox
I was also able to launch CLion from my debian docker container too.
If you need "sub-10-character hash"
you could use Fletcher-32 algorithm which produces 8 character hash (32 bits), CRC-32 or Adler-32.
CRC-32 is slower than Adler32 by a factor of 20% - 100%.
Fletcher-32 is slightly more reliable than Adler-32. It has a lower computational cost than the Adler checksum: Fletcher vs Adler comparison.
A sample program with a few Fletcher implementations is given below:
#include <stdio.h>
#include <string.h>
#include <stdint.h> // for uint32_t
uint32_t fletcher32_1(const uint16_t *data, size_t len)
{
uint32_t c0, c1;
unsigned int i;
for (c0 = c1 = 0; len >= 360; len -= 360) {
for (i = 0; i < 360; ++i) {
c0 = c0 + *data++;
c1 = c1 + c0;
}
c0 = c0 % 65535;
c1 = c1 % 65535;
}
for (i = 0; i < len; ++i) {
c0 = c0 + *data++;
c1 = c1 + c0;
}
c0 = c0 % 65535;
c1 = c1 % 65535;
return (c1 << 16 | c0);
}
uint32_t fletcher32_2(const uint16_t *data, size_t l)
{
uint32_t sum1 = 0xffff, sum2 = 0xffff;
while (l) {
unsigned tlen = l > 359 ? 359 : l;
l -= tlen;
do {
sum2 += sum1 += *data++;
} while (--tlen);
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
}
/* Second reduction step to reduce sums to 16 bits */
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
return (sum2 << 16) | sum1;
}
int main()
{
char *str1 = "abcde";
char *str2 = "abcdef";
size_t len1 = (strlen(str1)+1) / 2; // '\0' will be used for padding
size_t len2 = (strlen(str2)+1) / 2; //
uint32_t f1 = fletcher32_1(str1, len1);
uint32_t f2 = fletcher32_2(str1, len1);
printf("%u %X \n", f1,f1);
printf("%u %X \n\n", f2,f2);
f1 = fletcher32_1(str2, len2);
f2 = fletcher32_2(str2, len2);
printf("%u %X \n",f1,f1);
printf("%u %X \n",f2,f2);
return 0;
}
Output:
4031760169 F04FC729
4031760169 F04FC729
1448095018 56502D2A
1448095018 56502D2A
Agrees with Test vectors:
"abcde" -> 4031760169 (0xF04FC729)
"abcdef" -> 1448095018 (0x56502D2A)
Adler-32 has a weakness for short messages with few hundred bytes, because the checksums for these messages have a poor coverage of the 32 available bits. Check this:
The Adler32 algorithm is not complex enough to compete with comparable checksums.
If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:
javascript:alert("hello world");
And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.
Did you see this - http://kb.discountasp.net/KB/a799/error-accessing-wcf-service-this-collection-already.aspx
You can resolve this error by changing the web.config file.
With ASP.NET 4.0, add the following lines to your web.config:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
With ASP.NET 2.0/3.0/3.5, add the following lines to your web.config:
<system.serviceModel>
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://www.YourHostedDomainName.com"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
I've seen Google toolbar's autocomplete feature disabled with javascript. It might work with some other autofill tools; I don't know if it'll help with browsers built in autocomplete.
<script type="text/javascript"><!--
if(window.attachEvent)
window.attachEvent("onload",setListeners);
function setListeners(){
inputList = document.getElementsByTagName("INPUT");
for(i=0;i<inputList.length;i++){
inputList[i].attachEvent("onpropertychange",restoreStyles);
inputList[i].style.backgroundColor = "";
}
selectList = document.getElementsByTagName("SELECT");
for(i=0;i<selectList.length;i++){
selectList[i].attachEvent("onpropertychange",restoreStyles);
selectList[i].style.backgroundColor = "";
}
}
function restoreStyles(){
if(event.srcElement.style.backgroundColor != "")
event.srcElement.style.backgroundColor = "";
}//-->
</script>
If you want to use regular expressions, then try:
ls -c | grep "^d" | wc -l
For those who don't want to go for Newtonsoft Json.Net or DataContractJsonSerializer
for some reason (I can't think of any :) ), here is an implementation of JavaScriptConverter
that supports DataContract
and enum
to string
conversion -
public class DataContractJavaScriptConverter : JavaScriptConverter
{
private static readonly List<Type> _supportedTypes = new List<Type>();
static DataContractJavaScriptConverter()
{
foreach (Type type in Assembly.GetExecutingAssembly().DefinedTypes)
{
if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
{
_supportedTypes.Add(type);
}
}
}
private bool ConvertEnumToString = false;
public DataContractJavaScriptConverter() : this(false)
{
}
public DataContractJavaScriptConverter(bool convertEnumToString)
{
ConvertEnumToString = convertEnumToString;
}
public override IEnumerable<Type> SupportedTypes
{
get { return _supportedTypes; }
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
{
try
{
object instance = Activator.CreateInstance(type);
IEnumerable<MemberInfo> members = ((IEnumerable<MemberInfo>)type.GetFields())
.Concat(type.GetProperties().Where(property => property.CanWrite && property.GetIndexParameters().Length == 0))
.Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
foreach (MemberInfo member in members)
{
DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
object value;
if (dictionary.TryGetValue(attribute.Name, out value) == false)
{
if (attribute.IsRequired)
{
throw new SerializationException(String.Format("Required DataMember with name {0} not found", attribute.Name));
}
continue;
}
if (member.MemberType == MemberTypes.Field)
{
FieldInfo field = (FieldInfo)member;
object fieldValue;
if (ConvertEnumToString && field.FieldType.IsEnum)
{
fieldValue = Enum.Parse(field.FieldType, value.ToString());
}
else
{
fieldValue = serializer.ConvertToType(value, field.FieldType);
}
field.SetValue(instance, fieldValue);
}
else if (member.MemberType == MemberTypes.Property)
{
PropertyInfo property = (PropertyInfo)member;
object propertyValue;
if (ConvertEnumToString && property.PropertyType.IsEnum)
{
propertyValue = Enum.Parse(property.PropertyType, value.ToString());
}
else
{
propertyValue = serializer.ConvertToType(value, property.PropertyType);
}
property.SetValue(instance, propertyValue);
}
}
return instance;
}
catch (Exception)
{
return null;
}
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
if (obj != null && Attribute.IsDefined(obj.GetType(), typeof(DataContractAttribute)))
{
Type type = obj.GetType();
IEnumerable<MemberInfo> members = ((IEnumerable<MemberInfo>)type.GetFields())
.Concat(type.GetProperties().Where(property => property.CanRead && property.GetIndexParameters().Length == 0))
.Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
foreach (MemberInfo member in members)
{
DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
object value;
if (member.MemberType == MemberTypes.Field)
{
FieldInfo field = (FieldInfo)member;
if (ConvertEnumToString && field.FieldType.IsEnum)
{
value = field.GetValue(obj).ToString();
}
else
{
value = field.GetValue(obj);
}
}
else if (member.MemberType == MemberTypes.Property)
{
PropertyInfo property = (PropertyInfo)member;
if (ConvertEnumToString && property.PropertyType.IsEnum)
{
value = property.GetValue(obj).ToString();
}
else
{
value = property.GetValue(obj);
}
}
else
{
continue;
}
if (dictionary.ContainsKey(attribute.Name))
{
throw new SerializationException(String.Format("More than one DataMember found with name {0}", attribute.Name));
}
dictionary[attribute.Name] = value;
}
}
return dictionary;
}
}
Note: This DataContractJavaScriptConverter
will only handle DataContract
classes defined in the assembly where it is placed. If you want classes from separate assemblies, modify the _supportedTypes
list accordingly in the static constructror.
This can be used as follows -
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new DataContractJavaScriptConverter(true) });
DataObject dataObject = serializer.Deserialize<DataObject>(JsonData);
The DataObject
class would look like this -
using System.Runtime.Serialization;
[DataContract]
public class DataObject
{
[DataMember(Name = "user_id")]
public int UserId { get; set; }
[DataMember(Name = "detail_level")]
public string DetailLevel { get; set; }
}
Please note that this solution doesn't handle EmitDefaultValue
and Order
properties supported by DataMember
attribute.
Another version which is simple
BiFunction<TreeSet<Employee>,List<Employee> ,TreeSet<Employee>> appendTree = (y,x) -> (y.addAll(x))? y:y;
TreeSet<Employee> outputList = appendTree.apply(new TreeSet<Employee>(Comparator.comparing(p->p.getId())),personList);
In my case i leave my .js file empty means i never write anything in my .js file after that i was using it in my route so make function component or class component and finally export it will work
Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.
(x + (x >> 31)) ^ (x >> 31);
This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.
You've got to override your Canvas's paint(Graphics g)
method and perform your drawing there. See the paint() documentation.
As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.
how to club the 4 query's as a single query
show below query
nsc = nature of case
report is taken on 06th of every month
( monthly report will be counted from 05th previous month to 05th present of present month)
In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:
C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"
You need to install typings for jasmine. Assuming you are on a relatively recent version of typescript 2 you should be able to do:
npm install --save-dev @types/jasmine
I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:
// Some global/configuration file that gets called in initialisation
global.MyError = [Function of MyError];
Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:
Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.
Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs). So it will be possible to write queries like this:
WITH RECURSIVE my_cte AS
(
SELECT 1 AS n
UNION ALL
SELECT 1+n FROM my_cte WHERE n<10
)
SELECT * FROM my_cte;
+------+
| n |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+------+
10 rows in set (0,00 sec)
in my case, I try tried File
>Invalidate Cache/Restart
and that works for me.
If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 'slow');
I ran into the same problem because I set the http_proxy and https_proxy environment variables. But occasionally, I connect to a different network and need to bypass the proxy temporarily. The easiest way to do this (without changing the environment variables) is:
curl --noproxy '*' stackoverflow.com
From the manual: "The only wildcard is a single * character, which matches all hosts, and effectively disables the proxy."
The * character is quoted so that it is not erroneously expanded by the shell.
TLDR - In addition to the previous responses. There might be a problem with the version of the fastboot
command. Try to download the newest one via Android SDK Manager instead of default one available in the OS repository.
There is one more thing you can do to fix this issue. I had the similar problem when trying to flash Nexus Player. All the adb commands we working fine while in normal boot mode. However, after switching to fastboot mode I wasn't able to execute fastboot commands. My device was not visible in the output of the fastboot devices
command. I've set the right rules in /etc/udev/rules.d/11-android.rules file. The lsusb
command showed that the device has been pluged in.
The soultion was quite simple. I've downloaded the the fastboot
via Android Studio's SDK Manager instead of using the default one available in Ubuntu packages.
All you need is sdkmanager. Download the Android SDK Platform Tools and replace the default /usr/bin/fastboot with the new one.
You can add any extension (in Wamp and Xampp servers) by removing the semi-colon (;)
Make it simple. Thanks
.bg {_x000D_
background-image: url('https://images.unsplash.com/photo-1476820865390-c52aeebb9891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80');_x000D_
background-repeat: no-repeat;_x000D_
background-size: cover;_x000D_
background-position: center;_x000D_
height: 100vh;_x000D_
width: 100vw;_x000D_
}
_x000D_
<div class="bg"></div>
_x000D_
The problem is not with the splitting but rather with the WriteLine
. A \n
in a string printed with WriteLine
will produce an "extra" line.
Example
var text =
"somet interesting text\n" +
"some text that should be in the same line\r\n" +
"some text should be in another line";
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
Console.WriteLine(s); //But will print 3 lines in total.
}
To fix the problem remove \n
before you print the string.
Console.WriteLine(s.Replace("\n", ""));
The name of the array indicates the starting address. Starting address of both namet2
and nameIt2
are different. So the equal to (==
) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp()
, or we can compare character by character using a loop.
The following command will (1) compare the file of the correct branch, to master (2) interactively ask you which modifications to apply.
git checkout --patch master
It is a static function on the MessageBox class, the simple way to do this is using
MessageBox.Show("my message");
in the System.Windows.Forms class. You can find more on the msdn page for this here . Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message"); or confirm("my question"); functions.
we can use
Math.pow(2, 4);
this mean 2 to the power 4 (2^4)
answer = 16
Because it was not posted yet and is a simple css fix:
#canvas {
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
}
Works great if you want to apply a fullscreen canvas background (for example with Granim.js).
Can't be done as it stands... The code
def myMethod(pParm1='1', pParm2='2'){
println "${pParm1}${pParm2}"
}
Basically makes groovy create the following methods:
Object myMethod( pParm1, pParm2 ) {
println "$pParm1$pParm2"
}
Object myMethod( pParm1 ) {
this.myMethod( pParm1, '2' )
}
Object myMethod() {
this.myMethod( '1', '2' )
}
One alternative would be to have an optional Map as the first param:
def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}
myMethod( 'a', 'b' ) // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd') // prints 'a b 1 2nd'
Obviously, documenting this so other people know what goes in the magical map
and what the defaults are is left to the reader ;-)
In my case (for OracleExpress) the service was running, but I got this issue when trying to access the database via sqlplus without connection identifier:
sqlplus sys/mypassword as sysdba
To make it work I needed to add the connection identifier (XE for Oracle Express), so following command worked ok:
sqlplus sys/mypassword@XE as sysdba
If you still get ORA-12560, make sure you can ping the XE service. Use:
tnsping XE
And you should get OK message along with full connection string (tnsping command is located in oracle's installation dir: [oracle express installation dir]\app\oracle\product\11.2.0\server\bin). If you can not ping make sure your tnsnames.ora
file is reachable for sqlplus. You might need to set TNS_ADMIN environment variable pointing to your ADMIN directory, where the file is located, for example:
TNS_ADMIN=[oracle express installation dir]\app\oracle\product\11.2.0\server\network\ADMIN
After finding this StackOverflow question/answer
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.
I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar
:
declare pos int; -- Keeping track of the next item's position
declare item varchar(100); -- A single item of the input
declare breaker int; -- Safeguard for while loop
-- The string must end with the delimiter
if right(inputString, 1) <> '|' then
set inputString = concat(inputString, '|');
end if;
DROP TABLE IF EXISTS MyTemporaryTable;
CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
set breaker = 0;
while (breaker < 2000) && (length(inputString) > 1) do
-- Iterate looking for the delimiter, add rows to temporary table.
set breaker = breaker + 1;
set pos = INSTR(inputString, '|');
set item = LEFT(inputString, pos - 1);
set inputString = substring(inputString, pos + 1);
insert into MyTemporaryTable values(item);
end while;
For example, input for this code could be the string Apple|Banana|Orange
. MyTemporaryTable
will be populated with three rows containing the strings Apple
, Banana
, and Orange
respectively.
I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).
Hope this helps somebody.
They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
Source: official documentation.
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
If someone is looking to sub out more than a comma I'm a fan of:
"1,200".chars.grep(/\d/).join.to_i
dunno about performance but, it is more flexible than a gsub
, ie:
"1-200".chars.grep(/\d/).join.to_i
You are supposed to edit two lines in your php.ini file (i'm using windows for this example):
-The first one is regarding the extensions directory location. See below:
; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "C:/php/ext"
-The second one is regarding the extension itself:
extension=php_mysqli.dll
Only modifying (uncommenting) the extension line was not enough for me. Hope it helps
If you want to take a component class as a parameter (vs an instance), use React.ComponentClass
:
function renderGreeting(Elem: React.ComponentClass<any>) {
return <span>Hello, <Elem />!</span>;
}
In HTML, the less-than sign is used at the beginning of tags.
if you use this bracket "<test1>
" in content, your bracket content will be unvisible, html renderer is assuming it as a html tag, changing chars with it's ASCI numbers prevents the issue.
with html friendly name:
<test1>
or with asci number:
<test1>
or comple asci:
<test1>
result: <test1>
asci referance: https://www.w3schools.com/charsets/ref_html_ascii.asp
The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern
df[0::len(df)-1 if len(df) > 1 else 1]
works even for single row-dataframes.
Example: For the following dataframe this will not create a duplicate:
df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1 else 1]
print df2
a b
0 1 a
whereas this does:
df3 = df.iloc[[0, -1]]
print df3
a b
0 1 a
0 1 a
because the single row is the first AND last row at the same time.
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
wstring outputMe = L"can" + L" concatenate\n";
OutputDebugString(outputMe.c_str());
I was working with Spring REST, and I solved it adding the AllowedMethods into the WebMvcConfigurer.
@Value( "${app.allow.origins}" )
private String allowOrigins;
@Bean
public WebMvcConfigurer corsConfigurer() {
System.out.println("allow origin: "+allowOrigins);
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//.allowedOrigins("http://localhost")
.allowedOrigins(allowOrigins)
.allowedMethods("PUT", "DELETE","GET", "POST");
}
};
}
For Windows users looking for solution of same problem. I just repleced
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
in my /conf/extra/http?-xampp.conf
Here is the query to get the records of the last month:
SELECT *
FROM `tablename`
WHERE `datefiled`
BETWEEN DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH )
AND
LAST_DAY( DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH ) )
Regards - saqib
You want to join on condition 1 AND condition 2, so simply use the AND keyword as below
ON a.userid = b.sourceid AND a.listid = b.destinationid;
refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.
<?php
$con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM employee");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
echo "<br />";
}
mysqli_close($con);
?>
You can similarly echo
it inside your table
<?php
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
}
echo "</table>";
mysqli_close($con);
?>
I was asked the same question in one of my interviews. My thoughts: Initialize the matrix with 0. Keep 3 arrays 1)sum_row (size n) 2) sum_column (size n) 3) diagonal (size 2)
For each move by (X) decrement the box value by 1 and for each move by (0) increment it by 1. At any point if the row/column/diagonal which has been modified in current move has sum either -3 or +3 means somebody has won the game. For a draw we can use above approach to keep the moveCount variable.
Do you think I am missing something ?
Edit: Same can be used for nxn matrix. Sum should be even +3 or -3.
Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
nodeA : pod1 => clusterIP1, pod2 => clusterIP2
nodeB : pod3 => clusterIP3.
pod3 can talk to pod1 via their clusterIP network.
nodeA => nodeIPA : nodeportX
nodeB => nodeIPB : nodeportX
you might access service on pod1 either via nodeIPA:nodeportX OR nodeIPB:nodeportX. Either way will work because kube-proxy (which is installed in each node) will receive your request and distribute it [redirect it(iptables term)] across nodes using clusterIP network.
basically just putting LB in front, so that inbound traffic is distributed to nodeIPA:nodeportX and nodeIPB:nodeportX then continue with the process flow number 2 above.
i tested this on apache2 on many different hosting and it works great.
use this htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
be sure you have enabled mod_rewirte
with a phpinfo();
then do this in config/config.php:
$config['index_url'] = '';
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
if it doesn't works yet, try to change the $config['uri_protocol']='AUTO'
to one of the listed inside application/config/config.php
file on line 40/54:
sometimes i used : REQUEST_URI
instead of AUTO
or "QUERY_STRING"
for goDaddy hostings
I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.
$params = '';
foreach ($foo) {
$index = 0;
$params[$index]['keyName'] = $name . '.' . $fileExt;
}
After changing:
$params = '';
to:
$params = array();
I stopped getting the error. I found the solution in this bug report thread. I hope this helps.
Got it to work by transitioning the padding as well as the width.
JSFiddle: http://jsfiddle.net/tuybk748/1/
<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
<div class="gray contents">These are the contents of this div</div>
</div>
.gray {
background: #ddd;
}
.contents-wrapper, .label, .contents {
display: inline-block;
}
.label, .contents {
overflow: hidden; /* must be on both divs to prevent dropdown behavior */
height: 20px;
}
.label {
padding: 10px 10px 15px;
}
.contents {
padding: 10px 0px 15px; /* no left-right padding at beginning */
white-space: nowrap; /* keeps text all on same line */
width: 0%;
-webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
-moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
-o-transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
transition: width 1s ease-in-out, padding-left 1s ease-in-out,
padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
width: 100%;
padding-left: 10px;
padding-right: 10px;
}
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL
SELECT STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM table
say for example use the below query to get output
SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table
For String format use the below link
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
$.ajax({_x000D_
url: URL,_x000D_
type: 'GET',_x000D_
dataType: 'json',_x000D_
headers: {_x000D_
'header1': 'value1',_x000D_
'header2': 'value2'_x000D_
},_x000D_
contentType: 'application/json; charset=utf-8',_x000D_
success: function (result) {_x000D_
// CallBack(result);_x000D_
},_x000D_
error: function (error) {_x000D_
_x000D_
}_x000D_
});
_x000D_
Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.
curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
http://example.com/service
Using the exact JSON data from the question, the full command line would become:
curl -H 'Content-Type: application/json' -X PUT \
-d '{"tags":["tag1","tag2"],
"question":"Which band?",
"answers":[{"id":"a0","answer":"Answer1"},
{"id":"a1","answer":"answer2"}]}' \
http://example.com/service
Note: JSON data wrapped only for readability, not valid for curl
request.
Getting only the "major" build #:
java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print $3}'
For a very fast and simple solution where you check equality against a single value, you can use the mask
method.
df.mask(df == ' ')
PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
If eclipse worries about an uncaught NameNotFoundException
, you can use:
PackageManager m = getPackageManager();
String s = getPackageName();
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
Log.w("yourtag", "Error Package name not found ", e);
}
Here is a function to convert UNICODE (ISO_8859_1) to UTF-8
public static String String_ISO_8859_1To_UTF_8(String strISO_8859_1) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strISO_8859_1.length(); i++) {
final char ch = strISO_8859_1.charAt(i);
if (ch <= 127)
{
stringBuilder.append(ch);
}
else
{
stringBuilder.append(String.format("%02x", (int)ch));
}
}
String s = stringBuilder.toString();
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
String strUTF_8 =new String(data, StandardCharsets.UTF_8);
return strUTF_8;
}
TEST
String strA_ISO_8859_1_i = new String("??????".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
System.out.println("ISO_8859_1 strA est = "+ strA_ISO_8859_1_i + "\n String_ISO_8859_1To_UTF_8 = " + String_ISO_8859_1To_UTF_8(strA_ISO_8859_1_i));
RESULT
ISO_8859_1 strA est = اÙغÙا٠String_ISO_8859_1To_UTF_8 = ??????
If Not temp_rst1 Is Nothing Then ...
Add
[config]="{backdrop: 'static'}"
to the model code.
In one line and probably faster then arr.indexOf(Math.max.apply(Math, arr))
:
var a = [0, 21, 22, 7];_x000D_
var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);_x000D_
_x000D_
document.write("indexOfMaxValue = " + indexOfMaxValue); // prints "indexOfMaxValue = 2"
_x000D_
Where:
iMax
- the best index so far (the index of the max element so far, on the first iteration iMax = 0
because the second argument to reduce()
is 0
, we can't omit the second argument to reduce()
in our case)x
- the currently tested element from the arrayi
- the currently tested indexarr
- our array ([0, 21, 22, 7]
)About the reduce()
method (from "JavaScript: The Definitive Guide" by David Flanagan):
reduce() takes two arguments. The first is the function that performs the reduction operation. The task of this reduction function is to somehow combine or reduce two values into a single value, and to return that reduced value.
Functions used with reduce() are different than the functions used with forEach() and map(). The familiar value, index, and array values are passed as the second, third, and fourth arguments. The first argument is the accumulated result of the reduction so far. On the first call to the function, this first argument is the initial value you passed as the second argument to reduce(). On subsequent calls, it is the value returned by the previous invocation of the function.
When you invoke reduce() with no initial value, it uses the first element of the array as the initial value. This means that the first call to the reduction function will have the first and second array elements as its first and second arguments.
For windows you can use:
Running Windows command prompt commands in python.
import os
os.system('tzutil /s "Central Standard Time"')
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s "Central America Standard Time"
For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
Here is all way to add your program to startup for Windows Vista, 7, 8, 10
- File path
C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
(Visible from task manager, Running on current user login success, No admin privileges required)
C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
(Visible from task manager, Running on all user login success, Admin privileges required)
- Registry path
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on current user login success, No admin privileges required)
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on current user login success, Running for one login time, No admin privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on all user login success, Admin privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on all user login success, Running for one login time, Admin privileges required)
- Task scheduler
Microsoft.Win32.Taskscheduler.dll
(Not visible from task manager, Running on windows boot, Running as admin, Admin privileges required)
Updated for Swift 3
I came here just wanting to dismiss the current (presented) View Controller. I'm making this answer for anyone coming here with the same purpose.
If you are using a navigation controller, then it is quite easy.
Go back to the previous view controller:
// Swift
self.navigationController?.popViewController(animated: true)
// Objective-C
[self.navigationController popViewControllerAnimated:YES];
Go back to the root view controller:
// Swift
self.navigationController?.popToRootViewController(animated: true)
// Objective-C
[self.navigationController popToRootViewControllerAnimated:YES];
(Thanks to this answer for the Objective-C.)
When a View Controller is presented modally, you can dismiss it (from the second view controller) by calling
// Swift
self.dismiss(animated: true, completion: nil)
// Objective-C
[self dismissViewControllerAnimated:YES completion:nil];
The documentation says,
The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.
So it works for the presented view controller to call it on itself. Here is a full example.
The OP's question was about the complexity of using delegates to dismiss a view.
To this point I have not needed to use delegates since I usually have a navigation controller or modal view controllers, but if I do need to use the delegate pattern in the future, I will add an update.
Do
setTimeout(
function() {
this.setState({ position: 1 });
}
.bind(this),
3000
);
Otherwise, you are passing the result of setState
to setTimeout
.
You can also use ES6 arrow functions to avoid the use of this
keyword:
setTimeout(
() => this.setState({ position: 1 }),
3000
);
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.timezone,data.datetime,data.dst));
_x000D_
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
no need to require the ckeditor.php, because CKEditor will not processed by PHP...
you need just following the _samples directory and see what they do.
just need to include ckeditor.js by html tag, and do some configuration in javascript.
NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow
<input id="txtDay" type="text" placeholder="DD" />
<input id="txtMonth" type="text" placeholder="MM" />
<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>
function validateDate() {
var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);
if (date == "Invalid Date") {
alert("jnvalid date");
}
}
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");
I think you are looking for this function:
http://doc.qt.io/qt-5/qdatetime.html#toTime_t
uint QDateTime::toTime_t () const
Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).
On systems that do not support time zones, this function will behave as if local time were Qt::UTC.
See also setTime_t().
I want to expand on Todd R's point in the OP. In asp.net pages, the web.config
file defines permissions needed to access each file or folder in the application. In our case, the folder of CSS files did not allow access for unauthorized users, causing it to fail on the login page before the user was authorized. Changing the required permissions in web.config
allowed unauthorized users to access the CSS files and solved this problem.
Maybe a very rare scenario but I can't add a comment so leaving this here in case it helps someone: I had a similar issue dealing with someone else's code, modal wasn't displaying when I added ".fade" class, issue was some CSS for .modal-backdrop:
.modal-backdrop {display: none;}
After removing that, modal shows up fine.
Add the item first and then serialize:
$.ajax({
type: 'POST',
url: this.action,
data: $.extend($(this), {'NonFormValue': NonFormValue}).serialize()
});
Another option is:
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
You can do it with CSS:
<iframe style="position: absolute; height: 100%; border: none"></iframe>
Be aware that this will by default place it in the upper-left corner of the page, but I guess that is what you want to achieve. You can position with the left
,right
, top
and bottom
CSS properties.
public static double addDoubles(double a, double b) {
BigDecimal A = new BigDecimal(a + "");
BigDecimal B = new BigDecimal(b + "");
return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
Big O is a measure of how much time/space an algorithm uses relative to the size of its input.
If an algorithm is O(n) then the time/space will increase at the same rate as its input.
If an algorithm is O(n2) then the time/space increase at the rate of its input squared.
and so on.
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
In my case, restarting SQL Server Service was enough to resolve the issue.
Using Encoding.Unicode won't accurately decode an ANSI file in the same way that a JPEG decoder won't understand a GIF file.
I'm surprised that Encoding.Default
didn't work for the ANSI file if it really was ANSI - if you ever find out exactly which code page Notepad was using, you could use Encoding.GetEncoding(int)
.
In general, where possible I'd recommend using UTF-8.
I wrote serialijse because I faced the same problem as you.
you can find it at https://github.com/erossignon/serialijse
It can be used in nodejs or in a browser and can serve to serialize and deserialize a complex set of objects from one context (nodejs) to the other (browser) or vice-versa.
var s = require("serialijse");
var assert = require("assert");
// testing serialization of a simple javascript object with date
function testing_javascript_serialization_object_with_date() {
var o = {
date: new Date(),
name: "foo"
};
console.log(o.name, o.date.toISOString());
// JSON will fail as JSON doesn't preserve dates
try {
var jstr = JSON.stringify(o);
var jo = JSON.parse(jstr);
console.log(jo.name, jo.date.toISOString());
} catch (err) {
console.log(" JSON has failed to preserve Date during stringify/parse ");
console.log(" and has generated the following error message", err.message);
}
console.log("");
var str = s.serialize(o);
var so = s.deserialize(str);
console.log(" However Serialijse knows how to preserve date during serialization/deserialization :");
console.log(so.name, so.date.toISOString());
console.log("");
}
testing_javascript_serialization_object_with_date();
// serializing a instance of a class
function testing_javascript_serialization_instance_of_a_class() {
function Person() {
this.firstName = "Joe";
this.lastName = "Doe";
this.age = 42;
}
Person.prototype.fullName = function () {
return this.firstName + " " + this.lastName;
};
// testing serialization using JSON.stringify/JSON.parse
var o = new Person();
console.log(o.fullName(), " age=", o.age);
try {
var jstr = JSON.stringify(o);
var jo = JSON.parse(jstr);
console.log(jo.fullName(), " age=", jo.age);
} catch (err) {
console.log(" JSON has failed to preserve the object class ");
console.log(" and has generated the following error message", err.message);
}
console.log("");
// now testing serialization using serialijse serialize/deserialize
s.declarePersistable(Person);
var str = s.serialize(o);
var so = s.deserialize(str);
console.log(" However Serialijse knows how to preserve object classes serialization/deserialization :");
console.log(so.fullName(), " age=", so.age);
}
testing_javascript_serialization_instance_of_a_class();
// serializing an object with cyclic dependencies
function testing_javascript_serialization_objects_with_cyclic_dependencies() {
var Mary = { name: "Mary", friends: [] };
var Bob = { name: "Bob", friends: [] };
Mary.friends.push(Bob);
Bob.friends.push(Mary);
var group = [ Mary, Bob];
console.log(group);
// testing serialization using JSON.stringify/JSON.parse
try {
var jstr = JSON.stringify(group);
var jo = JSON.parse(jstr);
console.log(jo);
} catch (err) {
console.log(" JSON has failed to manage object with cyclic deps");
console.log(" and has generated the following error message", err.message);
}
// now testing serialization using serialijse serialize/deserialize
var str = s.serialize(group);
var so = s.deserialize(str);
console.log(" However Serialijse knows to manage object with cyclic deps !");
console.log(so);
assert(so[0].friends[0] == so[1]); // Mary's friend is Bob
}
testing_javascript_serialization_objects_with_cyclic_dependencies();
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
You can use a JS and SCSS/Fontawesome combination for the Prev/Next buttons.
In your JS (this includes screenreader only/accessibility classes with Zurb Foundation):
$('.whatever-carousel').owlCarousel({
... ...
navText: ["<span class='show-for-sr'>Previous</span>","<span class='show-for-sr'>Next</span>"]
... ...
})
In your SCSS this:
.owl-theme {
.owl-nav {
.owl-prev,
.owl-next {
font-family: FontAwesome;
//border-radius: 50%;
//padding: whatever-to-get-a-circle;
transition: all, .2s, ease;
}
.owl-prev {
&::before {
content: "\f104";
}
}
.owl-next {
&::before {
content: "\f105";
}
}
}
}
For the FontAwesome font-family I happen to use the embed code in the document header:
<script src="//use.fontawesome.com/123456whatever.js"></script>
There are various ways to include FA, strokes/folks, but I find this is pretty fast and as I'm using webpack I can just about live with that 1 extra js server call.
And to update this - there's also this JS option for slightly more complex arrows, still with accessibility in mind:
$('.whatever-carousel').owlCarousel({
navText: ["<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Previous</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-left fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>","<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Next</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-right fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>"]
})
Loads of escaping there, use single quotes instead if preferred.
And in the SCSS just comment out the ::before attrs:
.owl-prev {
//&::before { content: "\f104"; }
}
.owl-next {
//&::before { content: "\f105"; }
}
Yes, that is the definition of raw pointer equality: they both point to the same location (or are pointer aliases); usually in the virtual address space of the process running your application coded in C++ and managed by some operating system (but C++ can also be used for programming embedded devices with micro-controllers having a Harward architecture: on such microcontrollers some pointer casts are forbidden and makes no sense - since read only data could sit in code ROM)
For C++, read a good C++ programming book, see this C++ reference website, read the documentation of your C++ compiler (perhaps GCC or Clang) and consider coding with smart pointers. Maybe read also some draft C++ standard, like n4713 or buy the official standard from your ISO representative.
The concepts and terminology of garbage collection are also relevant when managing pointers and memory zones obtained by dynamic allocation (e.g. ::operator new
), so read perhaps the GC handbook.
For pointers on Linux machines, see also this.
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
As of July, 2020 the following dependencies in pom.xml worked for me:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.1</version>
</dependency>
With this 4.13 junit library and hamcrest, it uses hamcrest.MatcherAssert when asserting and throws exception- enter image description here
Very easy, this is how I did it.
.directive('blockOnRender', function ($blockUI) {_x000D_
return {_x000D_
restrict: 'A',_x000D_
link: function (scope, element, attrs) {_x000D_
_x000D_
if (scope.$first) {_x000D_
$blockUI.blockElement($(element).parent());_x000D_
}_x000D_
if (scope.$last) {_x000D_
$blockUI.unblockElement($(element).parent());_x000D_
}_x000D_
}_x000D_
};_x000D_
})
_x000D_
One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource
and supply it with StringReader
.
String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());
redirect 301 /contact.php /contact-us.php
There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally
You Can Try this
import ftplib
path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/'
filename = 'L28POC_B.xpt'
ftp = ftplib.FTP("Server IP")
ftp.login("UserName", "Password")
ftp.cwd(path)
ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
ftp.quit()
There's a very basic reason: Constructors are effectively static functions, and in C++ no static function can be virtual.
If you have much experience with C++, you know all about the difference between static & member functions. Static functions are associated with the CLASS, not the objects (instances), so they don't see a "this" pointer. Only member functions can be virtual, because the vtable- the hidden table of function pointers that makes 'virtual' work- is really a data member of each object.
Now, what is the constructor's job? It is in the name- a "T" constructor initializes T objects as they're allocated. This automatically precludes it being a member function! An object has to EXIST before it has a "this" pointer and thus a vtable. That means that even if the language treated constructors as ordinary functions (it doesn't, for related reasons I won't get into), they'd have to be static member functions.
A great way to see this is to look at the "Factory" pattern, especially factory functions. They do what you're after, and you'll notice that if class T has a factory method, it is ALWAYS STATIC. It has to be.
Python standard library solution
This generator-function takes an iterable and a window size N
and yields the average over the current values inside the window. It uses a deque
, which is a datastructure similar to a list, but optimized for fast modifications (pop
, append
) at both endpoints.
from collections import deque
from itertools import islice
def sliding_avg(iterable, N):
it = iter(iterable)
window = deque(islice(it, N))
num_vals = len(window)
if num_vals < N:
msg = 'window size {} exceeds total number of values {}'
raise ValueError(msg.format(N, num_vals))
N = float(N) # force floating point division if using Python 2
s = sum(window)
while True:
yield s/N
try:
nxt = next(it)
except StopIteration:
break
s = s - window.popleft() + nxt
window.append(nxt)
Here is the function in action:
>>> values = range(100)
>>> N = 5
>>> window_avg = sliding_avg(values, N)
>>>
>>> next(window_avg) # (0 + 1 + 2 + 3 + 4)/5
>>> 2.0
>>> next(window_avg) # (1 + 2 + 3 + 4 + 5)/5
>>> 3.0
>>> next(window_avg) # (2 + 3 + 4 + 5 + 6)/5
>>> 4.0
HttpWebRequest is used for this.
On postback, create a HttpWebRequest to your third party and post the form data, then once that is done, you can Response.Redirect wherever you want.
You get the added advantage that you don't have to name all of your server controls to make the 3rd parties form, you can do this translation when building the POST string.
string url = "3rd Party Url";
StringBuilder postData = new StringBuilder();
postData.Append("first_name=" + HttpUtility.UrlEncode(txtFirstName.Text) + "&");
postData.Append("last_name=" + HttpUtility.UrlEncode(txtLastName.Text));
//ETC for all Form Elements
// Now to Send Data.
StreamWriter writer = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.ToString().Length;
try
{
writer = new StreamWriter(request.GetRequestStream());
writer.Write(postData.ToString());
}
finally
{
if (writer != null)
writer.Close();
}
Response.Redirect("NewPage");
However, if you need the user to see the response page from this form, your only option is to utilize Server.Transfer, and that may or may not work.
This method should completely avoid activities below the grey area retrieving click events.
Remove this line if you have it:
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
Put this on your activity created
getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
then override the touch event with this
@Override
public boolean onTouchEvent(MotionEvent ev)
{
if(MotionEvent.ACTION_DOWN == ev.getAction())
{
Rect dialogBounds = new Rect();
getWindow().getDecorView().getHitRect(dialogBounds);
if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
// You have clicked the grey area
displayYourDialog();
return false; // stop activity closing
}
}
// Touch events inside are fine.
return super.onTouchEvent(ev);
}
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
If you want to copy the current dir's contents, you can run:
docker build -t <imagename:tag> -f- ./ < Dockerfile
You could reference controls inside the master page this way:
void Page_Load()
{
ContentPlaceHolder cph;
Literal lit;
cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if (cph != null) {
lit = (Literal) cph.FindControl("Literal1");
if (lit != null) {
lit.Text = "Some <b>HTML</b>";
}
}
}
In this example you have to put a Literal control in your ContentPlaceholder.
Angularjs already has filter option to do this , https://docs.angularjs.org/api/ng/filter/filter
If you use the php Datetime class you could use:
function time_ago(Datetime $date) {
$time_ago = '';
$diff = $date->diff(new Datetime('now'));
if (($t = $diff->format("%m")) > 0)
$time_ago = $t . ' months';
else if (($t = $diff->format("%d")) > 0)
$time_ago = $t . ' days';
else if (($t = $diff->format("%H")) > 0)
$time_ago = $t . ' hours';
else
$time_ago = 'minutes';
return $time_ago . ' ago (' . $date->format('M j, Y') . ')';
}
Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length
returns undefined rather than 5.
This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:
Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused
& I resolved it following way.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://hostname:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
I solved this problem :
> Preferences –> Browse Packages –> Default
Open the exec.py
file, near line 41-42, the code should look like this :
for k, v in proc_env.iteritems():
proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
then delete it or edit it as :
try:
for k, v in proc_env.iteritems():
proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
except:
print 'foobar'
You don't need any date-specific functions for this, it's just string manipulation:
var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);
$('#submit_button').click(function() {
if (!$("input[@name='name']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the radio buttons is checked!');
}
});
Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put name=
on the last argument of the url
(or path
in Django 2.0+) function call.
For instance, the following functions throw the error from the question:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')
But these actually work:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')
The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs
, and since a string is an iterable, an atypical code path begins to unfold. Always use name=
on your urls!
Big screen:
Small screen (Mobile)
if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview
CSS + HTML + JQUERY :
_x000D_
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
body {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
background: #fafafa;_x000D_
}_x000D_
_x000D_
p {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
font-size: 1.1em;_x000D_
font-weight: 300;_x000D_
line-height: 1.7em;_x000D_
color: #999;_x000D_
}_x000D_
_x000D_
a,_x000D_
a:hover,_x000D_
a:focus {_x000D_
color: inherit;_x000D_
text-decoration: none;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
.navbar {_x000D_
padding: 15px 10px;_x000D_
background: #fff;_x000D_
border: none;_x000D_
border-radius: 0;_x000D_
margin-bottom: 40px;_x000D_
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
}_x000D_
_x000D_
.navbar-btn {_x000D_
box-shadow: none;_x000D_
outline: none !important;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.line {_x000D_
width: 100%;_x000D_
height: 1px;_x000D_
border-bottom: 1px dashed #ddd;_x000D_
margin: 40px 0;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#sidebar {_x000D_
width: 250px;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100vh;_x000D_
z-index: 999;_x000D_
background: #7386D5;_x000D_
color: #fff !important;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
#sidebar.active {_x000D_
margin-left: -250px;_x000D_
}_x000D_
_x000D_
#sidebar .sidebar-header {_x000D_
padding: 20px;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
#sidebar ul.components {_x000D_
padding: 20px 0;_x000D_
border-bottom: 1px solid #47748b;_x000D_
}_x000D_
_x000D_
#sidebar ul p {_x000D_
color: #fff;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#sidebar ul li a {_x000D_
padding: 10px;_x000D_
font-size: 1.1em;_x000D_
display: block;_x000D_
color:white;_x000D_
}_x000D_
_x000D_
#sidebar ul li a:hover {_x000D_
color: #7386D5;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
#sidebar ul li.active>a,_x000D_
a[aria-expanded="true"] {_x000D_
color: #fff;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
a[data-toggle="collapse"] {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
a[aria-expanded="false"]::before,_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e259';_x000D_
display: block;_x000D_
position: absolute;_x000D_
right: 20px;_x000D_
font-family: 'Glyphicons Halflings';_x000D_
font-size: 0.6em;_x000D_
}_x000D_
_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e260';_x000D_
}_x000D_
_x000D_
ul ul a {_x000D_
font-size: 0.9em !important;_x000D_
padding-left: 30px !important;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
ul.CTAs {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
ul.CTAs a {_x000D_
text-align: center;_x000D_
font-size: 0.9em !important;_x000D_
display: block;_x000D_
border-radius: 5px;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
a.download {_x000D_
background: #fff;_x000D_
color: #7386D5;_x000D_
}_x000D_
_x000D_
a.article,_x000D_
a.article:hover {_x000D_
background: #6d7fcc !important;_x000D_
color: #fff !important;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#content {_x000D_
width: calc(100% - 250px);_x000D_
padding: 40px;_x000D_
min-height: 100vh;_x000D_
transition: all 0.3s;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
#content.active {_x000D_
width: 100%;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
_x000D_
@media (max-width: 768px) {_x000D_
#sidebar {_x000D_
margin-left: -250px;_x000D_
}_x000D_
#sidebar.active {_x000D_
margin-left: 0;_x000D_
}_x000D_
#content {_x000D_
width: 100%;_x000D_
}_x000D_
#content.active {_x000D_
width: calc(100% - 250px);_x000D_
}_x000D_
#sidebarCollapse span {_x000D_
display: none;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
<title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
<!-- Bootstrap CSS CDN -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<!-- Our Custom CSS -->_x000D_
<link rel="stylesheet" href="style2.css">_x000D_
<!-- Scrollbar Custom CSS -->_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<div class="wrapper">_x000D_
<!-- Sidebar Holder -->_x000D_
<nav id="sidebar">_x000D_
<div class="sidebar-header">_x000D_
<h3>Header as you want </h3>_x000D_
</h3>_x000D_
</div>_x000D_
_x000D_
<ul class="list-unstyled components">_x000D_
<p>Dummy Heading</p>_x000D_
<li class="active">_x000D_
<a href="#menu">Animación</a>_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Interacción</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Blog</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Acerca</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">contacto</a>_x000D_
</li>_x000D_
_x000D_
_x000D_
</ul>_x000D_
_x000D_
_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content Holder -->_x000D_
<div id="content">_x000D_
_x000D_
<nav class="navbar navbar-default">_x000D_
<div class="container-fluid">_x000D_
_x000D_
<div class="navbar-header">_x000D_
<button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
<i class="glyphicon glyphicon-align-left"></i>_x000D_
<span>Toggle Sidebar</span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#">Page</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<!-- jQuery CDN -->_x000D_
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
<!-- Bootstrap Js CDN -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<!-- jQuery Custom Scroller CDN -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
_x000D_
_x000D_
$('#sidebarCollapse').on('click', function() {_x000D_
$('#sidebar, #content').toggleClass('active');_x000D_
$('.collapse.in').toggleClass('in');_x000D_
$('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
if this is what you want .
I tried the following ways in first jQuery, then JavaScript:
jQuery:
window.location.href = $(".contact").attr('href');
$('.contactformone').trigger('click');
This is the best way in JavaScript:
document.getElementById("id").click();
Here is all you need:
curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers
Z-index is not an absolute measurement. It is possible for an element with z-index: 1000 to be behind an element with z-index: 1 - as long as the respective elements belong to different stacking contexts.
When you specify z-index, you're specifying it relative to other elements in the same stacking context, and although the CSS spec's paragraph on Z-index says a new stacking context is only created for positioned content with a z-index other than auto (meaning your entire document should be a single stacking context), you did construct a positioned span: unfortunately IE7 interprets positioned content without z-index this as a new stacking context.
In short, try adding this CSS:
#envelope-1 {position:relative; z-index:1;}
or redesign the document such that your spans don't have position:relative any longer:
<html>
<head>
<title>Z-Index IE7 Test</title>
<style type="text/css">
ul {
background-color: #f00;
z-index: 1000;
position: absolute;
width: 150px;
}
</style>
</head>
<body>
<div>
<label>Input #1:</label> <input><br>
<ul><li>item<li>item<li>item<li>item</ul>
</div>
<div>
<label>Input #2:</label> <input>
</div>
</body>
</html>
See http://www.brenelz.com/blog/2009/02/03/squish-the-internet-explorer-z-index-bug/ for a similar example of this bug. The reason giving a parent element (envelope-1 in your example) a higher z-index works is because then all children of envelope-1 (including the menu) will overlap all siblings of envelope-1 (specifically, envelope-2).
Although z-index lets you explicitly define how things overlap, even without z-index the layering order is well defined. Finally, IE6 has an additional bug that causes selectboxes and iframes to float on top of everything else.
In .NET Core (any version), you can use ImmutableList, which has all the functionality of List<T>
.
This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:
select *
from issues
where issueid not in (
select top (
(select count(*) from issues) - 5
) issueid
from issues
)
Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.
And the more complex query if you need to search in a several groups:
(&(objectCategory=user)(|(memberOf=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))
The same example with recursion:
(&(objectCategory=user)(|(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))
If you don't want to bother with weird expansions from bash you can do this
me$ FOO="BAR \x2A BAR" # 2A is hex code for *
me$ echo -e $FOO
BAR * BAR
me$
Explanation here why using -e option of echo makes life easier:
Relevant quote from man here:
SYNOPSIS
echo [SHORT-OPTION]... [STRING]...
echo LONG-OPTION
DESCRIPTION
Echo the STRING(s) to standard output.
-n do not output the trailing newline
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes (default)
--help display this help and exit
--version
output version information and exit
If -e is in effect, the following sequences are recognized:
\\ backslash
...
\0NNN byte with octal value NNN (1 to 3 digits)
\xHH byte with hexadecimal value HH (1 to 2 digits)
For the hex code you can check man ascii page (first line in octal, second decimal, third hex):
051 41 29 ) 151 105 69 i
052 42 2A * 152 106 6A j
053 43 2B + 153 107 6B k
Simply, row_num = df.shape[0] # gives number of rows, here's the example:
import pandas as pd
import numpy as np
In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])
In [323]: df
Out[323]:
col_1 col_2
0 -0.894268 1.309041
1 -0.120667 -0.241292
2 0.076168 -1.071099
3 1.387217 0.622877
4 -0.488452 0.317882
In [324]: df.shape
Out[324]: (5, 2)
In [325]: df.shape[0] ## Gives no. of rows/records
Out[325]: 5
In [326]: df.shape[1] ## Gives no. of columns
Out[326]: 2
mcc -?
explains that the syntax to make *.exe (Standalone Application) with *.m is:
mcc -m <matlabFile.m>
For example:
mcc -m file.m
will create file.exe in the curent directory.
The problem is that there is an in-browser print dialogue within the popup window. If you call window.close()
immediately then the dialogue is not seen by the user. The user needs to click "Print" within the dialogue. This is not the same as on other browsers where the print dialogue is part of the OS, and blocks the window.close()
until dismissed - on Chrome, it's part of Chrome, not the OS.
This is the code I used, in a little popup window that is created by the parent window:
var is_chrome = function () { return Boolean(window.chrome); }
window.onload = function() {
if(is_chrome){
/*
* These 2 lines are here because as usual, for other browsers,
* the window is a tiny 100x100 box that the user will barely see.
* On Chrome, it needs to be big enough for the dialogue to be read
* (NB, it also includes a page preview).
*/
window.moveTo(0,0);
window.resizeTo(640, 480);
// This line causes the print dialogue to appear, as usual:
window.print();
/*
* This setTimeout isn't fired until after .print() has finished
* or the dialogue is closed/cancelled.
* It doesn't need to be a big pause, 500ms seems OK.
*/
setTimeout(function(){
window.close();
}, 500);
} else {
// For other browsers we can do things more briefly:
window.print();
window.close();
}
}
Here goes a straightforward example:
# Do something, or tell me why it failed
my_update_function <- function(x){
tryCatch(
# This is what I want to do...
{
y = x * 2
return(y)
},
# ... but if an error occurs, tell me what happened:
error=function(error_message) {
message("This is my custom message.")
message("And below is the error message from R:")
message(error_message)
return(NA)
}
)
}
If you also want to capture a "warning", just add warning=
similar to the error=
part.
This answer by Martin R seems to be correct because it accounts for Unicode.
However at the time of the post (Swift 1) his code doesn't compile in Swift 2.0 (Xcode 7), because they removed advance()
function. Updated version is below:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
if let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
return Range(nsRange, in: self)
}
}
Besides the solution of using an additional list and calling addAll to insert the new items after the iteration (as e.g. the solution by user Nat), you can also use concurrent collections like the CopyOnWriteArrayList.
The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.
With this special collection (usually used for concurrent access) it is possible to manipulate the underlying list while iterating over it. However, the iterator will not reflect the changes.
Is this better than the other solution? Probably not, I don't know the overhead introduced by the Copy-On-Write approach.
I'm using Ookii dialogs for a while and it work nice for WPF.
Here's the direct page:
I made a function which handles arrays as well as single GET or POST values
function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode
$retVal = "";
$retArray = array();
if($isArray) {
if(isset($_POST[$varName])) {
foreach ( $_POST[$varName] as $var ) { // multidimensional POST array elements
$retArray[]=$var;
}
}
$retVal=$retArray;
}
elseif (isset($_POST[$varName]) ) { // simple POST array element
$retVal = $_POST[$varName];
}
else {
if (isset($_GET[$varName]) ) {
$retVal = $_GET[$varName]; // simple GET array element
}
else {
$retVal = $default;
}
}
return $retVal;
}
Examples:
$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");
To install Docker for Mac with homebrew:
brew cask install docker
To install the command line completion:
brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion
Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:
update
MasterTbl
set
TotalX = Sum(DetailTbl.X),
TotalY = Sum(DetailTbl.Y),
TotalZ = Sum(DetailTbl.Z)
from
DetailTbl
where
DetailTbl.MasterID = MasterID
Working for all api version (tested on Android 10)
val returnCursor: Cursor? = context.contentResolver.query(uri, null, null, null, null)
val columnIndex = returnCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
returnCursor.moveToFirst();
val path = returnCursor.getString(columnIndex)
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
$@
is all of the parameters passed to the script.
For instance, if you call ./someScript.sh foo bar
then $@
will be equal to foo bar
.
If you do:
./someScript.sh foo bar
and then inside someScript.sh
reference:
umbrella_corp_options "$@"
this will be passed to umbrella_corp_options
with each individual parameter enclosed in double quotes, allowing to take parameters with blank space from the caller and pass them on.
Another reason for "lost update" can be the next:
If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this
static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}
Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)
This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:
install webpack-dev-server
npm i -g webpack-dev-server
start webpack-dev-server with https
webpack-dev-server --https
I too had the same problem.
The solution for me was to add following in the pom.xml as suggested here.
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
WARNING: This will remove the database
Use command:
rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8
Rubygems >= 2.1.0
gem uninstall -aIx
If Terminal returns below error
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.
Then write above command as below
sudo gem uninstall -aIx
And enter your mac os account password Done!!
You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.
enter = datetime.time(hour=1) # Example enter time
exit = datetime.time(hour=2) # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta
difference_delta is your difference which you can use for your reasons.
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.
If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.
On this web page, I see that:
"Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash."
So I guess the escaping of it is unnecessary...
Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development.
The Error Log
. It contains information about errors that occur while
the server is running (also server start and stop)
The General Query Log
. This is a general record of what mysqld is
doing (connect, disconnect, queries)
The Slow Query Log
. ?t consists of "slow" SQL statements (as
indicated by its name).
By default no log files are enabled in MYSQL. All errors will be shown in the syslog (/var/log/syslog
).
To Enable them just follow below steps:
step1: Go to this file (/etc/mysql/conf.d/mysqld_safe_syslog.cnf) and remove or comment those line.
step2: Go to mysql conf file (/etc/mysql/my.cnf
) and add following lines
To enable error log add following
[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log
[mysqld]
log_error=/var/log/mysql/mysql_error.log
To enable general query log add following
general_log_file = /var/log/mysql/mysql.log
general_log = 1
To enable Slow Query Log add following
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes
step3: save the file and restart mysql using following commands
service mysql restart
To enable logs at runtime, login to mysql client (mysql -u root -p
) and give:
SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
Finally one thing I would like to mention here is I read this from a blog. Thanks. It works for me.
Click here to visit the blog
I had the following problem where I was fetching data from a database and wanted to display a string containing \n
. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208
figure (1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig, 'Position', [0 0 xwidth ywidth])
plot(x,y)
print -depsc2 correlation.eps; % for saving in eps, look up options for saving as png or other formats you may need
This saves the figure in the dimensions specified
I could not get the keypress
event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup
or keydown
event to catch a press of the enter button.
You can try
angular.element('#<elementId>').focus();
for eg.
angular.element('#txtUserId').focus();
its working for me.
There is an issue with downloading npm dependencies due to network which you have. try to download the npm dependencies in open network . you won't get any issue. i am also faced this similar issue and resolved finally.
use below commands: npm install (it will download all depedencies) npm start to start the angular application
padding-right works for me in Firefox/Chrome on Windows but not in IE. Welcome to the wonderful world of IE standards non-compliance.
See: http://jsfiddle.net/SfPju/466/
HTML
<input type="text" class="foo" value="abcdefghijklmnopqrstuvwxyz"/>
CSS
.foo
{
padding-right: 20px;
}
For all the Swift lovers out there, here is the answer by @Travis translated into SWIFT:
Do what @Travis explained before the Objective C code. Then,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController
self.window?.rootViewController = exampleViewController
self.window?.makeKeyAndVisible()
return true
}
The ExampleViewController
would be the new initial view controller you would like to show.
The steps explained:
Enjoy and happy programming!
Timestamptz vs Timestamp
The timestamptz field in Postgres is basically just the timestamp field where Postgres actually just stores the “normalised” UTC time, even if the timestamp given in the input string has a timezone.
If your input string is: 2018-08-28T12:30:00+05:30 , when this timestamp is stored in the database, it will be stored as 2018-08-28T07:00:00.
The advantage of this over the simple timestamp field is that your input to the database will be timezone independent, and will not be inaccurate when apps from different timezones insert timestamps, or when you move your database server location to a different timezone.
To quote from the docs:
For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system’s TimeZone parameter, and is converted to UTC using the offset for the timezone zone. To give a simple analogy, a timestamptz value represents an instant in time, the same instant for anyone viewing it. But a timestamp value just represents a particular orientation of a clock, which will represent different instances of time based on your timezone.
For pretty much any use case, timestamptz is almost always a better choice. This choice is made easier with the fact that both timestamptz and timestamp take up the same 8 bytes of data.
source: https://hasura.io/blog/postgres-date-time-data-types-on-graphql-fd926e86ee87/
I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.
Use VideoView.
Natively ImageView does not support animated image. You have two options to show animated gif file
VideoView
ImageView
and Split the gif file into several parts and then apply animation to itThe code
comboBox1.SelectedItem = MyEnum.Something;
is ok, the problem must reside in the DataBinding. DataBinding assignments occur after the constructor, mainly the first time the combobox is shown. Try to set the value in the Load event. For example, add this code:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
comboBox1.SelectedItem = MyEnum.Something;
}
And check if it works.
You can also extend FloatingPoint in Swift 3 as follow:
extension FloatingPoint {
func rounded(to n: Int) -> Self {
let n = Self(n)
return (self / n).rounded() * n
}
}
324.0.rounded(to: 5) // 325
To sum up the other answers...
This works on all Java versions:
"cat".split("(?!^)")
This only works on Java 8 and up:
"cat".split("")
Make sure your element with the .date-picker
class does NOT already have a hasDatepicker
class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker();
will fail! Instead you need to do...
$myDatepicker.removeClass('hasDatepicker').datepicker();
You should type into the command line
git add --all
This will commit all untracked files
Edit:
After staging your files they are ready for commit so your next command should be
git commit -am "Your commit message"
While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:
/*
* Check a folder if changed in the latest commit.
* Returns true if changed, or false if no changes.
*/
def checkFolderForDiffs(path) {
try {
// git diff will return 1 for changes (failure) which is caught in catch, or
// 0 meaning no changes
sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
return false
} catch (err) {
return true
}
}
if ( checkFolderForDiffs('api/') ) {
//API folder changed, run steps here
}
Instead of returning a resultsArray
you return a promise for a results array and then then
that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:
function resultsByName(name)
{
var Card = Parse.Object.extend("Card");
var query = new Parse.Query(Card);
query.equalTo("name", name.toString());
var resultsArray = [];
return query.find({});
}
// later
resultsByName("Some Name").then(function(results){
// access results here by chaining to the returned promise
});
You can see more examples of using parse promises with queries in Parse's own blog post about it.
The proper way to do this is to use dispatch_async in the main_queue, as I did in the following code
dispatch_async(dispatch_get_main_queue(), {
(self.delegate as TBGQRCodeViewController).displayQRCode(receiveAddr, withAmountInBTC:amountBTC)
})
If you want to obtain it from query instead of psql, you can query the catalog schema. Here's a complex query that does that:
SELECT
f.attnum AS number,
f.attname AS name,
f.attnum,
f.attnotnull AS notnull,
pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,
CASE
WHEN p.contype = 'p' THEN 't'
ELSE 'f'
END AS primarykey,
CASE
WHEN p.contype = 'u' THEN 't'
ELSE 'f'
END AS uniquekey,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreignkey,
CASE
WHEN p.contype = 'f' THEN p.confkey
END AS foreignkey_fieldnum,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreignkey,
CASE
WHEN p.contype = 'f' THEN p.conkey
END AS foreignkey_connnum,
CASE
WHEN f.atthasdef = 't' THEN d.adsrc
END AS default
FROM pg_attribute f
JOIN pg_class c ON c.oid = f.attrelid
JOIN pg_type t ON t.oid = f.atttypid
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
LEFT JOIN pg_class AS g ON p.confrelid = g.oid
WHERE c.relkind = 'r'::char
AND n.nspname = '%s' -- Replace with Schema name
AND c.relname = '%s' -- Replace with table name
AND f.attnum > 0 ORDER BY number
;
It's pretty complex but it does show you the power and flexibility of the PostgreSQL system catalog and should get you on your way to pg_catalog mastery ;-). Be sure to change out the %s's in the query. The first is Schema and the second is the table name.
Use a progress bar with the style set to Marquee
. This represents an indeterminate progress bar.
myProgressBar.Style = ProgressBarStyle.Marquee;
You can also use the MarqueeAnimationSpeed
property to set how long it will take the little block of color to animate across your progress bar.
or you can simply use
def question_params
params.require(:question).permit(team_ids: [])
end
Use n module from npm in order to upgrade node
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
To upgrade to latest version (and not current stable) version, you can use
sudo n latest
Undo :
sudo apt-get install --reinstall nodejs-legacy # fix /usr/bin/node sudo n rm 6.0.0 # replace number with version of Node that was installed sudo npm uninstall -g n
Well firstly C doesn't have public/private/virtual functions. That's C++ and it has different conventions. In C typically you have:
C++ is more complex. I've seen a real mix here. Camel case for class names or lowercase+underscores (camel case is more common in my experience). Structs are used rarely (and typically because a library requires them, otherwise you'd use classes).
Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.
1.example for triggering external job from jenkins file with conditional example:
if (env.BRANCH_NAME == 'master') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam1',value: 'valueOfParam1')
booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
]
}
2.example triggering multiple jobs from jenkins file with conditionals example:
def jobs =[
'job1Title'{
if (env.BRANCH_NAME == 'master') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
]
}
},
'job2Title'{
if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam3',value: 'valueOfParam3')
booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
]
}
}
Declare @FKeyRemoveQuery NVarchar(max)
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
BEGIN
SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']'
FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')
EXECUTE Sp_executesql @FKeyRemoveQuery
END
Please take a look at Zdenek Kalal's Predator tracker. It requires some training, but it can actively learn how the tracked object looks at different orientations and scales and does it in realtime!
The source code is available on his site. It's in MATLAB, but perhaps there is a Java implementation already done by a community member. I have succesfully re-implemented the tracker part of TLD in C#. If I remember correctly, TLD is using Ferns as the keypoint detector. I use either SURF or SIFT instead (already suggested by @stacker) to reacquire the object if it was lost by the tracker. The tracker's feedback makes it easy to build with time a dynamic list of sift/surf templates that with time enable reacquiring the object with very high precision.
If you're interested in my C# implementation of the tracker, feel free to ask.
EDIT:
So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?
This question could be:
A request for advice; or
A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.
People differ in their predilection for following:
Official advice; or
The preponderance of practice.
Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!
In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.
By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.
Whatever your personal inclination, be it to follow one path or the other, I do not object.
(End of edit.)
The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).
As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.
As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.
Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."
Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."
As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.
The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.
Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!
Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?
Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).
Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.
Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.
Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.
Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".
The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.
".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.
You have to put the path to the file. For example:
require_once('../web/a.php');
You cannot get the file to require it from internet (with http protocol) it's restricted. The files must be on the same server. With Possibility to see each others (rights)
Dir-1 -
> Folder-1 -> a.php
Dir-2 -
> Folder-2 -> b.php
To include a.php inside b.php => require_once('../../Dir-1/Folder-1/a.php');
To include b.php inside a.php => require_once('../../Dir-2/Folder-2/b.php');
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
Just do this. It doesn't affect the horizontal position.
.test {
position: fixed;
left: 0;
right: 0;
}
The answer here is very simple:
You're already containing it in double quotes, so there's no need to escape it with \
.
If you want to escape single quotes in a single quote string:
var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
// ^ ^ same types, hence we need to escape it with a backslash
or if you want to escape \'
, you can escape the bashslash to \\
and the quote to \'
like so:
var string = 'this isn\\\'t a double quoted string';
// vvvv
// \ ' (the escaped characters)
However, if you contain the string with a different quote type, you don't need to escape:
var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
// ^ ^ different types, hence we don't need escaping
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
(Edit: two previous answers removed, one for answering the question as it stood before edits and one for being, if not absolutely wrong, at least close to it.)
If you compile with debug information on (javac -g
), the names of local variables are kept in the .class file. For example, take this simple class:
class TestLocalVarNames {
public String aMethod(int arg) {
String local1 = "a string";
StringBuilder local2 = new StringBuilder();
return local2.append(local1).append(arg).toString();
}
}
After compiling with javac -g:vars TestLocalVarNames.java
, the names of local variables are now in the .class file. javap
's -l
flag ("Print line number and local variable tables") can show them.
javap -l -c TestLocalVarNames
shows:
class TestLocalVarNames extends java.lang.Object{
TestLocalVarNames();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this LTestLocalVarNames;
public java.lang.String aMethod(int);
Code:
0: ldc #2; //String a string
2: astore_2
3: new #3; //class java/lang/StringBuilder
6: dup
7: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V
10: astore_3
11: aload_3
12: aload_2
13: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
16: iload_1
17: invokevirtual #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
20: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
23: areturn
LocalVariableTable:
Start Length Slot Name Signature
0 24 0 this LTestLocalVarNames;
0 24 1 arg I
3 21 2 local1 Ljava/lang/String;
11 13 3 local2 Ljava/lang/StringBuilder;
}
The VM spec explains what we're seeing here:
§4.7.9 The LocalVariableTable
Attribute:
The
LocalVariableTable
attribute is an optional variable-length attribute of aCode
(§4.7.3) attribute. It may be used by debuggers to determine the value of a given local variable during the execution of a method.
The LocalVariableTable
stores the names and types of the variables in each slot, so it is possible to match them up with the bytecode. This is how debuggers can do "Evaluate expression".
As erickson said, though, there's no way to access this table through normal reflection. If you're still determined to do this, I believe the Java Platform Debugger Architecture (JPDA) will help (but I've never used it myself).
In case that you want to add a class to a form's field in a template (not in view.py or form.py) for example in cases that you want to modify 3rd party apps without overriding their views, then a template filter as described in Charlesthk answer is very convenient. But in this answer the template filter overrides any existing classes that the field might has.
I tried to add this as an edit but it was suggested to be written as a new answer.
So, here is a template tag that respects the existing classes of the field:
from django import template
register = template.Library()
@register.filter(name='addclass')
def addclass(field, given_class):
existing_classes = field.field.widget.attrs.get('class', None)
if existing_classes:
if existing_classes.find(given_class) == -1:
# if the given class doesn't exist in the existing classes
classes = existing_classes + ' ' + given_class
else:
classes = existing_classes
else:
classes = given_class
return field.as_widget(attrs={"class": classes})
I think using this will be the easiest
new Uri("pack://application:,,/FolderIcon/" + youImageICO);
or this code will work on any machine that if your folder is in your root project if you want to change it... just change this section @"..\"
public static string bingPathToAppDir(string localPath)
{
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(
Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + localPath)));
return directory.ToString();
}
If your intention or the context of this question is really garbage collection, then you can set the datasets and datatables to null explicitly or use the keyword using and let them go out of scope. Dispose does not do much as Tetraneutron said it earlier. GC will collect dataset objects that are no longer referenced and also those that are out of scope.
I really wish SO forced people down voting to actually write a comment before downvoting the answer.
You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.
See example bellow
([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
_x000D_
<div id="test">_x000D_
<span>1</span>_x000D_
<span>2</span>_x000D_
<span>3</span>_x000D_
<span>4</span>_x000D_
<div>
_x000D_
I think this code will do what you want. It stores the first row as a set of headers, then stores the rest in a data object which you can write to disk as JSON.
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
var worksheet = workbook.Sheets[y];
var headers = {};
var data = [];
for(z in worksheet) {
if(z[0] === '!') continue;
//parse out the column, row, and value
var col = z.substring(0,1);
var row = parseInt(z.substring(1));
var value = worksheet[z].v;
//store header names
if(row == 1) {
headers[col] = value;
continue;
}
if(!data[row]) data[row]={};
data[row][headers[col]] = value;
}
//drop those first two rows which are empty
data.shift();
data.shift();
console.log(data);
});
prints out
[ { id: 1,
headline: 'team: sally pearson',
location: 'Australia',
'body text': 'majority have…',
media: 'http://www.youtube.com/foo' },
{ id: 2,
headline: 'Team: rebecca',
location: 'Brazil',
'body text': 'it is a long established…',
media: 'http://s2.image.foo/' } ]
You could use this CMD in your Dockerfile
:
CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"
This will keep your container alive until it is told to stop. Using trap and wait will make your container react immediately to a stop request. Without trap/wait stopping will take a few seconds.
For busybox based images (used in alpine based images) sleep does not know about the infinity argument. This workaround gives you the same immediate response to a docker stop
like in the above example:
CMD exec /bin/sh -c "trap : TERM INT; sleep 9999999999d & wait"
char ch = Character.MIN_VALUE;
The code above will initialize the variable ch
with the minimum value that a char can have (i.e. \u0000
).
I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:
const ROUTER_INSTANCE = new VueRouter({
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
// ... other routes ...
// and finally the default route, when none of the above matches:
{ path: "*", component: PageNotFound }
]
})
In the above PageNotFound
component definition, you can specify the actual redirect, that will take you out of the app entirely:
Vue.component("page-not-found", {
template: "",
created: function() {
// Redirect outside the app using plain old javascript
window.location.href = "/my-new-404-page.html";
}
}
You may do it either on created
hook as shown above, or mounted
hook also.
Please note:
I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli
as it requires server side handling.
Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">
. This will fail for your /404-page.html
unless your server treats it as a special case and serves the static page.
Let me know if it works!
Update for Vue 3 onward:
You'll need to replace the '*'
path property with '/:pathMatch(.*)*'
if you're using Vue 3 as the old catch-all path of '*'
is no longer supported. The route would then look something like this:
{ path: '/:pathMatch(.*)*', component: PathNotFound },
See the docs for more info on this update.
I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.
CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM dbo.MyTable
The Statistic plugin worked for me.
To install it from Intellij:
File - Settings - Plugins - Browse repositories... Find it on the list and double-click on it.
Access the 'statistic' toolbar via tabs in bottom left of project
OLDER VERSIONS: Open statistics window from:
View -> Tool Windows -> Statistic
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the wrong approach!
If what you really want is a password-less mount
for that volume, maybe sudo
isn't needed at all! So may I suggest other approaches?
Use /etc/fstab
as mensi suggested. Use options user
and noauto
to let regular users mount that volume.
Use Polkit
for passwordless actions: Configure a .policy
file for your script with <allow_any>yes</allow_any>
and drop at /usr/share/polkit-1/actions
Edit /etc/sudoers
to allow your user to use sudo
without typing your password. As @Anders suggested, you can restrict such usage to specific commands, thus avoiding unlimited passwordless root priviledges in your account. See this answer for more details on /etc/sudoers
.
All the above allow passwordless root privilege, none require you to hardcode your password. Choose any approach and I can explain it in more detail.
As for why it is a very bad idea to hardcode passwords, here are a few good links for further reading:
The accepted answer from Thorn007 doesn't work when the image is too small.
To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.
Example:
<div style="width:400px; height:200px;">
<img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>
Notes:
-webkit-transform:scale(4); -webkit-transform-origin:left top;
in the style.First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
What is the length of str array, and with how much 0s it is ending?
int main() {
char str[] = "Hello\0";
int length = sizeof str / sizeof str[0];
// "sizeof array" is the bytes for the whole array (must use a real array, not
// a pointer), divide by "sizeof array[0]" (sometimes sizeof *array is used)
// to get the number of items in the array
printf("array length: %d\n", length);
printf("last 3 bytes: %02x %02x %02x\n",
str[length - 3], str[length - 2], str[length - 1]);
return 0;
}
You can do it in-place like so:
l = [1, 2, 3, 4, 5]
l[:] = [x * 5 for x in l]
This requires no additional imports and is very pythonic.
If you want to pass the type, than the equivalent in Java would be
java.lang.Class
If you want to use a weakly typed method, then you would simply use
java.lang.Object
and the corresponding operator
instanceof
e.g.
private void foo(Object o) {
if(o instanceof String) {
}
}//foo
However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.
The real question is what you actually want to achieve here, otherwise it is difficult to answer:
Or is there a better way?
You want to use the atof() function.