you can load images in your html somewhere using css display:none;
rule, then show them when you want with js or jquery
don't use js or jquery functions to preload is just a css rule Vs many lines of js to be executed
example: Html
<img src="someimg.png" class="hide" alt=""/>
Css:
.hide{
display:none;
}
jQuery:
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
Preloading images by jquery/javascript is not good cause images takes few milliseconds to load in page + you have milliseconds for the script to be parsed and executed, expecially then if they are big images, so hiding them in hml is better also for performance, cause image is really preloaded without beeing visible at all, until you show that!
A modern approach using STRING_SPLIT, requires SQL Server 2016 and above.
DECLARE @string varchar(100) = 'Hello John Smith'
SELECT
ROW_NUMBER() OVER (ORDER BY value) AS RowNr,
value
FROM string_split(@string, ' ')
Result:
RowNr value
1 Hello
2 John
3 Smith
Now it is possible to get th nth element from the row number.
I know this is an old post but I got the same error recently so for what it's worth, here's another solution:
This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.
However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:
First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:
Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.
weirdness
You can do this entirely with html and css and i have.
HTML
First you give the div you wish to hide an ID
to target like #view_element
and a class to target like #hide_element
. You can if you wish make both of these classes but i don't know if you can make them both IDs. Then have your Show button target your show id and your Hide button target your hide class. That is it for the html the hiding and showing is done in the CSS.
CSS The css to show and hide this should look something like this
#hide_element:target {
display:none;
}
.show_element:target{
display:block;
}
This should allow you to hide and show elements at will. This should work nicely on spans and divs.
OPTION 1: if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2: or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:
"Features" >
Unfortunately changing it through the UI means that the changes don't persist between logins.
First go to your Docker Hub account and make the repo. Here is a screenshot of my Docker Hub account:
From the pic, you can see my repo is “chuangg”
Now go into the repo and make it private by clicking on your image’s name. So for me, I clicked on “chuangg/gene_commited_image”, then I went to Settings -> Make Private. Then I followed the on screen instructions
HOW TO UPLOAD YOUR DOCKER IMAGE ONTO DOCKER HUB
Method #1= Pushing your image through the command line (cli)
1) docker commit <container ID> <repo name>/<Name you want to give the image>
Yes, I think it has to be the container ID. It probably cannot be the image ID.
For example= docker commit 99e078826312 chuangg/gene_commited_image
2) docker run -it chaung/gene_commited_image
3) docker login --username=<user username> --password=<user password>
For example= docker login --username=chuangg [email protected]
Yes, you have to login first. Logout using “docker logout”
4) docker push chuangg/gene_commited_image
Method #2= Pushing your image using pom.xml and command line.
Note, I used a Maven Profile called “build-docker”. If you don’t want to use a profile, just remove the <profiles>, <profile>, and <id>build-docker</id>
elements.
Inside the parent pom.xml:
<profiles>
<profile>
<id>build-docker</id>
<build>
<plugins>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.18.1</version>
<configuration>
<images>
<image>
<name>chuangg/gene_project</name>
<alias>${docker.container.name}</alias>
<!-- Configure build settings -->
<build>
<dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
<assembly>
<inline>
<fileSets>
<fileSet>
<directory>${project.basedir}\target</directory>
<outputDirectory>.</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</inline>
</assembly>
</build>
</image>
</images>
</configuration>
<executions>
<execution>
<id>docker:build</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Docker Terminal Command to deploy the Docker Image (from the directory where your pom.xml is located)= mvn clean deploy -Pbuild-docker docker:push
Note, the difference between Method #2 and #3 is that Method #3 has an extra <execution>
for the deployment.
Method #3= Using Maven to automatically deploy to Docker Hub
Add this stuff to your parent pom.xml:
<distributionManagement>
<repository>
<id>gene</id>
<name>chuangg</name>
<uniqueVersion>false</uniqueVersion>
<layout>legacy</layout>
<url>https://index.docker.io/v1/</url>
</repository>
</distributionManagement>
<profiles>
<profile>
<id>build-docker</id>
<build>
<plugins>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.18.1</version>
<configuration>
<images>
<image>
<name>chuangg/gene_project1</name>
<alias>${docker.container.name}</alias>
<!-- Configure build settings -->
<build>
<dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
<assembly>
<inline>
<fileSets>
<fileSet>
<directory>${project.basedir}\target</directory>
<outputDirectory>.</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</inline>
</assembly>
</build>
</image>
</images>
</configuration>
<executions>
<execution>
<id>docker:build</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
<execution>
<id>docker:push</id>
<phase>install</phase>
<goals>
<goal>push</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Go to C:\Users\Gene.docker\ directory and add this to your config.json file:
Now in your Docker Quickstart Terminal type= mvn clean install -Pbuild-docker
For those of you not using Maven Profiles, just type mvn clean install
Here is the screenshot of the success message:
Here is my full pom.xml and a screenshot of my directory structure:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gene.app</groupId>
<artifactId>VendingMachineDockerMavenPlugin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Maven Quick Start Archetype</name>
<url>www.gene.com</url>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.gene.sample.Customer_View</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>gene</id>
<name>chuangg</name>
<uniqueVersion>false</uniqueVersion>
<layout>legacy</layout>
<url>https://index.docker.io/v1/</url>
</repository>
</distributionManagement>
<profiles>
<profile>
<id>build-docker</id>
<properties>
<java.docker.version>1.8.0</java.docker.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.18.1</version>
<configuration>
<images>
<image>
<name>chuangg/gene_project1</name>
<alias>${docker.container.name}</alias>
<!-- Configure build settings -->
<build>
<dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
<assembly>
<inline>
<fileSets>
<fileSet>
<directory>${project.basedir}\target</directory>
<outputDirectory>.</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</inline>
</assembly>
</build>
</image>
</images>
</configuration>
<executions>
<execution>
<id>docker:build</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
<execution>
<id>docker:push</id>
<phase>install</phase>
<goals>
<goal>push</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Here is my Dockerfile:
FROM java:8
MAINTAINER Gene Chuang
RUN echo Running Dockerfile in src/docker/vending_machine_emulator/Dockerfile directory
ADD maven/VendingMachineDockerMavenPlugin-1.0-SNAPSHOT.jar /bullshitDirectory/gene-app-1.0-SNAPSHOT.jar
CMD ["java", "-classpath", "/bullshitDirectory/gene-app-1.0-SNAPSHOT.jar", "com/gene/sample/Customer_View" ]
Solution for Error #1= Do not sync the <execution>
with maven deploy phase because then maven tries to deploy the image 2x and puts a timestamp on the jar. That’s why I used <phase>install</phase>
.
awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'
Add the numbers in $2
(second column) in sum
(variables are auto-initialized to zero by awk
) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.
awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'
If you want to use the shebang notation, you could write:
#!/bin/awk
{ sum += $2 }
END { if (NR > 0) print sum / NR }
You can also control the format of the average with printf()
and a suitable format ("%13.6e\n"
, for example).
You can also generalize the code to average the Nth column (with N=2
in this sample) using:
awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'
Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the Composite Pattern This is ideal for working with "Tree-Like Structures"..
Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^
Other answers to this question do not return what the OP needs, they will return a string like:
test1 test2 test3 test1 test3 test4
(notice that test1
and test3
are duplicated) while the OP wants to return this string:
test1 test2 test3 test4
the problem here is that the string "test1 test3"
is duplicated and is inserted only once, but all of the others are distinct to each other ("test1 test2 test3"
is distinct than "test1 test3"
, even if some tests contained in the whole string are duplicated).
What we need to do here is to split each string into different rows, and we first need to create a numbers table:
CREATE TABLE numbers (n INT);
INSERT INTO numbers VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
then we can run this query:
SELECT
SUBSTRING_INDEX(
SUBSTRING_INDEX(tableName.categories, ' ', numbers.n),
' ',
-1) category
FROM
numbers INNER JOIN tableName
ON
LENGTH(tableName.categories)>=
LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1;
and we get a result like this:
test1
test4
test1
test1
test2
test3
test3
test3
and then we can apply GROUP_CONCAT aggregate function, using DISTINCT clause:
SELECT
GROUP_CONCAT(DISTINCT category ORDER BY category SEPARATOR ' ')
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
FROM
numbers INNER JOIN tableName
ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
) s;
Please see fiddle here.
Short and simple implementation in Kotlin, with nullable support:
Add methods to Parcel
fun Parcel.writeBoolean(flag: Boolean?) {
when(flag) {
true -> writeInt(1)
false -> writeInt(0)
else -> writeInt(-1)
}
}
fun Parcel.readBoolean(): Boolean? {
return when(readInt()) {
1 -> true
0 -> false
else -> null
}
}
And use it:
parcel.writeBoolean(isUserActive)
parcel.readBoolean() // For true, false, null
parcel.readBoolean()!! // For only true and false
I'm not sure that Java has infinity for every numerical type but for some numerical data types the answer is positive:
Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY
or
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Also you may find useful the following article which represents some mathematical operations involving +/- infinity: Java Floating-Point Number Intricacies.
You may also verify that if you changed your main website folder (c:\inetpub\wwwroot
) to another folder you must give read permission to the IIS_IUSRS group in the new folder.
The simple thing that you can do is to check if Skype or VMware is installed in your machine or not.
Skype uses port 80 and 443 as an additional port for incoming connections. To change the port number in Skype, go to
Tools > Connection Options > Connection
in the Skype window. Now change the default 80 port number to something other.
VMware Workstation uses port 443 for sharing. To change this, open VMware Workstation and goto
Edit > Preferences > Shared Vms
That's all you have to do. Restart XAMPP and run the Apache server.
this error happen with me because I did the following
Update Model from database
in Edmx) I Renamed manually Property name to match the change in database schema Although all of this, I got this error
so what to do
Update Model from database
this will regenerate the model, and entity framework will
not give you this error
hope this help you
I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:
SELECT
name, author_id, count(*), t.total
FROM
names as n1
INNER JOIN LATERAL (
SELECT
count(*) as total
FROM
names as n2
WHERE
n2.id = n1.id
AND n2.author_id = n1.author_id
) as t ON 1=1
GROUP BY
n1.name, n1.author_id
Integer.toString(n,8) // decimal to octal
Integer.toString(n,2) // decimal to binary
Integer.toString(n,16) //decimal to Hex
where n = decimal number.
If you open the dropdown for the Text
property in Visual Studio, you can use the enter key to split lines. This will obviously only work for static text unless you know the maximum dimensions of dynamic text.
Here's an option that:
`
$('select').each(function(){
var $select = $(this);
$select.data('options', $select.find('option'));
});
function filter($select, search) {
var $prev = null;
var $options = $select.data('options');
search = search.trim().toLowerCase();
$options.each(function(){
var $option = $(this);
var optionText = $option.text();
if(search == "" || optionText.indexOf(search) >= 0) {
if ($option.parent().length) {
$prev = $option;
return;
}
if (!$prev) $select.prepend($option);
else $prev.after($option);
$prev = $option;
}
else {
$option.remove();
}
});
}
`
JSFiddle: https://jsfiddle.net/derrh5tr/
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
This should fix it:
var total = 0;
$(".price").each( function(){
total += $(this).val() * 1;
});
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
The only selector I see is a[id$="name"]
(all links with id finishing by "name") but it's not as restrictive as it should.
__PRETTY_FUNCTION__
handles C++ features: classes, namespaces, templates and overload
main.cpp
#include <iostream>
namespace N {
class C {
public:
template <class T>
static void f(int i) {
(void)i;
std::cout << "__func__ " << __func__ << std::endl
<< "__FUNCTION__ " << __FUNCTION__ << std::endl
<< "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
}
template <class T>
static void f(double f) {
(void)f;
std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
}
};
}
int main() {
N::C::f<char>(1);
N::C::f<void>(1.0);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
__func__ f
__FUNCTION__ f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]
You may also be interested in stack traces with function names: print call stack in C or C++
Tested in Ubuntu 19.04, GCC 8.3.0.
C++20 std::source_location::function_name
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.
The documentation says:
constexpr const char* function_name() const noexcept;
6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.
where NTBS means "Null Terminated Byte String".
I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a
still doesn't support it.
https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Possible output:
info:main.cpp:16:main Hello world!
so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?
Alternatively you can create your own afxres.h:
#ifndef _AFXRES_H
#define _AFXRES_H
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _WINDOWS_H
#include <windows.h>
#endif
/* IDC_STATIC is documented in winuser.h, but not defined. */
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif
#ifdef __cplusplus
}
#endif
#endif
If you install the application on your device via adb install
you should look for the reinstall option which should be -r
. So if you do adb install -r
you should be able to install without uninstalling before.
As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.
Some examples:
Python:
To retrieve any attribute form a visible element (e.g. <h1>
tag) you need to use the expected_conditions as visibility_of_element_located(locator)
as follows:
attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
To retrieve any attribute form an interactive element (e.g. <input>
tag) you need to use the expected_conditions as element_to_be_clickable(locator)
as follows:
attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
Below is a list of some attributes often used in HTML
Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference
I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".
Just call require
:
const content = require('../../path_of_your.json');
The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl
property by template
and the value by a require
call to the actual HTML resource.
If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json
:
"compilerOptions": {
"types": ["node"],
...
},
...
I have a simpler and elegant solution that doesn't mess up with classes, styles, opacities and stuff.
For the draggable element - you add 'start' event which will execute every time you try to move the element somewhere. You will have a condition which move is not legal. For the moves that are illegal - prevent them with 'e.preventDefault();' like in the code below.
$(".disc").draggable({
revert: "invalid",
cursor: "move",
start: function(e, ui){
console.log("element is moving");
if(SOME_CONDITION_FOR_ILLEGAL_MOVE){
console.log("illegal move");
//This will prevent moving the element from it's position
e.preventDefault();
}
}
});
You are welcome :)
In addition to @senderle's here, some might also be wondering how to use the functionality of multiprocessing.Pool
.
The nice thing is that there is a .Pool()
method to the manager
instance that mimics all the familiar API of the top-level multiprocessing
.
from itertools import repeat
import multiprocessing as mp
import os
import pprint
def f(d: dict) -> None:
pid = os.getpid()
d[pid] = "Hi, I was written by process %d" % pid
if __name__ == '__main__':
with mp.Manager() as manager:
d = manager.dict()
with manager.Pool() as pool:
pool.map(f, repeat(d, 10))
# `d` is a DictProxy object that can be converted to dict
pprint.pprint(dict(d))
Output:
$ python3 mul.py
{22562: 'Hi, I was written by process 22562',
22563: 'Hi, I was written by process 22563',
22564: 'Hi, I was written by process 22564',
22565: 'Hi, I was written by process 22565',
22566: 'Hi, I was written by process 22566',
22567: 'Hi, I was written by process 22567',
22568: 'Hi, I was written by process 22568',
22569: 'Hi, I was written by process 22569',
22570: 'Hi, I was written by process 22570',
22571: 'Hi, I was written by process 22571'}
This is a slightly different example where each process just logs its process ID to the global DictProxy
object d
.
Download
Get the latest pre-built OpenCV for Android release from https://github.com/opencv/opencv/releases and unpack it (for example, opencv-4.4.0-android-sdk.zip).
Create an empty Android Studio project
Open Android Studio. Start a new project.
Keep default target settings.
Use "Empty Activity" template. Name activity as MainActivity with a corresponding layout activity_main. Plug in your device and run the project. It should be installed and launched successfully before we'll go next.
Add OpenCV dependency
Go to File->New->Import module
and provide a path to unpacked_OpenCV_package/sdk/java. The name of module detects automatically. Disable all features that Android Studio will suggest you on the next window.
Configure your library build.gradle (openCVLibrary build.gradle)
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
Implement the library to the project (application build.gradle)
implementation project(':openCVLibrary330')
Update on the accepted answer:
Because of many properties becoming deprecated
(property) KeyboardEvent.which: number @deprecated
you should just rely on the key property and create the rest of the logic by yourself:
The code allows Enter, Backspace and all numbers [0-9], every other character is disallowed.
document.querySelector("input").addEventListener("keypress", (e) => {
if (isNaN(parseInt(e.key, 10)) && e.key !== "Backspace" && e.key !== "Enter") {
e.preventDefault();
}
});
NOTE This will disable paste action
To determine the type of a variable after a conditional statement you can use type guards. A type guard in typescript is the following:
An expression which allows you to narrow down the type of something within a conditional block.
In other words it is an expression within a conditional block from where the typescript compiler has enough information to narrow down the type. The type will be more specific within the block of the type guard because the compiler has inferred more information about the type.
declare let abc: number | string;
// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
// abc: string
console.log('abc is a string here')
} else {
// abc: number, only option because the previous type guard removed the option of string
console.log('abc is a number here')
}
Besides the typeof
operator there are built in type guards like instanceof
, in
and even your own type guards.
If you have released to Apple TestFlight for testing
You have to click the link each time and select No, only after that, your tester can see the build. This is quite annoying if you want to get your build delivered as soon as possible.
Do this for the next build, (If do this before the build then this error will not occur)
The solution is add the following setting to your iOS Info.plist
:
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
Can not add "Missing Compliance", see this Missing Compliance
These days, socket.on('connect', ...) is not working for me. I use the below code to check at 1st connecting.
if (socket.connected)
console.log('socket.io is connected.')
and use this code when reconnected.
socket.on('reconnect', ()=>{
//Your Code Here
});
Here are two ways, notice in this case that the first way assigns a new array ( translates to somearray = somearray + anotherarray )
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray += anotherarray # => ["some", "thing", "another", "thing"]
somearray = ["some", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
Without enumerate()
:
>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]
It sounds like the application isn't signed. Download ldid from Cydia and then use it like so: ldid -S /Applications/AccelerometerGraph.app/AccelerometerGraph
Also be sure that the binary is marked as executable: chmod +x /Applications/AccelerometerGraph.app/AccelerometerGraph
I would recommend staying pure to REST principles and using an HTTP delete for your deletes. Unfortunately HTML Specs only has HTTP Get & Post. A tag only can a HTTP Get. A form tag can either do a HTTP Get or Post. Fortunately if you use ajax you can do a HTTP Delete and this is what i recommend. See the following post for details: Http Deletes
@BindView(R.id.checkbox_id) // if you are using Butterknife
CheckBox yourCheckBox;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)
yourCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
}
});
}
Obviously you have to make your XML with the id of your checkbox :
<CheckBox
android:id="@+id/checkbox_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your label"
/>
So, the method to know if the check box is checked is : (CheckBox) yourCheckBox.isChecked()
it returns true
if the check box is checked.
I've literally just arrived at the answer in my case. I'm creating a system that has implemented a create method, so I was getting this actual error because I was accessing the overridden version not the one from Eloquent.
Hope that help?
Make sure you remove any java.exe
, javaw.exe
and javaws.exe
from your Windows\System32
folder and if you have an x64 system (Win 7 64 bits) also do the same under Windows\SysWOW64
.
If you can't find them at these locations, try deleting them from C:\ProgramData\Oracle\Java\javapath
.
You try to append to second element in array, but it does not exist. Create it.
arr = [[]]
arr[0].append("aa1")
arr[0].append("aa2")
arr.append([])
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")
Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)
The only solution that worked for me (node 12.x, npm 6.x) was using npm-force-resolutions developed by @Rogerio Chaves.
First, install it by:
npm install npm-force-resolutions --save-dev
You can add --ignore-scripts
if some broken transitive dependency scripts are blocking you from installing anything.
Then in package.json
define what dependency should be overridden (you must set exact version number):
"resolutions": {
"your-dependency-name": "1.23.4"
}
and in "scripts"
section add new preinstall entry:
"preinstall": "npx npm-force-resolutions",
Now, npm install
will apply changes and force your-dependency-name
to be at version 1.23.4
for all dependencies.
I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!
Example:
SQLQueryString = $"
Insert into Employee values(
{txtEmployeeNo},
{txtContractsStartDate},
{txtSeatNo},
{txtFloor},
{txtLeaves}
)"
It works. Documentation Here
Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
It doesn't because the href value is not sign_up
.It is #sign_up
. Try like below,
You need to add "#" to indicate the id of the href value.
$('a[href="#sign_up"]').click(function(){
alert('Sign new href executed.');
});
If you have multiple sections, here's how to get the last row in the last section (Swift 3):
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let visibleRows = tableView.indexPathsForVisibleRows, let lastRow = visibleRows.last?.row, let lastSection = visibleRows.map({$0.section}).last {
if indexPath.row == lastRow && indexPath.section == lastSection {
// Finished loading visible rows
}
}
}
swift 3.0 insert in viewDidLoad(), this->
{
view.addSubview(Your_messageInputConteinerView)
view.addConstraintWithFormat(format: "H:|[v0]|", views:Your_messageInputConteinerView)
view.addConstraintWithFormat(format: "V:[v0(48)]", views:Your_messageInputConteinerView)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(notification:)), name: .UIKeyboardWillHide, object: nil)
bottomConstraint = NSLayoutConstraint(item: Your_messageInputConteinerView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomConstraint!)
}
func handleKeyboardNotification(notification:Notification){
if let userInfo = notification.userInfo {
if let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{
print(keyBoardFrame)
if bottomConstraint?.constant != CGFloat(0) {
bottomConstraint?.constant = 0
return
}
bottomConstraint?.constant = -keyBoardFrame.height
or
self.view.frame.origin.y = -keyBoardFrame.height
}
}
}
I have found this tutorial at javascript.info to be very clear in explaining this topic. And its 3-points summary at the end is really talking to the crucial points. I quote it here:
- Events first are captured down to deepest target, then bubble up. In IE<9 they only bubble.
- All handlers work on bubbling stage excepts
addEventListener
with last argumenttrue
, which is the only way to catch the event on capturing stage.- Bubbling/capturing can be stopped by
event.cancelBubble=true
(IE) orevent.stopPropagation()
for other browsers.
You'll likely need to re-register ASP.Net version 4 with IIS.
Navigate to your .net framework 4.0 folder, and run aspnet_regiis.exe -i
For example, my .net framework 4.0 folder (Server 2k8 R2 x64) was located at: C:\Windows\Microsoft.NET\Framework64\v4.0.30319
To add my two cents to the conversation a process can have simultaneously open a number of sockets connected equal to this number (in Linux type sytems) /proc/sys/net/core/somaxconn
cat /proc/sys/net/core/somaxconn
This number can be modified on the fly (only by root user of course)
echo 1024 > /proc/sys/net/core/somaxconn
But entirely depends on the server process, the hardware of the machine and the network, the real number of sockets that can be connected before crashing the system
There a 3 ways to implement validation:
Validation rule example:
public class NumericValidationRule : ValidationRule
{
public Type ValidationType { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string strValue = Convert.ToString(value);
if (string.IsNullOrEmpty(strValue))
return new ValidationResult(false, $"Value cannot be coverted to string.");
bool canConvert = false;
switch (ValidationType.Name)
{
case "Boolean":
bool boolVal = false;
canConvert = bool.TryParse(strValue, out boolVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of boolean");
case "Int32":
int intVal = 0;
canConvert = int.TryParse(strValue, out intVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int32");
case "Double":
double doubleVal = 0;
canConvert = double.TryParse(strValue, out doubleVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Double");
case "Int64":
long longVal = 0;
canConvert = long.TryParse(strValue, out longVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int64");
default:
throw new InvalidCastException($"{ValidationType.Name} is not supported");
}
}
}
XAML:
Very important: don't forget to set ValidatesOnTargetUpdated="True"
it won't work without this definition.
<TextBox x:Name="Int32Holder"
IsReadOnly="{Binding IsChecked,ElementName=CheckBoxEditModeController,Converter={converters:BooleanInvertConverter}}"
Style="{StaticResource ValidationAwareTextBoxStyle}"
VerticalAlignment="Center">
<!--Text="{Binding Converter={cnv:TypeConverter}, ConverterParameter='Int32', Path=ValueToEdit.Value, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"-->
<TextBox.Text>
<Binding Path="Name"
Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged"
Converter="{cnv:TypeConverter}"
ConverterParameter="Int32"
ValidatesOnNotifyDataErrors="True"
ValidatesOnDataErrors="True"
NotifyOnValidationError="True">
<Binding.ValidationRules>
<validationRules:NumericValidationRule ValidationType="{x:Type system:Int32}"
ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<!--NumericValidationRule-->
</TextBox>
INotifyDataErrorInfo example:
public abstract class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
ValidateAsync();
}
#endregion
public virtual void OnLoaded()
{
}
#region INotifyDataErrorInfo
private ConcurrentDictionary<string, List<string>> _errors = new ConcurrentDictionary<string, List<string>>();
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public void OnErrorsChanged(string propertyName)
{
var handler = ErrorsChanged;
if (handler != null)
handler(this, new DataErrorsChangedEventArgs(propertyName));
}
public IEnumerable GetErrors(string propertyName)
{
List<string> errorsForName;
_errors.TryGetValue(propertyName, out errorsForName);
return errorsForName;
}
public bool HasErrors
{
get { return _errors.Any(kv => kv.Value != null && kv.Value.Count > 0); }
}
public Task ValidateAsync()
{
return Task.Run(() => Validate());
}
private object _lock = new object();
public void Validate()
{
lock (_lock)
{
var validationContext = new ValidationContext(this, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, validationResults, true);
foreach (var kv in _errors.ToList())
{
if (validationResults.All(r => r.MemberNames.All(m => m != kv.Key)))
{
List<string> outLi;
_errors.TryRemove(kv.Key, out outLi);
OnErrorsChanged(kv.Key);
}
}
var q = from r in validationResults
from m in r.MemberNames
group r by m into g
select g;
foreach (var prop in q)
{
var messages = prop.Select(r => r.ErrorMessage).ToList();
if (_errors.ContainsKey(prop.Key))
{
List<string> outLi;
_errors.TryRemove(prop.Key, out outLi);
}
_errors.TryAdd(prop.Key, messages);
OnErrorsChanged(prop.Key);
}
}
}
#endregion
}
View Model Implementation:
public class MainFeedViewModel : BaseViewModel//, IDataErrorInfo
{
private ObservableCollection<FeedItemViewModel> _feedItems;
[XmlIgnore]
public ObservableCollection<FeedItemViewModel> FeedItems
{
get
{
return _feedItems;
}
set
{
_feedItems = value;
OnPropertyChanged("FeedItems");
}
}
[XmlIgnore]
public ObservableCollection<FeedItemViewModel> FilteredFeedItems
{
get
{
if (SearchText == null) return _feedItems;
return new ObservableCollection<FeedItemViewModel>(_feedItems.Where(x => x.Title.ToUpper().Contains(SearchText.ToUpper())));
}
}
private string _title;
[Required]
[StringLength(20)]
//[CustomNameValidationRegularExpression(5, 20)]
[CustomNameValidationAttribute(3, 20)]
public string Title
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged("Title");
}
}
private string _url;
[Required]
[StringLength(200)]
[Url]
//[CustomValidation(typeof(MainFeedViewModel), "UrlValidation")]
/// <summary>
/// Validation of URL should be with custom method like the one that implemented below, or with
/// </summary>
public string Url
{
get { return _url; }
set
{
_url = value;
OnPropertyChanged("Url");
}
}
public MainFeedViewModel(string url, string title)
{
Title = title;
Url = url;
}
/// <summary>
///
/// </summary>
public MainFeedViewModel()
{
}
public MainFeedViewModel(ObservableCollection<FeedItemViewModel> feeds)
{
_feedItems = feeds;
}
private string _searchText;
[XmlIgnore]
public string SearchText
{
get { return _searchText; }
set
{
_searchText = value;
OnPropertyChanged("SearchText");
OnPropertyChanged("FilteredFeedItems");
}
}
#region Data validation local
/// <summary>
/// Custom URL validation method
/// </summary>
/// <param name="obj"></param>
/// <param name="context"></param>
/// <returns></returns>
public static ValidationResult UrlValidation(object obj, ValidationContext context)
{
var vm = (MainFeedViewModel)context.ObjectInstance;
if (!Uri.IsWellFormedUriString(vm.Url, UriKind.Absolute))
{
return new ValidationResult("URL should be in valid format", new List<string> { "Url" });
}
return ValidationResult.Success;
}
#endregion
}
XAML:
<UserControl x:Class="RssReaderTool.Views.AddNewFeedDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300">
<FrameworkElement.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate x:Name="TextErrorTemplate">
<DockPanel LastChildFill="True">
<AdornedElementPlaceholder>
<Border BorderBrush="Red"
BorderThickness="2" />
</AdornedElementPlaceholder>
<TextBlock FontSize="20"
Foreground="Red">*?*</TextBlock>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError"
Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource=
{x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"></Setter>
</Trigger>
</Style.Triggers>
</Style>
<!--<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError"
Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>-->
</FrameworkElement.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="5" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="5" />
<RowDefinition Height="Auto" />
<RowDefinition Height="5" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Feed Name"
ToolTip="Display" />
<TextBox Text="{Binding MainFeedViewModel.Title,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
Grid.Column="2" />
<TextBlock Text="Feed Url"
Grid.Row="2" />
<TextBox Text="{Binding MainFeedViewModel.Url,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
Grid.Column="2"
Grid.Row="2" />
</Grid>
</UserControl>
IDataErrorInfo:
View Model:
public class OperationViewModel : ViewModelBase, IDataErrorInfo
{
private const int ConstCodeMinValue = 1;
private readonly IEventAggregator _eventAggregator;
private OperationInfoDefinition _operation;
private readonly IEntityFilterer _contextFilterer;
private OperationDescriptionViewModel _description;
public long Code
{
get { return _operation.Code; }
set
{
if (SetProperty(value, _operation.Code, o => _operation.Code = o))
{
UpdateDescription();
}
}
}
public string Description
{
get { return _operation.Description; }
set
{
if (SetProperty(value, _operation.Description, o => _operation.Description = o))
{
UpdateDescription();
}
}
}
public string FriendlyName
{
get { return _operation.FriendlyName; }
set
{
if (SetProperty(value, _operation.FriendlyName, o => _operation.FriendlyName = o))
{
UpdateDescription();
}
}
}
public int Timeout
{
get { return _operation.Timeout; }
set
{
if (SetProperty(value, _operation.Timeout, o => _operation.Timeout = o))
{
UpdateDescription();
}
}
}
public string Category
{
get { return _operation.Category; }
set
{
if (SetProperty(value, _operation.Category, o => _operation.Category = o))
{
UpdateDescription();
}
}
}
public bool IsManual
{
get { return _operation.IsManual; }
set
{
if (SetProperty(value, _operation.IsManual, o => _operation.IsManual = o))
{
UpdateDescription();
}
}
}
void UpdateDescription()
{
//some code
}
#region Validation
#region IDataErrorInfo
public ValidationResult Validate()
{
return ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
}
public string this[string columnName]
{
get
{
var validation = ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
return validation.IsValid ? null : validation.ErrorContent.ToString();
}
}
public string Error
{
get
{
var result = Validate();
return result.IsValid ? null : result.ErrorContent.ToString();
}
}
#endregion
#endregion
}
XAML:
<controls:NewDefinitionControl x:Class="DiagnosticsDashboard.EntityData.Operations.Views.NewOperationView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:views="clr-namespace:DiagnosticsDashboard.EntityData.Operations.Views"
xmlns:controls="clr-namespace:DiagnosticsDashboard.Core.Controls;assembly=DiagnosticsDashboard.Core"
xmlns:c="clr-namespace:DiagnosticsDashboard.Core.Validation;assembly=DiagnosticsDashboard.Core"
mc:Ignorable="d">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Column="0"
Grid.Row="0"
Margin="5">Code:</Label>
<Label Grid.Column="0"
Grid.Row="1"
Margin="5">Description:</Label>
<Label Grid.Column="0"
Grid.Row="2"
Margin="5">Category:</Label>
<Label Grid.Column="0"
Grid.Row="3"
Margin="5">Friendly Name:</Label>
<Label Grid.Column="0"
Grid.Row="4"
Margin="5">Timeout:</Label>
<Label Grid.Column="0"
Grid.Row="5"
Margin="5">Is Manual:</Label>
<TextBox Grid.Column="1"
Text="{Binding Code,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
Grid.Row="0"
Margin="5"/>
<TextBox Grid.Column="1"
Grid.Row="1"
Margin="5"
Text="{Binding Description}" />
<TextBox Grid.Column="1"
Grid.Row="2"
Margin="5"
Text="{Binding Category}" />
<TextBox Grid.Column="1"
Grid.Row="3"
Margin="5"
Text="{Binding FriendlyName}" />
<TextBox Grid.Column="1"
Grid.Row="4"
Margin="5"
Text="{Binding Timeout}" />
<CheckBox Grid.Column="1"
Grid.Row="5"
Margin="5"
IsChecked="{Binding IsManual}"
VerticalAlignment="Center" />
</Grid>
</controls:NewDefinitionControl>
I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.
import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')
In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,
plt.legend(handles=[red_patch, black_patch])
And the legend ought to appear in the pointplot.
Edit: If you are using Docker-for-mac or Docker-for-Windows 18.03+, just connect to your mysql service using the host host.docker.internal
(instead of the 127.0.0.1
in your connection string).
As of Docker 18.09.3, this does not work on Docker-for-Linux. A fix has been submitted on March the 8th, 2019 and will hopefully be merged to the code base. Until then, a workaround is to use a container as described in qoomon's answer.
2020-01: some progress has been made. If all goes well, this should land in Docker 20.04
Docker 20.10-beta1 has been reported to implement host.docker.internal
:
$ docker run --rm --add-host host.docker.internal:host-gateway alpine ping host.docker.internal
PING host.docker.internal (172.17.0.1): 56 data bytes
64 bytes from 172.17.0.1: seq=0 ttl=64 time=0.534 ms
64 bytes from 172.17.0.1: seq=1 ttl=64 time=0.176 ms
...
Use --network="host"
in your docker run
command, then 127.0.0.1
in your docker container will point to your docker host.
Note: This mode only works on Docker for Linux, per the documentation.
Docker offers different networking modes when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.
Docker creates a bridge named docker0
by default. Both the docker host and the docker containers have an IP address on that bridge.
on the Docker host, type sudo ip addr show docker0
you will have an output looking like:
[vagrant@docker:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::5484:7aff:fefe:9799/64 scope link
valid_lft forever preferred_lft forever
So here my docker host has the IP address 172.17.42.1
on the docker0
network interface.
Now start a new container and get a shell on it: docker run --rm -it ubuntu:trusty bash
and within the container type ip addr show eth0
to discover how its main network interface is set up:
root@e77f6a1b3740:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
inet 172.17.1.192/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
valid_lft forever preferred_lft forever
Here my container has the IP address 172.17.1.192
. Now look at the routing table:
root@e77f6a1b3740:/# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.17.42.1 0.0.0.0 UG 0 0 0 eth0
172.17.0.0 * 255.255.0.0 U 0 0 0 eth0
So the IP Address of the docker host 172.17.42.1
is set as the default route and is accessible from your container.
root@e77f6a1b3740:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms
Alternatively you can run a docker container with network settings set to host
. Such a container will share the network stack with the docker host and from the container point of view, localhost
(or 127.0.0.1
) will refer to the docker host.
Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p
or -P
docker run
option.
IP config on my docker host:
[vagrant@docker:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
valid_lft forever preferred_lft forever
and from a docker container in host mode:
[vagrant@docker:~] $ docker run --rm -it --network=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
valid_lft forever preferred_lft forever
As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.
To access MySQL running on the docker host from containers in bridge mode, you need to make sure the MySQL service is listening for connections on the 172.17.42.1
IP address.
To do so, make sure you have either bind-address = 172.17.42.1
or bind-address = 0.0.0.0
in your MySQL config file (my.cnf).
If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :
export DOCKER_HOST_IP=$(route -n | awk '/UG[ \t]/{print $2}')
then in your application, use the DOCKER_HOST_IP
environment variable to open the connection to MySQL.
Note: if you use bind-address = 0.0.0.0
your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to setup firewall rules accordingly.
Note 2: if you use bind-address = 172.17.42.1
your MySQL server won't listen for connections made to 127.0.0.1
. Processes running on the docker host that would want to connect to MySQL would have to use the 172.17.42.1
IP address.
To access MySQL running on the docker host from containers in host mode, you can keep bind-address = 127.0.0.1
in your MySQL configuration and all you need to do is to connect to 127.0.0.1
from your containers:
[vagrant@docker:~] $ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
note: Do use mysql -h 127.0.0.1
and not mysql -h localhost
; otherwise the MySQL client would try to connect using a unix socket.
Doing it this way has always worked for me, I hope this helps.
var ddl = $("#dropListBuilding");
for (k = 0; k < buildings.length; k++)
ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");
On macOS, one option is to install FUSE for macOS and use sshfs
to mount a remote directory:
mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir
Some caveats apply with mounting network volumes, so YMMV.
I archive this using LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:height="166dp"
android:text="Tile1"
android:gravity="center"
android:background="#6f19e5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="Tile2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#f1d600"/>
<TextView
android:text="Tile3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#e75548"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="Tile4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#29d217"/>
<TextView
android:text="Tile5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#e519cb"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:height="176dp"
android:text="Tile6"
android:gravity="center"
android:background="#09eadd"/>
</LinearLayout>
</LinearLayout>
Hive Partitioning:
Partition divides large amount of data into multiple slices based on value of a table column(s).
Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.
Pros:
Cons:
Hive Bucketing:
Bucketing decomposes data into more manageable or equal parts.
With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.
Pros
Cons
GOPATH should be set to a newly created empty directory. This is the go "workspace", where it downloads packages, et cetera. I use ~/.go.
For example:
mkdir ~/.go
echo "GOPATH=$HOME/.go" >> ~/.bashrc
echo "export GOPATH" >> ~/.bashrc
echo "PATH=\$PATH:\$GOPATH/bin # Add GOPATH/bin to PATH for scripting" >> ~/.bashrc
source ~/.bashrc
source: http://www.larry-price.com/blog/2013/12/15/setting-up-a-go-environment-in-ubuntu-12-dot-04/
Since 2014b, Matlab has these normalization routines embedded natively in the histogram
function (see the help file for the 6 routines this function offers). Here is an example using the PDF normalization (the sum of all the bins is 1).
data = 2*randn(5000,1) + 5; % generate normal random (m=5, std=2)
h = histogram(data,'Normalization','pdf') % PDF normalization
The corresponding PDF is
Nbins = h.NumBins;
edges = h.BinEdges;
x = zeros(1,Nbins);
for counter=1:Nbins
midPointShift = abs(edges(counter)-edges(counter+1))/2;
x(counter) = edges(counter)+midPointShift;
end
mu = mean(data);
sigma = std(data);
f = exp(-(x-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));
The two together gives
hold on;
plot(x,f,'LineWidth',1.5)
An improvement that might very well be due to the success of the actual question and accepted answer!
EDIT - The use of hist
and histc
is not recommended now, and histogram
should be used instead. Beware that none of the 6 ways of creating bins with this new function will produce the bins hist
and histc
produce. There is a Matlab script to update former code to fit the way histogram
is called (bin edges instead of bin centers - link). By doing so, one can compare the pdf
normalization methods of @abcd (trapz
and sum
) and Matlab (pdf
).
The 3 pdf
normalization method give nearly identical results (within the range of eps
).
TEST:
A = randn(10000,1);
centers = -6:0.5:6;
d = diff(centers)/2;
edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
edges(2:end) = edges(2:end)+eps(edges(2:end));
figure;
subplot(2,2,1);
hist(A,centers);
title('HIST not normalized');
subplot(2,2,2);
h = histogram(A,edges);
title('HISTOGRAM not normalized');
subplot(2,2,3)
[counts, centers] = hist(A,centers); %get the count with hist
bar(centers,counts/trapz(centers,counts))
title('HIST with PDF normalization');
subplot(2,2,4)
h = histogram(A,edges,'Normalization','pdf')
title('HISTOGRAM with PDF normalization');
dx = diff(centers(1:2))
normalization_difference_trapz = abs(counts/trapz(centers,counts) - h.Values);
normalization_difference_sum = abs(counts/sum(counts*dx) - h.Values);
max(normalization_difference_trapz)
max(normalization_difference_sum)
The maximum difference between the new PDF normalization and the former one is 5.5511e-17.
For those working in Titanium Studio, the item is a little different: It's under the "Titanium Studio" Themes tab.
The color to change is the "Selection" one in the top right.
On macos Sierra this work for me, where python is managed by anaconda:
anaconda search -t conda mysql-python
anaconda show CEFCA/mysql-python
conda install --channel https://conda.anaconda.org/CEFCA mysql-python
The to use with SQLAlchemy:
Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org
>>> from sqlalchemy import *
>>>dbengine = create_engine('mysql://....')
In SSMS, "Query" menu item... "Results to"... "Results to File"
Shortcut = CTRL+shift+F
You can set it globally too
"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down
Edit: after comment
In SSMS, "Query" menu item... "SQLCMD" mode
This allows you to run "command line" like actions.
A quick test in my SSMS 2008
:OUT c:\foo.txt
SELECT * FROM sys.objects
Edit, Sep 2012
:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects
var cars = [{
make: 'audi',
model: 'r8',
year: '2012'
}, {
make: 'audi',
model: 'rs5',
year: '2013'
}, {
make: 'ford',
model: 'mustang',
year: '2012'
}, {
make: 'ford',
model: 'fusion',
year: '2015'
}, {
make: 'kia',
model: 'optima',
year: '2012'
}].reduce((r, car) => {
const {
model,
year,
make
} = car;
r[make] = [...r[make] || [], {
model,
year
}];
return r;
}, {});
console.log(cars);
_x000D_
It's the same principle.
You can either use SelectedIndex and use ComboBox.Items[SelectedIndex].ToString(). Or just ComboBox.SelectedItem and cast it to any type you need :)
From Rails Guide
You can use Active Record's ability to rollback migrations using the revert
method:
require_relative '20100905201547_create_blocks'
class FixupCreateBlock < ActiveRecord::Migration
def change
revert CreateBlock
create_table(:apples) do |t|
t.string :variety
end
end
end
The revert
method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations. For example, let's imagine that CreateBlock is committed and it is later decided it would be best to use Active Record validations, in place of the CHECK constraint, to verify the zipcode.
class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration
def change
revert do
# copy-pasted code from CreateBlock
reversible do |dir|
dir.up do
# add a CHECK constraint
execute <<-SQL
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
SQL
end
dir.down do
execute <<-SQL
ALTER TABLE distributors
DROP CONSTRAINT zipchk
SQL
end
end
# The rest of the migration was ok
end
end
end
The same migration could also have been written without using revert but this would have involved a few more steps: reversing the order of create_table and reversible, replacing create_table by drop_table, and finally replacing up by down and vice-versa. This is all taken care of by revert.
As far as I know python will compile all modules you "import". However python will NOT compile a python script run using: "python script.py" (it will however compile any modules that the script imports).
The real questions is why you don't want python to compile the modules? You could probably automate a way of cleaning these up if they are getting in the way.
In my case, I was copying and pasting code from my other classes, so I did not notice that the getter code was bad written:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "credito")
public Set getConceptoses() {
return this.letrases;
}
public void setConceptoses(Set conceptoses) {
this.conceptoses = conceptoses;
}
All references conceptoses but if you look at the get says letrases
Try to set :
default_socket_timeout = 120
in your php.ini
file.
A nice handy overview table from the Bash Hackers Wiki:
Syntax | Effective result |
---|---|
$* |
$1 $2 $3 … ${N} |
$@ |
$1 $2 $3 … ${N} |
"$*" |
"$1c$2c$3c…c${N}" |
"$@" |
"$1" "$2" "$3" … "${N}" |
where c
in the third row is the first character of $IFS
, the Input Field Separator, a shell variable.
If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*"
trick with the input field separator set to tab IFS=$'\t'
.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
Use:
git diff 15dc8^!
as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):
Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.
This means that you can use 15dc8^!
as a shorthand for 15dc8^..15dc8
anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8
is understood as git diff 15dc8^ 15dc8
, which means the difference between parent of commit (15dc8^
) and commit (15dc8
).
Note: the description in git-rev-parse(1)
manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^!
is "r1 --not r1^@
" i.e. "r1 ^r1^1 ^r1^2 ...
"
Also, you can use git show COMMIT
to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT
I would suggest using a custom filter such as this:
app.filter('reverse', function() {
return function(items) {
return items.slice().reverse();
};
});
Which can then be used like:
<div ng-repeat="friend in friends | reverse">{{friend.name}}</div>
See it working here: Plunker Demonstration
This filter can be customized to fit your needs as seen fit. I have provided other examples in the demonstration. Some options include checking that the variable is an array before performing the reverse, or making it more lenient to allow the reversal of more things such as strings.
Use the DataGridView.ReadOnly
property
The code in the MSDN example illustrates the use of this property in a DataGridView
control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.
Observe these settings in the sample code:
// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.DisableResizing;
To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace
function since it is not a mutator function:
myString = myString.replace('username1','');
Below I split all the details of formatted address like City, State, Country and Zip code.
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically.
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
var places = new google.maps.places.Autocomplete(document
.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function() {
var place = places.getPlace();
var address = place.formatted_address;
var value = address.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
var z=state.split(" ");
document.getElementById("selCountry").text = country;
var i =z.length;
document.getElementById("pstate").value = z[1];
if(i>2)
document.getElementById("pzcode").value = z[2];
document.getElementById("pCity").value = city;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
var mesg = address;
document.getElementById("txtPlaces").value = mesg;
var lati = latitude;
document.getElementById("plati").value = lati;
var longi = longitude;
document.getElementById("plongi").value = longi;
});
});
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
Here's what I did to do this. Keep in mind it won't work on IE8 and below.
#element {
width:100%;
height:50px;
background:url(/path/to/image.png);
background-position:140.112201963534% 973.333333333333%;
}
The background image's width will scale down as the parent of #element
scales down. You can do the same with its height, too, if you convert height
to a percentage. The only tricky bit are figuring out the percentages for background-position
.
The first percentage is the width of the targeted area of the sprite when at normal width divided by the sprite's total width, and multiplied by 100.
The second percentage is the height of the targeted area of the sprite before being scaled divided by the sprite's total height, and multiplied by 100.
The wording on those two equations is a little sloppy, so let me know if you need me to explain it better.
Yes, this is a kind of inconsistency in the language.
The "=" in myarray = "abc";
is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc";
it's an initialization of the array. There's no way for "late initialization".
You should just remember this rule.
In Node.js, you can set global variables via the "global" or "GLOBAL" object:
GLOBAL._ = require('underscore'); // But you "shouldn't" do this! (see note below)
or more usefully...
GLOBAL.window = GLOBAL; // Like in the browser
From the Node.js source, you can see that these are aliased to each other:
node-v0.6.6/src/node.js:
28: global = this;
128: global.GLOBAL = global;
In the code above, "this" is the global context. With the CommonJS module system (which Node.js uses), the "this" object inside of a module (i.e., "your code") is not the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.
console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);
/* Outputs ...
THIS:
{}
GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
DataView: [Function: DataView],
global: [Circular],
process:
{ EventEmitter: [Function: EventEmitter],
title: 'node',
assert: [Function],
version: 'v0.6.5',
_tickCallback: [Function],
moduleLoadList:
[ 'Binding evals',
'Binding natives',
'NativeModule events',
'NativeModule buffer',
'Binding buffer',
'NativeModule assert',
'NativeModule util',
'NativeModule path',
'NativeModule module',
'NativeModule fs',
'Binding fs',
'Binding constants',
'NativeModule stream',
'NativeModule console',
'Binding tty_wrap',
'NativeModule tty',
'NativeModule net',
'NativeModule timers',
'Binding timer_wrap',
'NativeModule _linklist' ],
versions:
{ node: '0.6.5',
v8: '3.6.6.11',
ares: '1.7.5-DEV',
uv: '0.6',
openssl: '0.9.8n' },
nextTick: [Function],
stdout: [Getter],
arch: 'x64',
stderr: [Getter],
platform: 'darwin',
argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
stdin: [Getter],
env:
{ TERM_PROGRAM: 'iTerm.app',
'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
TERM: 'xterm',
SHELL: '/bin/bash',
TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
USER: 'ddopson',
COMMAND_MODE: 'unix2003',
SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
__CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
PWD: '/workspace/zd/zgap/darwin-js',
LANG: 'en_US.UTF-8',
ITERM_PROFILE: 'Default',
SHLVL: '1',
COLORFGBG: '7;0',
HOME: '/Users/ddopson',
ITERM_SESSION_ID: 'w0t0p0',
LOGNAME: 'ddopson',
DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
OLDPWD: '/workspace/zd/zgap/darwin-js/external',
_: './index.js' },
openStdin: [Function],
exit: [Function],
pid: 10321,
features:
{ debug: false,
uv: true,
ipv6: true,
tls_npn: false,
tls_sni: true,
tls: true },
kill: [Function],
execPath: '/usr/local/bin/node',
addListener: [Function],
_needTickCallback: [Function],
on: [Function],
removeListener: [Function],
reallyExit: [Function],
chdir: [Function],
debug: [Function],
error: [Function],
cwd: [Function],
watchFile: [Function],
umask: [Function],
getuid: [Function],
unwatchFile: [Function],
mixin: [Function],
setuid: [Function],
setgid: [Function],
createChildProcess: [Function],
getgid: [Function],
inherits: [Function],
_kill: [Function],
_byteLength: [Function],
mainModule:
{ id: '.',
exports: {},
parent: null,
filename: '/workspace/zd/zgap/darwin-js/index.js',
loaded: false,
exited: false,
children: [],
paths: [Object] },
_debugProcess: [Function],
dlopen: [Function],
uptime: [Function],
memoryUsage: [Function],
uvCounters: [Function],
binding: [Function] },
GLOBAL: [Circular],
root: [Circular],
Buffer:
{ [Function: Buffer]
poolSize: 8192,
isBuffer: [Function: isBuffer],
byteLength: [Function],
_charsWritten: 8 },
setTimeout: [Function],
setInterval: [Function],
clearTimeout: [Function],
clearInterval: [Function],
console: [Getter],
window: [Circular],
navigator: {} }
*/
** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');
. Yes, you do that in every single file that uses Underscore.js, just like how in Java you do import com.foo.bar;
. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. It is mildly annoying, but a good thing. .... That's the preaching.
There is an exception to every rule. I have had precisely exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "configuration" files which were basically JSON, but were "written in JavaScript" to allow a bit more flexibility. Such configuration files had no 'require' statements, but I wanted them to have access to Underscore.js (the entire system was predicated on Underscore.js and Underscore.js templates), so before evaluating the "configuration", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "I get tired of typing 'require', so I want to break with the convention".
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016
Step 1: Right button mouse > Select "Edit Top 200 Rows"
Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)
Step 3: Modify the query
Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)
I've been researching this very same problem and couldn't find a decent solution other than having the div with the image as background and the img tag inside of it with visibility none or something like this.
One thing I might add is that you should add a background-size: cover
to the div, so that your image fills the background by clipping it's excess.
This is the simplest query to retrive all Columns and Tables
SELECT * FROM information_schema.`COLUMNS` C WHERE TABLE_SCHEMA = 'YOUR_DATABASE'
All the tables or those with specific string in name could be searched via Search tab in phpMyAdmin.
Have Nice Query... \^.^/
You need to use dynamic SQL to achieve this; something like:
DECLARE
TYPE cur_type IS REF CURSOR;
CURSOR client_cur IS
SELECT DISTING username
FROM all_users
WHERE length(username) = 3;
emails_cur cur_type;
l_cur_string VARCHAR2(128);
l_email_id <type>;
l_name <type>;
BEGIN
FOR client IN client_cur LOOP
dbms_output.put_line('Client is '|| client.username);
l_cur_string := 'SELECT id, name FROM '
|| client.username || '.org';
OPEN emails_cur FOR l_cur_string;
LOOP
FETCH emails_cur INTO l_email_id, l_name;
EXIT WHEN emails_cur%NOTFOUND;
dbms_output.put_line('Org id is ' || l_email_id
|| ' org name ' || l_name);
END LOOP;
CLOSE emails_cur;
END LOOP;
END;
/
Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR
and an example.
Edited to make the inner cursor query a string variable.
When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
def add(a,b):
return a + b
you would call the function like this:
add(3,5)
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
answer = add(4,7)
Which would set the variable answer equal to 11 in this case.
Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method
setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'
import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))
Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499
So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.
The solution is that you should uncheck (deactivate) option "Run only if user is logged on".
After that change, it starts to work on my machine.
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
On express 3 you can use directly res.json({foo:bar})
res.json({ msgId: msg.fileName })
See the documentation
Josh is correct but he left out one variation:
ALTER ROLE <role_name> IN DATABASE <db_name> SET search_path TO schema1,schema2;
Set the search path for the user, in one particular database.
You should never look to override certificate validation in code! If you need to do testing, use an internal/test CA and install the CA root certificate on the device or emulator. You can use BurpSuite or Charles Proxy if you don't know how to setup a CA.
You can use margin. See the example:
li{
margin: 10px 0;
}
This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "
This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.
Maybe using the TOR network may help you do your job.
Fair warning:
element.onclick()
does not behave as expected. It only runs the code within onclick="" attribute
, but does not trigger default behavior.
I had similar issue with radio button not setting to checked, even though onclick
custom function was running fine. Had to add radio.checked = "true";
to set it. Probably the same goes and for other elements (after a.onclick()
there should be also window.location.href = "url";
)
I agree that StringTokenizer is overkill here. Actually I tried out the suggestions above and took the time.
My test was fairly simple: create a StringBuilder with about a million characters, convert it to a String, and traverse each of them with charAt() / after converting to a char array / with a CharacterIterator a thousand times (of course making sure to do something on the string so the compiler can't optimize away the whole loop :-) ).
The result on my 2.6 GHz Powerbook (that's a mac :-) ) and JDK 1.5:
As the results are significantly different, the most straightforward way also seems to be the fastest one. Interestingly, charAt() of a StringBuilder seems to be slightly slower than the one of String.
BTW I suggest not to use CharacterIterator as I consider its abuse of the '\uFFFF' character as "end of iteration" a really awful hack. In big projects there's always two guys that use the same kind of hack for two different purposes and the code crashes really mysteriously.
Here's one of the tests:
int count = 1000;
...
System.out.println("Test 1: charAt + String");
long t = System.currentTimeMillis();
int sum=0;
for (int i=0; i<count; i++) {
int len = str.length();
for (int j=0; j<len; j++) {
if (str.charAt(j) == 'b')
sum = sum + 1;
}
}
t = System.currentTimeMillis()-t;
System.out.println("result: "+ sum + " after " + t + "msec");
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
You need the Apache Commons Codec library 1.4 or above in your classpath. This library contains Base64 implementation.
I haven't studied yet, when Maven does which look-up, but to get stable and reproducible builds, I strongly recommend not to access Maven Respositories directly but to use a Maven Repository Manager such as Nexus.
Here is the tutorial how to set up your settings file:
http://books.sonatype.com/nexus-book/reference/maven-sect-single-group.html
declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'
Sed is a little ugly, you could do it elegantly like so:
hendry@i7 tmp$ cat foo
bar
candy
car
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done
barbar
candybar
carbar
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.
First, get hostname and port number by typing a command lsnrctl status
on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521
Second, enter the below command with your hostname and port number:
sqlplus username/password@HostName:Port Number/PluggableDatabaseName.
For example:
sqlplus hr/[email protected]:1521/ORCLPDB.
For Web API 2, you can implement IHttpActionResult
. Here's mine:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
class FileResult : IHttpActionResult
{
private readonly string _filePath;
private readonly string _contentType;
public FileResult(string filePath, string contentType = null)
{
if (filePath == null) throw new ArgumentNullException("filePath");
_filePath = filePath;
_contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(_filePath))
};
var contentType = _contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(_filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return Task.FromResult(response);
}
}
Then something like this in your controller:
[Route("Images/{*imagePath}")]
public IHttpActionResult GetImage(string imagePath)
{
var serverPath = Path.Combine(_rootPath, imagePath);
var fileInfo = new FileInfo(serverPath);
return !fileInfo.Exists
? (IHttpActionResult) NotFound()
: new FileResult(fileInfo.FullName);
}
And here's one way you can tell IIS to ignore requests with an extension so that the request will make it to the controller:
<!-- web.config -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).
In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!
As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.
import Tkinter as tk
class Window(tk.Frame):
def __init__(self, master=None, view=None ):
tk.Frame.__init__( self, master )
self.view_ = view
""" Setup window linking it to the view... """
class GuiView( MyViewSuperClass ):
def open( self ):
self.tkRoot_ = tk.Tk()
self.window_ = Window( master=None, view=self )
self.window_.pack()
self.refresh()
self.onOpen()
self.tkRoot_.mainloop()
def onOpen( self ):
""" Do some initial tasks... """
def refresh( self ):
self.tkRoot_.update()
Use double quotation marks.
string foo = @"this ""word"" is escaped";
There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).
public class TheClass {
private int theField= 42;
public static void main(String[] args) throws Exception {
TheClass c= new TheClass();
System.out.println(c.getClass().getDeclaredField("theField").get(c));
}
}
MacOS is different, there is two way to solve this problem with sed in mac
first ,use \'$'\n''
replace \n
, it can work in MacOS:
sed 's/,/\'$'\n''/g' file
the second, just use an empty line:
sed 's/,/\
/g' file
Ps. Pay attention the range separated by '
the third, use gnu-sed replace the mac-sed
Here using Hive warehouse dir you can export data instead of Hive table. first give hive warehouse path and after local path where you want to store the .csv file For this command is bellow :-
hadoop fs -cat /user/hdusr/warehouse/HiveDb/tableName/* > /users/hadoop/test/nilesh/sample.csv
I found my answer.
<?php
$profpic = "bg.jpg";
?>
<html>
<head>
<style type="text/css">
body {
background-image: url('<?php echo $profpic;?>');
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>
References are cleaner and easier to use, and they do a better job of hiding information. References cannot be reassigned, however. If you need to point first to one object and then to another, you must use a pointer. References cannot be null, so if any chance exists that the object in question might be null, you must not use a reference. You must use a pointer. If you want to handle object manipulation on your own i.e if you want to allocate memory space for an object on the Heap rather on the Stack you must use Pointer
int *pInt = new int; // allocates *pInt on the Heap
This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:
First, create a duplicate column with a temporary name:
alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;
Next, get the name of your primary key constraint:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';
Now try drop the primary key constraint for your column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..
Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
commit;
Finally, add the FK constraints back in:
alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..
El Fin!
You can also use case then like this:
UPDATE table
SET ID = case
when ID = 2555 then 111111259
when ID = 2724 then 111111261
when ID = 2021 then 111111263
when ID = 2017 then 111111264
else ID
end
From this post, try this javascript:
function removeRow(id) {
var tr = document.getElementById(id);
if (tr) {
if (tr.nodeName == 'TR') {
var tbl = tr; // Look up the hierarchy for TABLE
while (tbl != document && tbl.nodeName != 'TABLE') {
tbl = tbl.parentNode;
}
if (tbl && tbl.nodeName == 'TABLE') {
while (tr.hasChildNodes()) {
tr.removeChild( tr.lastChild );
}
tr.parentNode.removeChild( tr );
}
} else {
alert( 'Specified document element is not a TR. id=' + id );
}
} else {
alert( 'Specified document element is not found. id=' + id );
}
}
I tried this javascript in a test page and it worked for me in Firefox.
algorithm: procedure/formula for solving a problem
How do analyze algorithms and how can we compare algorithms against each other?
example: you and a friend are asked to create a function to sum the numbers from 0 to N. You come up with f(x) and your friend comes up with g(x). Both functions have the same result, but a different algorithm. In order to objectively compare the efficiency of the algorithms we use Big-O notation.
Big-O notation: describes how quickly runtime will grow relative to the input as the input get arbitrarily large.
3 key takeaways:
Space complexity: aside from time complexity, we also care about space complexity (how much memory/space an algorithm uses). Instead of checking the time of operations, we check the size of the allocation of memory.
Edit Answer of @rolnad :-Remove White space from name
<color name="Black">#000000</color>
<color name="Gunmetal">#2C3539</color>
<color name="Midnight">#2B1B17</color>
<color name="Charcoal">#34282C</color>
<color name="DarkSlateGrey">#25383C</color>
<color name="Oil">#3B3131</color>
<color name="BlackCat">#413839</color>
<color name="BlackEel">#463E3F</color>
<color name="BlackCow">#4C4646</color>
<color name="GrayWolf">#504A4B</color>
<color name="VampireGray">#565051</color>
<color name="GrayDolphin">#5C5858</color>
<color name="CarbonGray">#625D5D</color>
<color name="AshGray">#666362</color>
<color name="CloudyGray">#6D6968</color>
<color name="SmokeyGray">#726E6D</color>
<color name="Gray">#736F6E</color>
<color name="Granite">#837E7C</color>
<color name="BattleshipGray">#848482</color>
<color name="GrayCloud">#B6B6B4</color>
<color name="GrayGoose">#D1D0CE</color>
<color name="Platinum">#E5E4E2</color>
<color name="MetallicSilver">#BCC6CC</color>
<color name="BlueGray">#98AFC7</color>
<color name="LightSlateGray">#6D7B8D</color>
<color name="SlateGray">#657383</color>
<color name="JetGray">#616D7E</color>
<color name="MistBlue">#646D7E</color>
<color name="MarbleBlue">#566D7E</color>
<color name="SteelBlue">#4863A0</color>
<color name="BlueJay">#2B547E</color>
<color name="DarkSlateBlue">#2B3856</color>
<color name="MidnightBlue">#151B54</color>
<color name="NavyBlue">#000080</color>
<color name="BlueWhale">#342D7E</color>
<color name="LapisBlue">#15317E</color>
<color name="EarthBlue">#0000A0</color>
<color name="CobaltBlue">#0020C2</color>
<color name="BlueberryBlue">#0041C2</color>
<color name="SapphireBlue">#2554C7</color>
<color name="BlueEyes">#1569C7</color>
<color name="RoyalBlue">#2B60DE</color>
<color name="BlueOrchid">#1F45FC</color>
<color name="BlueLotus">#6960EC</color>
<color name="LightSlateBlue">#736AFF</color>
<color name="Slate_Blue">#357EC7</color>
<color name="SilkBlue">#488AC7</color>
<color name="BlueIvy">#3090C7</color>
<color name="BlueKoi">#659EC7</color>
<color name="ColumbiaBlue">#87AFC7</color>
<color name="BabyBlue">#95B9C7</color>
<color name="LightSteelBlue">#728FCE</color>
<color name="OceanBlue">#2B65EC</color>
<color name="BlueRibbon">#306EFF</color>
<color name="BlueDress">#157DEC</color>
<color name="DodgerBlue">#1589FF</color>
<color name="Cornflower_Blue">#6495ED</color>
<color name="ButterflyBlue">#38ACEC</color>
<color name="Iceberg">#56A5EC</color>
<color name="CrystalBlue">#5CB3FF</color>
<color name="DeepSkyBlue">#3BB9FF</color>
<color name="DenimBlue">#79BAEC</color>
<color name="LightSkyBlue">#82CAFA</color>
<color name="SkyBlue">#82CAFF</color>
<color name="JeansBlue">#A0CFEC</color>
<color name="BlueAngel">#B7CEEC</color>
<color name="PastelBlue">#B4CFEC</color>
<color name="SeaBlue">#C2DFFF</color>
<color name="PowderBlue">#C6DEFF</color>
<color name="CoralBlue">#AFDCEC</color>
<color name="LightBlue">#ADDFFF</color>
<color name="RobinEggBlue">#BDEDFF</color>
<color name="PaleBlueLily">#CFECEC</color>
<color name="LightCyan">#E0FFFF</color>
<color name="Water">#EBF4FA</color>
<color name="AliceBlue">#F0F8FF</color>
<color name="Azure">#F0FFFF</color>
<color name="LightSlate">#CCFFFF</color>
<color name="LightAquamarine">#93FFE8</color>
<color name="ElectricBlue">#9AFEFF</color>
<color name="Aquamarine">#7FFFD4</color>
<color name="CyanorAqua">#00FFFF</color>
<color name="TronBlue">#7DFDFE</color>
<color name="BlueZircon">#57FEFF</color>
<color name="BlueLagoon">#8EEBEC</color>
<color name="Celeste">#50EBEC</color>
<color name="BlueDiamond">#4EE2EC</color>
<color name="TiffanyBlue">#81D8D0</color>
<color name="CyanOpaque">#92C7C7</color>
<color name="BlueHosta">#77BFC7</color>
<color name="NorthernLightsBlue">#78C7C7</color>
<color name="MediumTurquoise">#48CCCD</color>
<color name="Turquoise">#43C6DB</color>
<color name="Jellyfish">#46C7C7</color>
<color name="MascawBlueGreen">#43BFC7</color>
<color name="LightSeaGreen">#3EA99F</color>
<color name="DarkTurquoise">#3B9C9C</color>
<color name="SeaTurtleGreen">#438D80</color>
<color name="MediumAquamarine">#348781</color>
<color name="GreenishBlue">#307D7E</color>
<color name="GrayishTurquoise">#5E7D7E</color>
<color name="BeetleGreen">#4C787E</color>
<color name="Teal">#008080</color>
<color name="SeaGreen">#4E8975</color>
<color name="CamouflageGreen">#78866B</color>
<color name="HazelGreen">#617C58</color>
<color name="VenomGreen">#728C00</color>
<color name="FernGreen">#667C26</color>
<color name="DarkForrestGreen">#254117</color>
<color name="MediumSeaGreen">#306754</color>
<color name="MediumForestGreen">#347235</color>
<color name="SeaweedGreen">#437C17</color>
<color name="PineGreen">#387C44</color>
<color name="JungleGreen">#347C2C</color>
<color name="ShamrockGreen">#347C17</color>
<color name="MediumSpringGreen">#348017</color>
<color name="ForestGreen">#4E9258</color>
<color name="GreenOnion">#6AA121</color>
<color name="SpringGreen">#4AA02C</color>
<color name="LimeGreen">#41A317</color>
<color name="CloverGreen">#3EA055</color>
<color name="GreenSnake">#6CBB3C</color>
<color name="AlienGreen">#6CC417</color>
<color name="GreenApple">#4CC417</color>
<color name="YellowGreen">#52D017</color>
<color name="KellyGreen">#4CC552</color>
<color name="ZombieGreen">#54C571</color>
<color name="FrogGreen">#99C68E</color>
<color name="GreenPeas">#89C35C</color>
<color name="DollarBillGreen">#85BB65</color>
<color name="DarkSeaGreen">#8BB381</color>
<color name="IguanaGreen">#9CB071</color>
<color name="AvocadoGreen">#B2C248</color>
<color name="PistachioGreen">#9DC209</color>
<color name="SaladGreen">#A1C935</color>
<color name="HummingbirdGreen">#7FE817</color>
<color name="NebulaGreen">#59E817</color>
<color name="StoplightGoGreen">#57E964</color>
<color name="AlgaeGreen">#64E986</color>
<color name="JadeGreen">#5EFB6E</color>
<color name="Green">#00FF00</color>
<color name="EmeraldGreen">#5FFB17</color>
<color name="LawnGreen">#87F717</color>
<color name="Chartreuse">#8AFB17</color>
<color name="DragonGreen">#6AFB92</color>
<color name="Mintgreen">#98FF98</color>
<color name="GreenThumb">#B5EAAA</color>
<color name="LightJade">#C3FDB8</color>
<color name="TeaGreen">#CCFB5D</color>
<color name="GreenYellow">#B1FB17</color>
<color name="SlimeGreen">#BCE954</color>
<color name="Goldenrod">#EDDA74</color>
<color name="HarvestGold">#EDE275</color>
<color name="SunYellow">#FFE87C</color>
<color name="Yellow">#FFFF00</color>
<color name="CornYellow">#FFF380</color>
<color name="Parchment">#FFFFC2</color>
<color name="Cream">#FFFFCC</color>
<color name="LemonChiffon">#FFF8C6</color>
<color name="Cornsilk">#FFF8DC</color>
<color name="Beige">#F5F5DC</color>
<color name="AntiqueWhite">#FAEBD7</color>
<color name="BlanchedAlmond">#FFEBCD</color>
<color name="Vanilla">#F3E5AB</color>
<color name="TanBrown">#ECE5B6</color>
<color name="Peach">#FFE5B4</color>
<color name="Mustard">#FFDB58</color>
<color name="RubberDuckyYellow">#FFD801</color>
<color name="BrightGold">#FDD017</color>
<color name="Goldenbrown">#EAC117</color>
<color name="MacaroniandCheese">#F2BB66</color>
<color name="Saffron">#FBB917</color>
<color name="Beer">#FBB117</color>
<color name="Cantaloupe">#FFA62F</color>
<color name="BeeYellow">#E9AB17</color>
<color name="BrownSugar">#E2A76F</color>
<color name="BurlyWood">#DEB887</color>
<color name="DeepPeach">#FFCBA4</color>
<color name="GingerBrown">#C9BE62</color>
<color name="SchoolBusYellow">#E8A317</color>
<color name="SandyBrown">#EE9A4D</color>
<color name="FallLeafBrown">#C8B560</color>
<color name="Gold">#D4A017</color>
<color name="Sand">#C2B280</color>
<color name="CookieBrown">#C7A317</color>
<color name="Caramel">#C68E17</color>
<color name="Brass">#B5A642</color>
<color name="Khaki">#ADA96E</color>
<color name="Camelbrown">#C19A6B</color>
<color name="Bronze">#CD7F32</color>
<color name="TigerOrange">#C88141</color>
<color name="Cinnamon">#C58917</color>
<color name="DarkGoldenrod">#AF7817</color>
<color name="Copper">#B87333</color>
<color name="Wood">#966F33</color>
<color name="OakBrown">#806517</color>
<color name="Moccasin">#827839</color>
<color name="ArmyBrown">#827B60</color>
<color name="Sandstone">#786D5F</color>
<color name="Mocha">#493D26</color>
<color name="Taupe">#483C32</color>
<color name="Coffee">#6F4E37</color>
<color name="BrownBear">#835C3B</color>
<color name="RedDirt">#7F5217</color>
<color name="Sepia">#7F462C</color>
<color name="OrangeSalmon">#C47451</color>
<color name="Rust">#C36241</color>
<color name="RedFox">#C35817</color>
<color name="Chocolate">#C85A17</color>
<color name="Sedona">#CC6600</color>
<color name="PapayaOrange">#E56717</color>
<color name="HalloweenOrange">#E66C2C</color>
<color name="PumpkinOrange">#F87217</color>
<color name="ConstructionConeOrange">#F87431</color>
<color name="SunriseOrange">#E67451</color>
<color name="MangoOrange">#FF8040</color>
<color name="DarkOrange">#F88017</color>
<color name="Coral">#FF7F50</color>
<color name="BasketBallOrange">#F88158</color>
<color name="LightSalmon">#F9966B</color>
<color name="Tangerine">#E78A61</color>
<color name="DarkSalmon">#E18B6B</color>
<color name="LightCoral">#E77471</color>
<color name="BeanRed">#F75D59</color>
<color name="ValentineRed">#E55451</color>
<color name="ShockingOrange">#E55B3C</color>
<color name="Red">#FF0000</color>
<color name="Scarlet">#FF2400</color>
<color name="RubyRed">#F62217</color>
<color name="FerrariRed">#F70D1A</color>
<color name="FireEngineRed">#F62817</color>
<color name="LavaRed">#E42217</color>
<color name="LoveRed">#E41B17</color>
<color name="Grapefruit">#DC381F</color>
<color name="ChestnutRed">#C34A2C</color>
<color name="CherryRed">#C24641</color>
<color name="Mahogany">#C04000</color>
<color name="ChilliPepper">#C11B17</color>
<color name="Cranberry">#9F000F</color>
<color name="RedWine">#990012</color>
<color name="Burgundy">#8C001A</color>
<color name="BloodRed">#7E3517</color>
<color name="Sienna">#8A4117</color>
<color name="Sangria">#7E3817</color>
<color name="Firebrick">#800517</color>
<color name="Maroon">#810541</color>
<color name="PlumPie">#7D0541</color>
<color name="VelvetMaroon">#7E354D</color>
<color name="PlumVelvet">#7D0552</color>
<color name="RosyFinch">#7F4E52</color>
<color name="Puce">#7F5A58</color>
<color name="DullPurple">#7F525D</color>
<color name="RosyBrown">#B38481</color>
<color name="KhakiRose">#C5908E</color>
<color name="PinkBow">#C48189</color>
<color name="LipstickPink">#C48793</color>
<color name="Rose">#E8ADAA</color>
<color name="DesertSand">#EDC9AF</color>
<color name="PigPink">#FDD7E4</color>
<color name="CottonCandy">#FCDFFF</color>
<color name="PinkBubblegum">#FFDFDD</color>
<color name="MistyRose">#FBBBB9</color>
<color name="Pink">#FAAFBE</color>
<color name="LightPink">#FAAFBA</color>
<color name="FlamingoPink">#F9A7B0</color>
<color name="PinkRose">#E7A1B0</color>
<color name="PinkDaisy">#E799A3</color>
<color name="CadillacPink">#E38AAE</color>
<color name="CarnationPink">#F778A1</color>
<color name="BlushRed">#E56E94</color>
<color name="HotPink">#F660AB</color>
<color name="WatermelonPink">#FC6C85</color>
<color name="VioletRed">#F6358A</color>
<color name="DeepPink">#F52887</color>
<color name="PinkCupcake">#E45E9D</color>
<color name="PinkLemonade">#E4287C</color>
<color name="NeonPink">#F535AA</color>
<color name="Magenta">#FF00FF</color>
<color name="DimorphothecaMagenta">#E3319D</color>
<color name="BrightNeonPink">#F433FF</color>
<color name="PaleVioletRed">#D16587</color>
<color name="TulipPink">#C25A7C</color>
<color name="MediumVioletRed">#CA226B</color>
<color name="RoguePink">#C12869</color>
<color name="BurntPink">#C12267</color>
<color name="BashfulPink">#C25283</color>
<color name="Carnation_Pink">#C12283</color>
<color name="Plum">#B93B8F</color>
<color name="ViolaPurple">#7E587E</color>
<color name="PurpleIris">#571B7E</color>
<color name="PlumPurple">#583759</color>
<color name="Indigo">#4B0082</color>
<color name="PurpleMonster">#461B7E</color>
<color name="PurpleHaze">#4E387E</color>
<color name="Eggplant">#614051</color>
<color name="Grape">#5E5A80</color>
<color name="PurpleJam">#6A287E</color>
<color name="DarkOrchid">#7D1B7E</color>
<color name="PurpleFlower">#A74AC7</color>
<color name="MediumOrchid">#B048B5</color>
<color name="PurpleAmethyst">#6C2DC7</color>
<color name="DarkViolet">#842DCE</color>
<color name="Violet">#8D38C9</color>
<color name="PurpleSageBush">#7A5DC7</color>
<color name="LovelyPurple">#7F38EC</color>
<color name="Purple">#8E35EF</color>
<color name="AztechPurple">#893BFF</color>
<color name="MediumPurple">#8467D7</color>
<color name="JasminePurple">#A23BEC</color>
<color name="PurpleDaffodil">#B041FF</color>
<color name="TyrianPurple">#C45AEC</color>
<color name="CrocusPurple">#9172EC</color>
<color name="PurpleMimosa">#9E7BFF</color>
<color name="HeliotropePurple">#D462FF</color>
<color name="Crimson">#E238EC</color>
<color name="PurpleDragon">#C38EC7</color>
<color name="Lilac">#C8A2C8</color>
<color name="BlushPink">#E6A9EC</color>
<color name="Mauve">#E0B0FF</color>
<color name="WiseriaPurple">#C6AEC7</color>
<color name="BlossomPink">#F9B7FF</color>
<color name="Thistle">#D2B9D3</color>
<color name="Periwinkle">#E9CFEC</color>
<color name="LavenderPinocchio">#EBDDE2</color>
<color name="Lavender">#E3E4FA</color>
<color name="Pearl">#FDEEF4</color>
<color name="SeaShell">#FFF5EE</color>
<color name="MilkWhite">#FEFCFF</color>
<color name="White">#FFFFFF</color>
What I found is that if another app is dialog type and allows touches to be sent to background app then almost any background app will crash with this error. I think we need to check every time a transaction is performed if the instance was saved or restored.
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
import java.util.Iterator;
import android.database.Cursor;
public class IterableCursor implements Iterable<Cursor>, Iterator<Cursor> {
Cursor cursor;
int toVisit;
public IterableCursor(Cursor cursor) {
this.cursor = cursor;
toVisit = cursor.getCount();
}
public Iterator<Cursor> iterator() {
cursor.moveToPosition(-1);
return this;
}
public boolean hasNext() {
return toVisit>0;
}
public Cursor next() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// }
cursor.moveToNext();
toVisit--;
return cursor;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Example code:
static void listAllPhones(Context context) {
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
for (Cursor phone : new IterableCursor(phones)) {
String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("name=" + name + " phoneNumber=" + phoneNumber);
}
phones.close();
}
I encountered this error while executing
SELECT * FROM table;
I traced the error to cursor.py line 195.
if args is not None:
if isinstance(args, dict):
nargs = {}
for key, item in args.items():
if isinstance(key, unicode):
key = key.encode(db.encoding)
nargs[key] = db.literal(item)
args = nargs
else:
args = tuple(map(db.literal, args))
try:
query = query % args
except TypeError as m:
raise ProgrammingError(str(m))
Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.
@kashesandr's solution worked for me but to hide horizontal scrollbar I added one more style for body. here is complete solution:
CSS
<style>
/* prevent layout shifting and hide horizontal scroll */
html {
width: 100vw;
}
body {
overflow-x: hidden;
}
</style>
JS
$(function(){
/**
* For multiple modals.
* Enables scrolling of 1st modal when 2nd modal is closed.
*/
$('.modal').on('hidden.bs.modal', function (event) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
}
});
});
JS Only Solution (when 2nd modal opened from 1st modal):
/**
* For multiple modals.
* Enables scrolling of 1st modal when 2nd modal is closed.
*/
$('.modal').on('hidden.bs.modal', function (event) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
$('body').css('padding-right', 17);
}
});
I wanted to replace only a part of the url, and with this solution, I don't have to pass the whole url, just the dynamic part:
public interface APIService {
@GET("users/{user_id}/playlists")
Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}
I tried to test performance using some of the various approaches listed. It's hard to make a rigorous test as many factors affect the result. I prepared two folders, one with 330 jpg files and another one with 330 png files. The average file size was 4Mb in both cases. Then I called getDimension for each file. Each implementation of getDimension method and each image type was tested separately (separate run). Here is the execution times that I got (first number for jpg, second number for png):
1(Apurv) - 101454ms, 84611ms
2(joinJpegs) - 471ms, N/A
3(Andrew Taylor) - 707ms, 68ms
4(Karussell, ImageIcon) - 106655ms, 100898ms
5(user350756) - 2649ms, 68ms
It's obvious that some methods load the whole file in order to get dimensions while others get by just reading some header information from the image. I think these numbers may be useful when application performance is critical.
Thank you everyone for the contribution to this thread - very helpful.
I'd like to give more codes to make it clear.
struct A
{
operator bool() const { return true; }
};
struct B
{
explicit operator bool() const { return true; }
};
int main()
{
A a1;
if (a1) cout << "true" << endl; // OK: A::operator bool()
bool na1 = a1; // OK: copy-initialization selects A::operator bool()
bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization
B b1;
if (b1) cout << "true" << endl; // OK: B::operator bool()
// bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}
I use Ude that is a C# port of Mozilla Universal Charset Detector. It is easy to use and gives some really good results.
<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="sample.mov">
<param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
<param name="autoplay" value="true">
<param name="loop" value="false">
<param name="controller" value="true">
<embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>
source is the first search result of the Google
Using auxiliary Result class to track if node is found and current k.
public class KthSmallestElementWithAux {
public int kthsmallest(TreeNode a, int k) {
TreeNode ans = kthsmallestRec(a, k).node;
if (ans != null) {
return ans.val;
} else {
return -1;
}
}
private Result kthsmallestRec(TreeNode a, int k) {
//Leaf node, do nothing and return
if (a == null) {
return new Result(k, null);
}
//Search left first
Result leftSearch = kthsmallestRec(a.left, k);
//We are done, no need to check right.
if (leftSearch.node != null) {
return leftSearch;
}
//Consider number of nodes found to the left
k = leftSearch.k;
//Check if current root is the solution before going right
k--;
if (k == 0) {
return new Result(k - 1, a);
}
//Check right
Result rightBalanced = kthsmallestRec(a.right, k);
//Consider all nodes found to the right
k = rightBalanced.k;
if (rightBalanced.node != null) {
return rightBalanced;
}
//No node found, recursion will continue at the higher level
return new Result(k, null);
}
private class Result {
private final int k;
private final TreeNode node;
Result(int max, TreeNode node) {
this.k = max;
this.node = node;
}
}
}
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document
for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');_x000D_
_x000D_
$postList.find('h1').on('click', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 5000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
While this example displays the usage of event delegation to capture events for a specific node (h1
in this case), and issue a callback for such events.
$postList = $('#post-list');_x000D_
_x000D_
$postList.on('click', 'h1', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
I had the same problem, all I did was to restart the command line and then navigate to the document folder rather than the user folder using the command '' cd documents '' . That should be all thats needed. Also ensure that the link is correct.
Use overflow-y: auto;
on the div.
Also, you should be setting the width as well.
The following syntax can also be used if the array is not named (just the array is passed to the template):
<ul id="luke_should_be_here">
{{this.1.name}}
</ul>
Appears you are having 'y' default to 1: An arrow function would be useful in 2020:
let x = (y = 1) => //insert operation with y here
Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.
Having a script or even a subsystem of an application for a network protocol debugging, it's desired to see what request-response pairs are exactly, including effective URLs, headers, payloads and the status. And it's typically impractical to instrument individual requests all over the place. At the same time there are performance considerations that suggest using single (or few specialised) requests.Session
, so the following assumes that the suggestion is followed.
requests
supports so called event hooks (as of 2.23 there's actually only response
hook). It's basically an event listener, and the event is emitted before returning control from requests.request
. At this moment both request and response are fully defined, hence can be logged.
import logging
import requests
logger = logging.getLogger('httplogger')
def logRoundtrip(response, *args, **kwargs):
extra = {'req': response.request, 'res': response}
logger.debug('HTTP roundtrip', extra=extra)
session = requests.Session()
session.hooks['response'].append(logRoundtrip)
That's basically how to log all HTTP round-trips of a session.
For the logging above to be useful there can be specialised logging formatter that understands req
and res
extras on logging records. It can look like this:
import textwrap
class HttpFormatter(logging.Formatter):
def _formatHeaders(self, d):
return '\n'.join(f'{k}: {v}' for k, v in d.items())
def formatMessage(self, record):
result = super().formatMessage(record)
if record.name == 'httplogger':
result += textwrap.dedent('''
---------------- request ----------------
{req.method} {req.url}
{reqhdrs}
{req.body}
---------------- response ----------------
{res.status_code} {res.reason} {res.url}
{reshdrs}
{res.text}
''').format(
req=record.req,
res=record.res,
reqhdrs=self._formatHeaders(record.req.headers),
reshdrs=self._formatHeaders(record.res.headers),
)
return result
formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[handler])
Now if you do some requests using the session
, like:
session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')
The output to stderr
will look as follows.
2020-05-14 22:10:13,224 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): httpbin.org:443
2020-05-14 22:10:13,695 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
2020-05-14 22:10:13,698 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/user-agent
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
None
---------------- response ----------------
200 OK https://httpbin.org/user-agent
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: application/json
Content-Length: 45
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"user-agent": "python-requests/2.23.0"
}
2020-05-14 22:10:13,814 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
2020-05-14 22:10:13,818 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/status/200
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
None
---------------- response ----------------
200 OK https://httpbin.org/status/200
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
When you have a lot of queries, having a simple UI and a way to filter records comes at handy. I'll show to use Chronologer for that (which I'm the author of).
First, the hook has be rewritten to produce records that logging
can serialise when sending over the wire. It can look like this:
def logRoundtrip(response, *args, **kwargs):
extra = {
'req': {
'method': response.request.method,
'url': response.request.url,
'headers': response.request.headers,
'body': response.request.body,
},
'res': {
'code': response.status_code,
'reason': response.reason,
'url': response.url,
'headers': response.headers,
'body': response.text
},
}
logger.debug('HTTP roundtrip', extra=extra)
session = requests.Session()
session.hooks['response'].append(logRoundtrip)
Second, logging configuration has to be adapted to use logging.handlers.HTTPHandler
(which Chronologer understands).
import logging.handlers
chrono = logging.handlers.HTTPHandler(
'localhost:8080', '/api/v1/record', 'POST', credentials=('logger', ''))
handlers = [logging.StreamHandler(), chrono]
logging.basicConfig(level=logging.DEBUG, handlers=handlers)
Finally, run Chronologer instance. e.g. using Docker:
docker run --rm -it -p 8080:8080 -v /tmp/db \
-e CHRONOLOGER_STORAGE_DSN=sqlite:////tmp/db/chrono.sqlite \
-e CHRONOLOGER_SECRET=example \
-e CHRONOLOGER_ROLES="basic-reader query-reader writer" \
saaj/chronologer \
python -m chronologer -e production serve -u www-data -g www-data -m
And run the requests again:
session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')
The stream handler will produce:
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org:443
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
DEBUG:httplogger:HTTP roundtrip
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
DEBUG:httplogger:HTTP roundtrip
Now if you open http://localhost:8080/ (use "logger" for username and empty password for the basic auth popup) and click "Open" button, you should see something like:
As David pointed out, I would go with KB in most cases.
php_value post_max_size 2K
Note: my form is simple, just a few text boxes, not long text.
(PHP shorthand for KB is K, as outlined here.)
cd <your project folder>
(where your angularjs's deployable code is there)
sudo npm install serve -g
serve
You can hit your page at
localhost:3000 or IPaddress:3000
There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.
You need to trick it back by telling it your browser is capable, something like,
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");
Since upgrading my typings to react 0.14.43 (I'm not sure exactly when this was introduced), the React.FormEvent type is now generic and this removes the need for a cast.
import React = require('react');
interface ITestState {
selectedValue: string;
}
export class Test extends React.Component<{}, ITestState> {
constructor() {
super();
this.state = { selectedValue: "A" };
}
change(event: React.FormEvent<HTMLSelectElement>) {
// No longer need to cast to any - hooray for react!
var safeSearchTypeValue: string = event.currentTarget.value;
console.log(safeSearchTypeValue); // in chrome => B
this.setState({
selectedValue: safeSearchTypeValue
});
}
render() {
return (
<div>
<label htmlFor="searchType">Safe</label>
<select className="form-control" id="searchType" onChange={ e => this.change(e) } value={ this.state.selectedValue }>
<option value="A">A</option>
<option value="B">B</option>
</select>
<h1>{this.state.selectedValue}</h1>
</div>
);
}
}
var angle = 0;
$('#button').on('click', function() {
angle += 90;
$('#image').css('transform','rotate(' + angle + 'deg)');
});
Try this code.
All of the prior solutions get at the point a little, however, they just don't copy everything over. I created a PHP function (albeit somewhat lengthy) that copies everything including tables, foreign keys, data, views, procedures, functions, triggers, and events. Here is the code:
/* This function takes the database connection, an existing database, and the new database and duplicates everything in the new database. */
function copyDatabase($c, $oldDB, $newDB) {
// creates the schema if it does not exist
$schema = "CREATE SCHEMA IF NOT EXISTS {$newDB};";
mysqli_query($c, $schema);
// selects the new schema
mysqli_select_db($c, $newDB);
// gets all tables in the old schema
$tables = "SELECT table_name
FROM information_schema.tables
WHERE table_schema = '{$oldDB}'
AND table_type = 'BASE TABLE'";
$results = mysqli_query($c, $tables);
// checks if any tables were returned and recreates them in the new schema, adds the foreign keys, and inserts the associated data
if (mysqli_num_rows($results) > 0) {
// recreates all tables first
while ($row = mysqli_fetch_array($results)) {
$table = "CREATE TABLE {$newDB}.{$row[0]} LIKE {$oldDB}.{$row[0]}";
mysqli_query($c, $table);
}
// resets the results to loop through again
mysqli_data_seek($results, 0);
// loops through each table to add foreign key and insert data
while ($row = mysqli_fetch_array($results)) {
// inserts the data into each table
$data = "INSERT IGNORE INTO {$newDB}.{$row[0]} SELECT * FROM {$oldDB}.{$row[0]}";
mysqli_query($c, $data);
// gets all foreign keys for a particular table in the old schema
$fks = "SELECT constraint_name, column_name, table_name, referenced_table_name, referenced_column_name
FROM information_schema.key_column_usage
WHERE referenced_table_name IS NOT NULL
AND table_schema = '{$oldDB}'
AND table_name = '{$row[0]}'";
$fkResults = mysqli_query($c, $fks);
// checks if any foreign keys were returned and recreates them in the new schema
// Note: ON UPDATE and ON DELETE are not pulled from the original so you would have to change this to your liking
if (mysqli_num_rows($fkResults) > 0) {
while ($fkRow = mysqli_fetch_array($fkResults)) {
$fkQuery = "ALTER TABLE {$newDB}.{$row[0]}
ADD CONSTRAINT {$fkRow[0]}
FOREIGN KEY ({$fkRow[1]}) REFERENCES {$newDB}.{$fkRow[3]}({$fkRow[1]})
ON UPDATE CASCADE
ON DELETE CASCADE;";
mysqli_query($c, $fkQuery);
}
}
}
}
// gets all views in the old schema
$views = "SHOW FULL TABLES IN {$oldDB} WHERE table_type LIKE 'VIEW'";
$results = mysqli_query($c, $views);
// checks if any views were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$view = "SHOW CREATE VIEW {$oldDB}.{$row[0]}";
$viewResults = mysqli_query($c, $view);
$viewRow = mysqli_fetch_array($viewResults);
mysqli_query($c, preg_replace("/CREATE(.*?)VIEW/", "CREATE VIEW", str_replace($oldDB, $newDB, $viewRow[1])));
}
}
// gets all triggers in the old schema
$triggers = "SELECT trigger_name, action_timing, event_manipulation, event_object_table, created
FROM information_schema.triggers
WHERE trigger_schema = '{$oldDB}'";
$results = mysqli_query($c, $triggers);
// checks if any triggers were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$trigger = "SHOW CREATE TRIGGER {$oldDB}.{$row[0]}";
$triggerResults = mysqli_query($c, $trigger);
$triggerRow = mysqli_fetch_array($triggerResults);
mysqli_query($c, str_replace($oldDB, $newDB, $triggerRow[2]));
}
}
// gets all procedures in the old schema
$procedures = "SHOW PROCEDURE STATUS WHERE db = '{$oldDB}'";
$results = mysqli_query($c, $procedures);
// checks if any procedures were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$procedure = "SHOW CREATE PROCEDURE {$oldDB}.{$row[1]}";
$procedureResults = mysqli_query($c, $procedure);
$procedureRow = mysqli_fetch_array($procedureResults);
mysqli_query($c, str_replace($oldDB, $newDB, $procedureRow[2]));
}
}
// gets all functions in the old schema
$functions = "SHOW FUNCTION STATUS WHERE db = '{$oldDB}'";
$results = mysqli_query($c, $functions);
// checks if any functions were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$function = "SHOW CREATE FUNCTION {$oldDB}.{$row[1]}";
$functionResults = mysqli_query($c, $function);
$functionRow = mysqli_fetch_array($functionResults);
mysqli_query($c, str_replace($oldDB, $newDB, $functionRow[2]));
}
}
// selects the old schema (a must for copying events)
mysqli_select_db($c, $oldDB);
// gets all events in the old schema
$query = "SHOW EVENTS
WHERE db = '{$oldDB}';";
$results = mysqli_query($c, $query);
// selects the new schema again
mysqli_select_db($c, $newDB);
// checks if any events were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$event = "SHOW CREATE EVENT {$oldDB}.{$row[1]}";
$eventResults = mysqli_query($c, $event);
$eventRow = mysqli_fetch_array($eventResults);
mysqli_query($c, str_replace($oldDB, $newDB, $eventRow[3]));
}
}
}
You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function
public static String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?
Keep up the good work !
The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source
You can use (char) System.in.read();
.
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
You have to construct a new string out of a byte array. The first element in your byteArray
should be 0x63
. If you want to add any more letters, make the byteArray
longer and add them to the next indices.
byte[] byteArray = new byte[1];
byteArray[0] = 0x63;
try {
System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO: Handle exception.
e.printStackTrace();
}
Note that specifying the encoding will eventually throw an UnsupportedEncodingException
and you must handle that accordingly.
Open Control Panel Administrative Tools Services Select Extended services tab
Find SQL Server(MSSQLSERVER) & SQL Server(SQLEXPRESS) Stop these services and Start again (from the start & stop button displayed above)
Done.
In Swift 3, 4, 5:
button.setTitle("Button Title", for: .normal)
Otherwise:
button.setTitle("Button Title", forState: UIControlState.Normal)
Also an @IBOutlet
has to declared for the button
.
Try the following css:
#innerbox
{
width:250px; /* or whatever width you want. */
max-width:250px; /* or whatever width you want. */
display: inline-block;
}
This makes the div take as little space as possible, and its width is defined by the css.
// Expanded answer
To make the buttons fixed widths do the following :
#innerbox input
{
width:150px; /* or whatever width you want. */
max-width:150px; /* or whatever width you want. */
}
However, you should be aware that as the size of the text changes, so does the space needed to display it. As such, it's natural that the containers need to expand. You should perhaps review what you are trying to do; and maybe have some predefined classes that you alter on the fly using javascript to ensure the content placement is perfect.
If the CSV file must be imported as part of a python program, then for simplicity and efficiency, you could use os.system
along the lines suggested by the following:
import os
cmd = """sqlite3 database.db <<< ".import input.csv mytable" """
rc = os.system(cmd)
print(rc)
The point is that by specifying the filename of the database, the data will automatically be saved, assuming there are no errors reading it.
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
. then a=7
is provided to post increment => 7 + 6 + 7 =20
and a =8
.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
.then a=7
is provided to post increment => 7 + 7 + 6 =20
and a =8
.
It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator".
If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $
symbol.
To answer your question, conditional operators replace simple if statements. An example is best:
var insurancePremium = age > 21 ? 100 : 200;
Instead of:
var insurancePremium;
if (age > 21) {
insurancePremium = 100;
} else {
insurancePremium = 200;
}
Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?
In your situation (for your example) it would be:
prompt> git add B
prompt> git commit
Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use
prompt> git reset A
or
prompt> git checkout HEAD -- A
to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).
Besides Manuel's way, you can still use the Manifest.
In Android Studio stable, you have to add the following 2 lines to application
in the AndroidManifest
file:
android:debuggable="true"
tools:ignore="HardcodedDebugMode"
The first one will enable debugging of signed APK, and the second one will prevent compile-time error.
After this, you can attach to the process via "Attach debugger to Android process" button.
If one installed boost on macOS via Homebrew, one is likely to see the installed boost version(s) with:
ls /usr/local/Cellar/boost*
I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.
class ReverseWordsInString{
public static String reverse(String s1){
int l = s1.length();
if (l>1)
return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
else
return(s1.substring(0));
}
public static void main(String[] args){
String st = "Hello My World!";
String r = "";
for (String word : st.split(" "))
r += " "+ reverse(word);
System.out.println("Reversed words in the given string: "+r.trim());
}
}
You can do this with html/css like this:
<body>
<div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
<iframe src="http: //www.google.com.tw" style="position:fixed;top:30px;bottom:0px;width:100%;"></iframe>
</body>
In my test the better performance is ENUM > MAP > SWITCH > IF/ELSE IF in Windows7.
import java.util.HashMap;
import java.util.Map;
public class StringsInSwitch {
public static void main(String[] args) {
String doSomething = null;
//METHOD_1 : SWITCH
long start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
switch (input) {
case "Hello World0":
doSomething = "Hello World0";
break;
case "Hello World1":
doSomething = "Hello World0";
break;
case "Hello World2":
doSomething = "Hello World0";
break;
case "Hello World3":
doSomething = "Hello World0";
break;
case "Hello World4":
doSomething = "Hello World0";
break;
case "Hello World5":
doSomething = "Hello World0";
break;
case "Hello World6":
doSomething = "Hello World0";
break;
case "Hello World7":
doSomething = "Hello World0";
break;
case "Hello World8":
doSomething = "Hello World0";
break;
case "Hello World9":
doSomething = "Hello World0";
break;
case "Hello World10":
doSomething = "Hello World0";
break;
case "Hello World11":
doSomething = "Hello World0";
break;
case "Hello World12":
doSomething = "Hello World0";
break;
case "Hello World13":
doSomething = "Hello World0";
break;
case "Hello World14":
doSomething = "Hello World0";
break;
case "Hello World15":
doSomething = "Hello World0";
break;
}
}
System.out.println("Time taken for String in Switch :"+ (System.currentTimeMillis() - start));
//METHOD_2 : IF/ELSE IF
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
if(input.equals("Hello World0")){
doSomething = "Hello World0";
} else if(input.equals("Hello World1")){
doSomething = "Hello World0";
} else if(input.equals("Hello World2")){
doSomething = "Hello World0";
} else if(input.equals("Hello World3")){
doSomething = "Hello World0";
} else if(input.equals("Hello World4")){
doSomething = "Hello World0";
} else if(input.equals("Hello World5")){
doSomething = "Hello World0";
} else if(input.equals("Hello World6")){
doSomething = "Hello World0";
} else if(input.equals("Hello World7")){
doSomething = "Hello World0";
} else if(input.equals("Hello World8")){
doSomething = "Hello World0";
} else if(input.equals("Hello World9")){
doSomething = "Hello World0";
} else if(input.equals("Hello World10")){
doSomething = "Hello World0";
} else if(input.equals("Hello World11")){
doSomething = "Hello World0";
} else if(input.equals("Hello World12")){
doSomething = "Hello World0";
} else if(input.equals("Hello World13")){
doSomething = "Hello World0";
} else if(input.equals("Hello World14")){
doSomething = "Hello World0";
} else if(input.equals("Hello World15")){
doSomething = "Hello World0";
}
}
System.out.println("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));
//METHOD_3 : MAP
//Create and build Map
Map<String, ExecutableClass> map = new HashMap<String, ExecutableClass>();
for (int i = 0; i <= 15; i++) {
String input = "Hello World" + (i & 0xF);
map.put(input, new ExecutableClass(){
public void execute(String doSomething){
doSomething = "Hello World0";
}
});
}
//Start test map
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
map.get(input).execute(doSomething);
}
System.out.println("Time taken for String in Map :"+ (System.currentTimeMillis() - start));
//METHOD_4 : ENUM (This doesn't use muliple string with space.)
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "HW" + (i & 0xF);
HelloWorld.valueOf(input).execute(doSomething);
}
System.out.println("Time taken for String in ENUM :"+ (System.currentTimeMillis() - start));
}
}
interface ExecutableClass
{
public void execute(String doSomething);
}
// Enum version
enum HelloWorld {
HW0("Hello World0"), HW1("Hello World1"), HW2("Hello World2"), HW3(
"Hello World3"), HW4("Hello World4"), HW5("Hello World5"), HW6(
"Hello World6"), HW7("Hello World7"), HW8("Hello World8"), HW9(
"Hello World9"), HW10("Hello World10"), HW11("Hello World11"), HW12(
"Hello World12"), HW13("Hello World13"), HW14("Hello World4"), HW15(
"Hello World15");
private String name = null;
private HelloWorld(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
doSomething = "Hello World0";
}
public static HelloWorld fromString(String input) {
for (HelloWorld hw : HelloWorld.values()) {
if (input.equals(hw.getName())) {
return hw;
}
}
return null;
}
}
//Enum version for betterment on coding format compare to interface ExecutableClass
enum HelloWorld1 {
HW0("Hello World0") {
public void execute(String doSomething){
doSomething = "Hello World0";
}
},
HW1("Hello World1"){
public void execute(String doSomething){
doSomething = "Hello World0";
}
};
private String name = null;
private HelloWorld1(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
// super call, nothing here
}
}
/*
* http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string
* https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10
* http://forums.xkcd.com/viewtopic.php?f=11&t=33524
*/
$result = If ($condition) {"true"} Else {"false"}
Everything else is incidental complexity and thus to be avoided.
For use in or as an expression, not just an assignment, wrap it in $()
, thus:
write-host $(If ($condition) {"true"} Else {"false"})
The basic intrinsic types (e.g. byte
, int
, string
, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.
So, a silly question (but I have to ask it...): is UploadedFile marked as a [DataContract]
? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].
Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)
A tremendous resource for WCF development is what we know in our shop as "the fish book": Programming WCF Services by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.
location.reload();
Does the trick.
<a ng-click="reload()">
$scope.reload = function()
{
location.reload();
}
No need for routes or anything just plain old js
The said method with highest up's by Laz is deprecated from version 4.3 onwards. Hence it would be better to user the Request Config Object and then build the HTTP Client
private CloseableHttpClient createHttpClient()
{
CloseableHttpClient httpClient;
CommonHelperFunctions helperFunctions = new CommonHelperFunctions();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(306);
cm.setDefaultMaxPerRoute(108);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(15000)
.setSocketTimeout(15000).build();
httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(requestConfig).build();
return httpClient;
}
The PoolingHttpClientConnectionManager is user to set the max default number of connections and the max number of conncetions per route. I have set it as 306 and 108 respectively. The default values will not be sufficient for most of the cases.
For setting Timeout: I have used the RequestConfig object. You can also set the property Connection Request Timeout for setting timeout for waiting for connection from Connection manager.
With CSS Shapes you can go one step further than just float text around a rectangular image.
You can actually wrap text such that it takes the shape of the edge of the image or polygon that you are wrapping it around.
.oval {_x000D_
width: 400px;_x000D_
height: 250px;_x000D_
color: #111;_x000D_
border-radius: 50%;_x000D_
text-align: center;_x000D_
font-size: 90px;_x000D_
float: left;_x000D_
shape-outside: ellipse();_x000D_
padding: 10px;_x000D_
background-color: MediumPurple;_x000D_
background-clip: content-box;_x000D_
}_x000D_
span {_x000D_
padding-top: 70px;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="oval"><span>PHP</span>_x000D_
</div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has_x000D_
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing_x000D_
software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley_x000D_
of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing_x000D_
Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy_x000D_
text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised_x000D_
in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
_x000D_
Also, here is a good list apart article on CSS Shapes
It might be related to corruption in Angular Packages or incompatibility of packages.
Please follow the below steps to solve the issue.
Update
ASP.NET Boilerplate suggests here to use yarn because npm has some problems. It is slow and can not consistently resolve dependencies, yarn solves those problems and it is compatible to npm as well.
"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".
So, try to change the code to:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = df.parse(startDateString);
Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws Exception {
String startDateString = "06/27/2007";
// This object can interpret strings representing dates in the format MM/dd/yyyy
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Convert from String to Date
Date startDate = df.parse(startDateString);
// Print the date, with the default formatting.
// Here, the important thing to note is that the parts of the date
// were correctly interpreted, such as day, month, year etc.
System.out.println("Date, with the default formatting: " + startDate);
// Once converted to a Date object, you can convert
// back to a String using any desired format.
String startDateString1 = df.format(startDate);
System.out.println("Date in format MM/dd/yyyy: " + startDateString1);
// Converting to String again, using an alternative format
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String startDateString2 = df2.format(startDate);
System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
}
}
Output:
Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007
Try using the downloadable DotNetVersionLister module (based on registry infos and some version-to-marketing-version lookup table).
Which would be used like this:
PS> Get-DotNetVersion -LocalHost -nosummary
ComputerName : localhost
>=4.x : 4.5.2
v4\Client : Installed
v4\Full : Installed
v3.5 : Installed
v3.0 : Installed
v2.0.50727 : Installed
v1.1.4322 : Not installed (no key)
Ping : True
Error :
Or like this if you just want to test it for some .NET framework >= 4.*:
PS> (Get-DotNetVersion -LocalHost -nosummary).">=4.x"
4.5.2
But it will not work (install/import) e.g. with PS v2.0 (Win 7, Win Server 2010 standard) due to incompatibility...
(You could skip reading this and use code below)
We had to work with PS 2.0 on some machines and could not install/import the above DotNetVersionLister.
On other machines we wanted to update (from PS 2.0) to PS 5.1 (which in turn needs .NET Framework >= 4.5) with the help of two company-custom Install-DotnetLatestCompany
and Install-PSLatestCompany
.
To guide admins nicely through the install/update process we would have to determine the .NET version in these functions on all machines and PS versions existing.
Thus we used also the below functions to determine them more safely in all environments...
So the following code and below (extracted) usage examples are useful here (based on other answers here):
function Get-DotNetVersionByFs {
<#
.SYNOPSIS
NOT RECOMMENDED - try using instead:
Get-DotNetVersion
from DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister),
but it is not usable/importable in PowerShell 2.0
Get-DotNetVersionByReg
reg(istry) based: (available herin as well) but it may return some wrong version or may not work reliably for versions > 4.5
(works in PSv2.0)
Get-DotNetVersionByFs (this):
f(ile) s(ystem) based: determines the latest installed .NET version based on $Env:windir\Microsoft.NET\Framework content
this is unreliable, e.g. if 4.0* is already installed some 4.5 update will overwrite content there without
renaming the folder
(works in PSv2.0)
.EXAMPLE
PS> Get-DotnetVersionByFs
4.0.30319
.EXAMPLE
PS> Get-DotnetVersionByFs -All
1.0.3705
1.1.4322
2.0.50727
3.0
3.5
4.0.30319
.NOTES
from https://stackoverflow.com/a/52078523/1915920
#>
[cmdletbinding()]
param(
[Switch]$All ## do not return only latest, but all installed
)
$list = ls $Env:windir\Microsoft.NET\Framework |
?{ $_.PSIsContainer -and $_.Name -match '^v\d.[\d\.]+' } |
%{ $_.Name.TrimStart('v') }
if ($All) { $list } else { $list | select -last 1 }
}
function Get-DotNetVersionByReg {
<#
.SYNOPSIS
NOT RECOMMENDED - try using instead:
Get-DotNetVersion
From DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister),
but it is not usable/importable in PowerShell 2.0.
Determines the latest installed .NET version based on registry infos under 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP'
.EXAMPLE
PS> Get-DotnetVersionByReg
4.5.51209
.EXAMPLE
PS> Get-DotnetVersionByReg -AllDetailed
PSChildName Version Release
----------- ------- -------
v2.0.50727 2.0.50727.5420
v3.0 3.0.30729.5420
Windows Communication Foundation 3.0.4506.5420
Windows Presentation Foundation 3.0.6920.5011
v3.5 3.5.30729.5420
Client 4.0.0.0
Client 4.5.51209 379893
Full 4.5.51209 379893
.NOTES
from https://stackoverflow.com/a/52078523/1915920
#>
[cmdletbinding()]
param(
[Switch]$AllDetailed ## do not return only latest, but all installed with more details
)
$Lookup = @{
378389 = [version]'4.5'
378675 = [version]'4.5.1'
378758 = [version]'4.5.1'
379893 = [version]'4.5.2'
393295 = [version]'4.6'
393297 = [version]'4.6'
394254 = [version]'4.6.1'
394271 = [version]'4.6.1'
394802 = [version]'4.6.2'
394806 = [version]'4.6.2'
460798 = [version]'4.7'
460805 = [version]'4.7'
461308 = [version]'4.7.1'
461310 = [version]'4.7.1'
461808 = [version]'4.7.2'
461814 = [version]'4.7.2'
}
$list = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -name Version, Release -EA 0 |
# For One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
Select-Object `
@{
name = ".NET Framework" ;
expression = {$_.PSChildName}},
@{ name = "Product" ;
expression = {$Lookup[$_.Release]}},
Version, Release
if ($AllDetailed) { $list | sort version } else { $list | sort version | select -last 1 | %{ $_.version } }
}
Example usage:
PS> Get-DotNetVersionByFs
4.0.30319
PS> Get-DotNetVersionByFs -All
1.0.3705
1.1.4322
2.0.50727
3.0
3.5
4.0.30319
PS> Get-DotNetVersionByReg
4.5.51209
PS> Get-DotNetVersionByReg -AllDetailed
.NET Framework Product Version Release
-------------- ------- ------- -------
v2.0.50727 2.0.50727.5420
v3.0 3.0.30729.5420
Windows Communication Foundation 3.0.4506.5420
Windows Presentation Foundation 3.0.6920.5011
v3.5 3.5.30729.5420
Client 4.0.0.0
Client 4.5.2 4.5.51209 379893
Full 4.5.2 4.5.51209 379893
I would go with Collections.emptyList()
if the returned list is not being modified in any way (as the list is immutable), otherwise I would go with option 2.
The benefit of Collections.emptyList()
is that the same static instance is returned each time and so there is not instance creation occurring for each call.
x=list()
def enter(n):
y=list()
for i in range(0,n):
y.append(int(input("Enter ")))
return y
for i in range(0,2):
x.insert(i,enter(2))
print (x)
here i made function to create 1-D array and inserted into another array as a array member. multiple 1-d array inside a an array, as the value of n and i changes u create multi dimensional arrays
Resetting the password will only solve the problem temporarily. From MySQL 5.7.4 to 5.7.10 (to encourage better security - see MySQL: Password Expiration Policy) the default default_password_lifetime
variable value is 360 (1 year-ish). For those versions, if you make no changes to this variable (or to individual user accounts) all passwords expire after 360 days.
So from a script you might get the message: "Your password has expired. To log in you must change it using a client that supports expired passwords."
To stop automatic password expiry, log in as root (mysql -u root -p
), then, for clients that automatically connect to the server (e.g. scripts.) change password expiration settings:
ALTER USER 'script'@'localhost' PASSWORD EXPIRE NEVER;
OR you can disable automatic password expiration for all users:
SET GLOBAL default_password_lifetime = 0;
As pointed out by Mertaydin in the comments, to make this permanent add the following line to a my.cnf
file MySQL reads on startup, under the [mysqld]
group of settings. The location of my.cnf
depends on your setup (e.g. Windows, or Homebrew on OS X, or an installer), and whether you want this per-user on Unix or global:
[mysqld]
default_password_lifetime = 0
(There may be other settings here too...)
See the MySQL docs on configuration files.
One other thing you can do is to go to your Document Outline, select the table view that your prototype cell is nested. Then on the Size Inspector, change your table view Row Height to your desired value and uncheck the Automatic box.
for higher precision. this format:
45 11.735N,004 34.281E
and this
45 23.623, 5 38.77
Another way to do something similar is with flexbox on a wrapper element, i.e.,
.row {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}
_x000D_
<div class="row">_x000D_
<div>Left</div>_x000D_
<div>Right</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
@duncan's solution above specifying new()
for the static type works also with interfaces:
interface MyType {
instanceMethod();
}
interface MyTypeStatic {
new():MyType;
staticMethod();
}
If you don't want your code to depend on other packages, you can always just write these functions:
perm = function(n, x) {
factorial(n) / factorial(n-x)
}
comb = function(n, x) {
factorial(n) / factorial(n-x) / factorial(x)
}
This happens because you put bracket of return
on the next line. That might be a common mistake if you write js without semicolons and use a style where you put opened braces on the next line.
Interpreter thinks that you return undefined and doesn't check your next line. That's the return
operator thing.
Put your opened bracket on the same line with the return
.
[attr.disabled]="valid == true ? true : null"
You have to use null
to remove attr from html element.
Use entrySet()
to iterate through Map
and need to access value and key:
Map<String, Person> hm = new HashMap<String, Person>();
hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));
Set<Map.Entry<String, Person>> set = hm.entrySet();
for (Map.Entry<String, Person> me : set) {
System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());
}
If you want just to iterate over keys
of map you can use keySet()
for(String key: map.keySet()) {
Person value = map.get(key);
}
If you just want to iterate over values
of map you can use values()
for(Person person: map.values()) {
}
<div class="w-100 d-lg-none mt-4"></div>
I created 4 cards and place this code between second and third card, try this.
I think the problem may be with the ownership to the folder so set it to the current user ownership
sudo chown -R your_login_name /path/to/folder
You can find the solution [here][1]
Make sure when you create a txt file you don't type in the name "name.txt", just type in "name". If you type "name.txt" Eclipse will see it as "name.txt.txt". This solved it for me. Also save the file in the src folder, not the folder were the .java resides, one folder up.
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
Here is some code to show this subtle difference:
// x is a method assigned to the object using "this"
var A = function () {
this.x = function () { alert('A'); };
};
A.prototype.updateX = function( value ) {
this.x = function() { alert( value ); }
};
var a1 = new A();
var a2 = new A();
a1.x(); // Displays 'A'
a2.x(); // Also displays 'A'
a1.updateX('Z');
a1.x(); // Displays 'Z'
a2.x(); // Still displays 'A'
// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () { alert('B'); };
B.prototype.updateX = function( value ) {
B.prototype.x = function() { alert( value ); }
}
var b1 = new B();
var b2 = new B();
b1.x(); // Displays 'B'
b2.x(); // Also displays 'B'
b1.updateX('Y');
b1.x(); // Displays 'Y'
b2.x(); // Also displays 'Y' because by using prototype we have changed it for all instances
As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.
Please Follow this process
First of all install git bash and create a repository on git
1) Go to working directory where the file exist which you want to push on remote and create .git folder by
$ git init
2) Add the files in your new local repository.
$ git add .
Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity
3) Commit the files that you've staged in your local repository.
$ git commit -m "First commit"**
4) after this go to git repository and copy remote URL
$ git remote add origin *remote repository URL
5)
$ git remote -v
Note: this will ask for user.email and user.name just put it as per config
6)
$ git push origin master
this will push whole committed code to FILE.git on repository
And I think we done
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
Cannot comment anymore but voted it up and wanted to let folks know that "
works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src="(.*)".*"
using the escaped version instead of double-quotes.
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).
If you want to see the difference as just the names of the files changed then use:
git diff --name-status <remote-branch> <local-branch>
,
else this would show all differences between the two branches:
git diff <remote-branch> <local-branch>
A trick to truncate that avoids a function call entirely is
var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2
To round a floating-point number to the nearest integer, use the addition/subtraction
trick. This works for numbers with absolute value < 2 ^ 51.
var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)
console.log(rounded); // 3
Note:
Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.
The magic number 6755399441055744.0
is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);
let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)
console.log("number floor ceil round trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
let f = x => (x).toString().padStart(6," ");
console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);
});
_x000D_
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED
, DOCUMENT_POSITION_PRECEDING
, and DOCUMENT_POSITION_FOLLOWING
.
Not supported in IE<=8.
Or you could try:
This worked for me.
jQuery('#grid').jqGrid('clearGridData');
jQuery('#grid').jqGrid('setGridParam', {data: dataToLoad});
jQuery('#grid').trigger('reloadGrid');
A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.
Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.
Check chart.Boxplot from package PerformanceAnalytics
. It lets you define the symbol to use for the mean of the distribution.
By default, the chart.Boxplot(data)
command adds the mean as a red circle and the median as a black line.
Here is the output with sample data; MWE:
#install.packages(PerformanceAnalytics)
library(PerformanceAnalytics)
chart.Boxplot(cars$speed)
%~z1
expands to the size of the first argument to the batch file. See
C:\> call /?
and
C:\> if /?
Simple example:
@ECHO OFF
SET SIZELIMIT=1000
SET FILESIZE=%~z1
IF %FILESIZE% GTR %SIZELIMIT% Goto No
ECHO Great! Your filesize is smaller than %SIZELIMIT% kbytes.
PAUSE
GOTO :EOF
:No
ECHO Um ... You have a big filesize.
PAUSE
GOTO :EOF
Have you tried height="100%"
in the definition of your iframe ? It seems to do what you seek, if you add height:100%
in the css for "body" (if you do not, 100% will be "100% of your content").
EDIT: do not do this. The height
attribute (as well as the width
one) must have an integer as value, not a string.