- name: set pkg copy dir name
set_fact:
PKG_DIR: >-
{% if ansible_os_family == "RedHat" %}centos/*.rpm
{%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
{%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
{%- else %}{%- endif %}
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2"),
new KeyValuePair<string, string>("Key3", "Value3"),
};
kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));
Using this code:
foreach (KeyValuePair<string, string> kvp in kvpList)
{
Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}
the expected output should be:
Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3
The same will work with a KeyValuePair or whatever other type you want to use..
Edit -
To lookup by the key, you can do the following:
var result = stringList.Where(s => s == "Lookup");
You could do this with a KeyValuePair by doing the following:
var result = kvpList.Where (kvp => kvp.Value == "Lookup");
Last edit -
Made the answer specific to KeyValuePair rather than string.
// Procedural
$fineStamp = date('Y-m-d\TH:i:s') . substr(microtime(), 1, 9);
echo $fineStamp . PHP_EOL;
// Object-oriented (if you must). Still relies on $fineStamp though :-\
$d = new DateTime($fineStamp);
echo $d->format('Y-m-d\TH:i:s.u') . PHP_EOL;
initialize the Session class in the constructor of controller using
$this->load->library('session');
for example :
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->model('user_activity','',TRUE);
$this->load->library('session');
}
Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.
This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.
For Debian distributions. Nothing worked for until I added the debian main repositories on the apt sources (I don't know how were they removed):
sudo vi /etc/apt/sources.list
and added
deb http://deb.debian.org/debian stretch main
deb-src http://deb.debian.org/debian stretch main
after that sudo apt-get update
(you can upgrade too) and finally sudo apt-get install php-sqlite3
I found a great jQuery solution here on SO.
var success = $.grep(array_a, function(v,i) {
return $.inArray(v, array_b) !== -1;
}).length === array_a.length;
I wish someone would post an example of how to do this in underscore.
My solution in code behind was:
System.Web.UI.WebControls.FileUpload fileUpload;
I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.
Text Input Example
input[type=text] {_x000D_
width: 150px;_x000D_
}_x000D_
_x000D_
input[name=myname] {_x000D_
width: 100px;_x000D_
}
_x000D_
<input type="text">_x000D_
<br>_x000D_
<input type="text" name="myname">
_x000D_
you can use this:
^\d+(\.\d)?\d*$
matches:
11
11.1
0.2
does not match:
.2
2.
2.6.9
try this
Execute this SQL:
SHOW TABLE STATUS LIKE '<tablename>'
and fetch the value of the field Auto_increment
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Because Submit
button is inside login_modal
so you need to use loginDialog
view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Slight modification to the accepted answer.
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
If the web service being invoked uses windows integrated security, creating a NetworkCredential
from the current WindowsIdentity
should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.
Edit: To get the credentials for the current identity, use the following:
Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");
Yes, bool is a built-in type.
WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.
I have one more solution. If anybody uses AngularJs : http://jsfiddle.net/ec9gn/30/
<div ng-controller='ctrl'>
<img ng-mouseover="img='eb00eb'" ng-mouseleave="img='000'"
ng-src='http://dummyimage.com/100x100/{{img}}/fff' />
</div>
The Javascript :
function ctrl($scope){
$scope.img= '000';
}
No CSS ^^.
Decode it.
>>> b'a string'.decode('ascii')
'a string'
To get bytes from string, encode it.
>>> 'a string'.encode('ascii')
b'a string'
Since most for loops are very similar, Java provides a shortcut to reduce the amount of code required to write the loop called the for each loop.
Here is an example of the concise for each loop:
for (Integer grade : quizGrades){
System.out.println(grade);
}
In the example above, the colon (:) can be read as "in". The for each loop altogether can be read as "for each Integer element (called grade) in quizGrades, print out the value of grade."
You can remove the "not null" property from your column in mysql table if not necessary. when you remove "not null" property no need for "0000-00-00 00:00:00" conversion and problem is gone.
At least worked for me.
Also, to use your new namespaced class you can also do
var jenine:com.newnamespace.subspace.Jenine = com.newnamespace.subspace.Jenine()
You can also use the shorter format
From the man page:
%F full date; same as %Y-%m-%d
Example:
#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)
I solved this by using a small function to convert version strings to plain integer values that can be compared:
function versionToInt() {
local IFS=.
parts=($1)
let val=1000000*parts[0]+1000*parts[1]+parts[2]
echo $val
}
This makes two important assumptions:
For example
versionToInt 12.34.56 # --> 12034056
versionToInt 1.2.3 # --> 1002003
Example testing whether npm
command meets minimum requirement ...
NPM_ACTUAL=$(versionToInt $(npm --version)) # Capture npm version
NPM_REQUIRED=$(versionToInt 4.3.0) # Desired version
if [ $NPM_ACTUAL \< $NPM_REQUIRED ]; then
echo "Please update to npm@latest"
exit 1
fi
I have added the following functions into my .bashrc file to automate these tasks. It does git push/git pull + name of current branch.
function gpush()
{
if [[ "x$1" == "x-h" ]]; then
cat <<EOF
Usage: gpush
git: for current branch: push changes to remote branch;
EOF
else
set -x
local bname=`git rev-parse --abbrev-ref --symbolic-full-name @{u} | sed -e "s#/# #"`
git push ${bname}
set +x
fi
}
function gpull()
{
if [[ "x$1" == "x-h" ]]; then
cat <<EOF
Usage: gpull
git: for current branch: pull changes from
EOF
else
set -x
local bname=`git rev-parse --abbrev-ref --symbolic-full-name @{u} | sed -e "s#/# #"`
git pull ${bname}
set +x
fi
}
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("5120MB");
factory.setMaxRequestSize("5120MB");
return factory.createMultipartConfig();
}
put it in class where you are defining beans
Below are the working steps without the need for any external modules:
Step 1: Create a module in your app.
E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.
Lets call this as custom_cors_middleware.py
Paste the below Class definition:
class CustomCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
# Code to be executed for each request/response after
# the view is called.
return response
Step 2: Register a middleware
In your projects settings.py file, add this line
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'
E.g:
MIDDLEWARE = [
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
...
'django.middleware.common.CommonMiddleware',
]
Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.
You can now verify it will add the required response headers to all the views in the project!
You can try the following. Works fine in my case:
Hope that helps.
Check this post, helped me a lot. In short, the best option for me was:
import random
import string
# defining function for random
# string id with parameter
def ran_gen(size, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
# function call for random string
# generation with size 8 and string
print (ran_gen(8, "AEIOSUMA23"))
Because I needed just 4-6 random characters instead of bulky GUID.
If you want to place your address in google map then easy way to use following
Intent searchAddress = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address));
startActivity(searchAddress);
OR
if you needed to get lat long from your address then use Google Place Api following
create a method that returns a JSONObject with the response of the HTTP Call like following
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
now pass that JSONObject to getLatLong() method like following
public static boolean getLatLong(JSONObject jsonObject) {
try {
longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
return true;
}
I hope this helps to you nd others..!! Thank you..!!
To summarize or simplify,
2xx: Optional data: Well formed URI: Criteria is not part of URI: If the criteria is optional that can be specified in @RequestBody and @RequestParam should lead to 2xx. Example: filter by name / status
4xx: Expected data : Not well formed URI : Criteria is part of URI : If the criteria is mandatory that can only be specified in @PathVariable then it should lead to 4xx. Example: lookup by unique id.
Thus for the asked situation: "users/9" would be 4xx (possibly 404) But for "users?name=superman" should be 2xx (possibly 204)
Solution for Hibernate users when parsing datas:
I had this error because I was parsing a list of objects mapped on both sides @OneToMany
and @ManyToOne
to json using jackson which caused an infinite loop.
If you are in the same situation you can solve this by using @JsonManagedReference
and @JsonBackReference
annotations.
Definitions from API :
JsonManagedReference (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonManagedReference.html) :
Annotation used to indicate that annotated property is part of two-way linkage between fields; and that its role is "parent" (or "forward") link. Value type (class) of property must have a single compatible property annotated with JsonBackReference. Linkage is handled such that the property annotated with this annotation is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling
JsonBackReference: (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonBackReference.html):
Annotation used to indicate that associated property is part of two-way linkage between fields; and that its role is "child" (or "back") link. Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.
Example:
Owner.java:
@JsonManagedReference
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
Set<Car> cars;
Car.java:
@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id")
private Owner owner;
Another solution is to use @JsonIgnore
which will just set null to the field.
I also got this error, was not having any clue. I could see the class and jars in Target folder. I later installed Maven 3.5, switched my local repo from C drive to other drive through conf/settings.xml of Maven. It worked perfectly fine after that. I think having local repo in C drive was main issue. Even though repo was having full access.
You are right that CSS positioning is the way to go. Here's a quick run down:
position: relative
will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).
However, you're most likely interested in position: absolute
which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative
or position: absolute
set on it, then it will act as the parent for positioning coordinates for its children.
To demonstrate:
#container {_x000D_
position: relative;_x000D_
border: 1px solid red;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="box">absolute</div>_x000D_
</div>
_x000D_
In that example, the top left corner of #box
would be 100px down and 50px left of the top left corner of #container
. If #container
did not have position: relative
set, the coordinates of #box
would be relative to the top left corner of the browser view port.
You can't have multiple time the same ID for elements. It is meant to be unique.
Use a class and make your IDs unique:
<div class="solTitle" id="solTitle1"> <a href = "#" id = "solution0" onClick = "openSolution();">Solution0 </a></div>
And use the class selector:
$('.solTitle a').click(function(evt) {
evt.preventDefault();
alert('here in');
var divId = 'summary' + this.id.substring(0, this.id.length-1);
document.getElementById(divId).className = '';
});
Listen the change
event.
document.querySelector("input")
.addEventListener('change', (e) => {
console.log(e.currentTarget.value);
});
I had this problem because i was adding bundle and certificate in wrong order so maybe this could help someone else.
Before (which is wrong) :
cat ca_bundle.crt certificate.crt > bundle_chained.crt
After (which is right)
cat certificate.crt ca_bundle.crt > bundle_chained.crt
And Please don't forget to update the appropriate conf (ssl_certificate must now point to the chained crt) as
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate bundle_chained.crt;
ssl_certificate_key www.example.com.key;
...
}
From the nginx manpage:
If the server certificate and the bundle have been concatenated in the wrong order, nginx will fail to start and will display the error message:
SSL_CTX_use_PrivateKey_file(" ... /www.example.com.key") failed (SSL: error:0B080074:x509 certificate routines: X509_check_private_key:key values mismatch)
My solution will encode deeply nested objects, unlike the currently accepted solution by @RakeshPai.
It uses the 'qs' npm library and its stringify function to convert nested objects into parameters.
This code works well with a Rails back-end, although you should be able to modify it to work with whatever backend you need by modifying the options passed to stringify. Rails requires that arrayFormat be set to "brackets".
import qs from "qs"
function normalPost(url, params) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", url);
const keyValues = qs
.stringify(params, { arrayFormat: "brackets", encode: false })
.split("&")
.map(field => field.split("="));
keyValues.forEach(field => {
var key = field[0];
var value = field[1];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value);
form.appendChild(hiddenField);
});
document.body.appendChild(form);
form.submit();
}
Example:
normalPost("/people/new", {
people: [
{
name: "Chris",
address: "My address",
dogs: ["Jordan", "Elephant Man", "Chicken Face"],
information: { age: 10, height: "3 meters" }
},
{
name: "Andrew",
address: "Underworld",
dogs: ["Doug", "Elf", "Orange"]
},
{
name: "Julian",
address: "In a hole",
dogs: ["Please", "Help"]
}
]
});
Produces these Rails parameters:
{"authenticity_token"=>"...",
"people"=>
[{"name"=>"Chris", "address"=>"My address", "dogs"=>["Jordan", "Elephant Man", "Chicken Face"], "information"=>{"age"=>"10", "height"=>"3 meters"}},
{"name"=>"Andrew", "address"=>"Underworld", "dogs"=>["Doug", "Elf", "Orange"]},
{"name"=>"Julian", "address"=>"In a hole", "dogs"=>["Please", "Help"]}]}
how about something along these lines
<style type="text/css">
#container {
margin: 0 auto;
text-align: center; /* for IE */
}
#yourdiv {
width: 400px;
border: 1px solid #000;
}
</style>
....
<div id="container">
<div id="yourdiv">
weee
</div>
</div>
My guess is that the webpage is listening to mousedown rather than click (which is bad for accessibility because when a user uses the keyboard, only focus and click are fired, not mousedown). So you should simulate mousedown, click, and mouseup (which, by the way, is what the iPhone, iPod Touch, and iPad do on tap events).
To simulate the mouse events, you can use this snippet for browsers that support DOM 2 Events. For a more foolproof simulation, fill in the mouse position using initMouseEvent
instead.
// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
var e = document.createEvent("MouseEvents");
// If you need clientX, clientY, etc., you can call
// initMouseEvent instead of initEvent
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);
When you fire a simulated click event, the browser will actually fire the default action (e.g. navigate to the link's href, or submit a form).
In IE, the equivalent snippet is this (unverified since I don't have IE). I don't think you can give the event handler mouse positions.
// IE 5.5+
element.fireEvent("onmouseover");
element.fireEvent("onmousedown");
element.fireEvent("onclick"); // or element.click()
element.fireEvent("onmouseup");
You can simulate keydown and keypress events, but unfortunately in Chrome they only fire the event handlers and don't perform any of the default actions. I think this is because the DOM 3 Events working draft describes this funky order of key events:
This means that you have to (while combing the HTML5 and DOM 3 Events drafts) simulate a large amount of what the browser would otherwise do. I hate it when I have to do that. For example, this is roughly how to simulate a key press on an input or textarea.
// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
var e = document.createEvent("KeyboardEvents");
e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
var e = document.createEvent("TextEvent");
e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
var e = document.createEvent("Event");
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var canceled = !dispatchKeyboardEvent(element,
'keydown', true, true, // type, bubbles, cancelable
null, // window
'h', // key
0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
''); // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
element.value += 'h';
dispatchSimpleEvent(element, 'input', false, false);
// not supported in Chrome yet
// if (element.form) element.form.dispatchFormInput();
dispatchSimpleEvent(element, 'change', false, false);
// not supported in Chrome yet
// if (element.form) element.form.dispatchFormChange();
}
}
dispatchKeyboardEvent(
element, 'keyup', true, true, null, 'h', 0, '');
I don't think it is possible to simulate key events in IE.
JSON Test has some
try its free and has other features too.
I use innerHTML together a ref to span:
import React, { useRef, useEffect, useState } from 'react';
export default function Sample() {
const spanRef = useRef<HTMLSpanElement>(null);
const [someHTML,] = useState("some <b>bold</b>");
useEffect(() => {
if (spanRef.current) {
spanRef.current.innerHTML = someHTML;
}
}, [spanRef.current, someHTML]);
return <div>
my custom text follows<br />
<span ref={spanRef} />
</div>
}
Solution
[
{
"name": "Naruto: Shippuuden",
"description": "It has been two and a half years since Naruto Uzumaki left Konohagakure, the Hidden Leaf Village, for intense training following events which fueled his desire to be stronger. Now Akatsuki, the mysterious organization of elite rogue ninja, is closing in on their grand plan which may threaten the safety of the entire shinobi world.",
"Rating": "8.16",
"episode": 500,
"categorie":"Animation | Drama | Adventure",
"studio":"Studio Pierrot",
"img": "https://myanimelist.cdn-dena.com/images/anime/5/17407.jpg"
},
{
"name": "One Piece",
"description": "Gol D. Roger was known as the 'Pirate King',the strongest and most infamous being to have sailed the Grand Line. The capture and death of Roger by the World Government brought a change throughout the world. His last words before his death revealed the existence of the greatest treasure in the world, One Piece. It was this revelation that brought about the Grand Age of Pirates, men who dreamed of finding One Piece—which promises an unlimited amount of riches and fame—and quite possibly the pinnacle of glory and the title of the Pirate King.",
"Rating": "8.54",
"episode": 700,
"categorie":"Animation | Drama | Adventure",
"studio":"Toei Animation",
"img": "https://myanimelist.cdn-dena.com/images/anime/6/73245.jpg"
}
]
2.This my model
public class DataResponse implements Serializable {
@SerializedName("studio")
private String studio;
@SerializedName("img")
private String img;
@SerializedName("categorie")
private String categorie;
@SerializedName("Rating")
private String rating;
@SerializedName("name")
private String name;
@SerializedName("description")
private String description;
@SerializedName("episode")
private int episode;
public void setStudio(String studio){
this.studio = studio;
}
public String getStudio(){
return studio;
}
public void setImg(String img){
this.img = img;
}
public String getImg(){
return img;
}
public void setCategorie(String categorie){
this.categorie = categorie;
}
public String getCategorie(){
return categorie;
}
public void setRating(String rating){
this.rating = rating;
}
public String getRating(){
return rating;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return description;
}
public void setEpisode(int episode){
this.episode = episode;
}
public int getEpisode(){
return episode;
}
@Override
public String toString(){
return
"Response{" +
"studio = '" + studio + '\'' +
",img = '" + img + '\'' +
",categorie = '" + categorie + '\'' +
",rating = '" + rating + '\'' +
",name = '" + name + '\'' +
",description = '" + description + '\'' +
",episode = '" + episode + '\'' +
"}";
}
}
define globle
private List<DataResponse> dataResponses = new ArrayList<>();
private void volleyAutomation(String url) {
JSONArray array = new JSONArray();
JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.GET, url, array,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
dataResponses = Arrays.asList(gson.fromJson(response.toString(), DataResponse[].class));
rvList(dataResponses);
Log.d("respknce___", String.valueOf(dataResponses.size()));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request_json);
}
You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
Just write <a href="#"></a>
.
If that's what you want, you don't need a server-side control.
Your error shows you are not compiling file with the definition of the insert
function. Update your command to include the file which contains the definition of that function and it should work.
Absolutely Asset Catalog is you answer, it removes the need to follow naming conventions when you are adding or updating your app icons.
Below are the steps to Migrating an App Icon Set or Launch Image Set From Apple:
1- In the project navigator, select your target.
2- Select the General pane, and scroll to the App Icons section.
3- Specify an image in the App Icon table by clicking the folder icon on the right side of the image row and selecting the image file in the dialog that appears.
4-Migrate the images in the App Icon table to an asset catalog by clicking the Use Asset Catalog button, selecting an asset catalog from the popup menu, and clicking the Migrate button.
Alternatively, you can create an empty app icon set by choosing Editor > New App Icon, and add images to the set by dragging them from the Finder or by choosing Editor > Import.
This will also work:
$(".myclass[reference='12345']").css('border', '#000 solid 1px');
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
public - The members (Functions & Variables) declared as public can be accessed from anywhere.
private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be considered as private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber.
protected - Protected members can be accessed only from the child classes.
internal - It can be accessed only within the same assembly.
protected internal - It can be accessed within the same assembly as well as in derived class.
This was happening for me, when I had a download link and after clicking on it I was trying also to catch the click with jquery and send an ajax request. The problem was because when you are clicking on the download link, you are leaving the page, even it does not look so. If there would no file transfer, you would see the requested page.. So I set a target="_blank" for preventing this issue.
Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url
# 1: Pause timeout and page loading
self.timeout.pause()
sleep(1)
# 2: Check for internet connection (Really lazy way)
while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)
# 3:Try again
if self.url == self.page().mainFrame().url():
self.page().action(QWebPage.Reload)
self.timeout.resume(60)
else:
self.page().action(QWebPage.Stop)
self.page().mainFrame().load(self.url)
self.timeout.resume(30)
return False
"
is shown as \"
in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.
Updated Answer
Code can be found here : official-doc
Answer Outdated
Check out the following links which may help you
Best examples are provided in the below links, which you can refactor to meet your requirements.
Took the following code from php manual for get_browser.
$browser = get_browser(null, true);
print_r($browser);
The $browser
array has platform
information included which gives you the specific Operating System in use.
Please make sure to see the "Notes" section in that page. This might be something (thismachine.info) is using if not something already pointed in other answers.
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
You can use simple color resources, specified usually inside res/values/colors.xml
.
<color name="red">#ffff0000</color>
and use this via android:background="@color/red"
. This color can be used anywhere else too, e.g. as a text color. Reference it in XML the same way, or get it in code via getResources().getColor(R.color.red)
.
You can also use any drawable resource as a background, use android:background="@drawable/mydrawable"
for this (that means 9patch drawables, normal bitmaps, shape drawables, ..).
In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0
His
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")
Corrected
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")
select floor((datediff(day,0,@today) - datediff(day,0,@birthdate)) / 365.2425) as age
There are a lot of 365.25 answers here. Remember how leap years are defined:
// Import data
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);
function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
$connection = mysqli_connect($host,$uname,$pass)
or die("Database Connection Failed");
$selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected");
$templine = '';
$lines = file($filename); // Read entire file
foreach ($lines as $line){
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
mysqli_query($connection, $templine)
or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
$templine = '';
}
}
echo "Tables imported successfully";
}
// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');
function backup_tables($host,$user,$pass,$name,$tables = '*'){
$link = mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($link,$name);
//get all of the tables
if($tables == '*'){
$tables = array();
$result = mysqli_query($link,'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
}else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = '';
foreach($tables as $table)
{
$result = mysqli_query($link,'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
$row2 = mysqli_fetch_row($row_query);
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysqli_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j < $num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", '\n', $row[$j]);
if (isset($row[$j])) {
$return.= '"'.$row[$j].'"' ;
} else {
$return.= '""';
}
if ($j < ($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
i tried all mentioned solutions available on the internet but no solution working on my Mac, then i created a provisioning profile manually on apple developer website from certificates and identifiers. By importing that file manually app successfully uploaded on appStore follow below steps
On Developer website
1-go to this link https://developer.apple.com/account/resources/certificates
2- In profile Section create new profile by using app bundle identifier
3-Download it and save it an where
On Xcode
1-Go to Signing and certificates
2-Disable automatically manage signing
3- Select provisioning profile in its section
4- Archive the app
5-Click Distribute App ->ApStore connect ->Upload->Next-> Then Select Profile from XXXX-app section when it download it show inside this section and now upload it
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:
String to match: "my word"
String to search: "I'm searching for my funny words inside this text"
You need the following regex: /^(?=.*my)(?=.*word).*$/im
Explaining:
^ assert position at start of a line
?= Positive Lookahead
.* matches any character (except newline)
() Groups
$ assert position at end of a line
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Test the Regex here: https://regex101.com/r/iS5jJ3/1
So, you can create a javascript function that:
Example:
function fullTextCompare(myWords, toMatch){_x000D_
//Replace regex reserved characters_x000D_
myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
//Split your string at spaces_x000D_
arrWords = myWords.split(" ");_x000D_
//Encapsulate your words inside regex groups_x000D_
arrWords = arrWords.map(function( n ) {_x000D_
return ["(?=.*"+n+")"];_x000D_
});_x000D_
//Create a regex pattern_x000D_
sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
//Execute the regex match_x000D_
return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
Another solution is that if you're making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).
For Example :
public int compareTo(freq arg0)
{
int ret=0;
if(this.magnitude>arg0.magnitude)
ret= 1;
else if (this.magnitude==arg0.magnitude)
ret= 0;
else if (this.magnitude<arg0.magnitude)
ret= -1;
return ret;
}
Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it's magnitude. So in order to correct that, you switch the values returned by the <
and >
. This gives you the following :
public int compareTo(freq arg0)
{
int ret=0;
if(this.magnitude>arg0.magnitude)
ret= -1;
else if (this.magnitude==arg0.magnitude)
ret= 0;
else if (this.magnitude<arg0.magnitude)
ret= 1;
return ret;
}
To make use of this compareTo, we simply call Arrays.sort(mFreq)
which will give you the sorted array freq [] mFreq
.
The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I'd encourage you not to think that way, it actually isn't. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.
It seems like you need to use __init__
in Python if you want to correctly initialize mutable attributes of your instances.
See the following example:
>>> class EvilTest(object):
... attr = []
...
>>> evil_test1 = EvilTest()
>>> evil_test2 = EvilTest()
>>> evil_test1.attr.append('strange')
>>>
>>> print "This is evil:", evil_test1.attr, evil_test2.attr
This is evil: ['strange'] ['strange']
>>>
>>>
>>> class GoodTest(object):
... def __init__(self):
... self.attr = []
...
>>> good_test1 = GoodTest()
>>> good_test2 = GoodTest()
>>> good_test1.attr.append('strange')
>>>
>>> print "This is good:", good_test1.attr, good_test2.attr
This is good: ['strange'] []
This is quite different in Java where each attribute is automatically initialized with a new value:
import java.util.ArrayList;
import java.lang.String;
class SimpleTest
{
public ArrayList<String> attr = new ArrayList<String>();
}
class Main
{
public static void main(String [] args)
{
SimpleTest t1 = new SimpleTest();
SimpleTest t2 = new SimpleTest();
t1.attr.add("strange");
System.out.println(t1.attr + " " + t2.attr);
}
}
produces an output we intuitively expect:
[strange] []
But if you declare attr
as static
, it will act like Python:
[strange] [strange]
final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msgs) {
//write your code hear which give error
}
}
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
//this will call handleMessage function and hendal all error
}
}).start();
I concur with Franci, all Sysinternals utilities are worth taking a look (Autoruns is a must too), and Process Monitor, which replaces the good old Filemon and Regmon is precious.
Beside the usage you want, it is very useful to see why a process fails (like trying to access a file or a registry key that doesn't exist), etc.
Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.
That being said, the following works...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then((res: Actor) => {
// res is now an Actor
});
I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...
callBack: (response: any) => void
But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then(res => {
if (callback) {
callback(res); // Client receives the response as desired type.
}
});
So that a client can call it with a callback like...
(response: IApigeeResponse) => {
// Process response as an IApigeeResponse
}
const img = '../../img/splash/splash_bg.png';
<ImageBackground source={{ uri: img }} style={styles.backgroundImage} >
</ImageBackground>
This worked for me. Reference to RN docs can be found here.I wrote mine by reading this- https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting
in my case i want getting timeZone of several country ,first install moment js
npm install moment --save
then install moment-timezone.js
npm install moment-timezone --save
then i import themn in my component like this
import moment from 'moment';
import timezone from 'moment-timezone'
then because iwant getting hour and minutes and second sepratly i do like this
<Clock minutes={moment().tz('Australia/Sydney').minute()} hour={moment().tz('Australia/Sydney').hours()} second={moment().tz('Australia/Sydney').second()}/>
A useful shortcut from inside Sublime Text:
cmd-shift-P --> Browse Packages Now open user folder.
I've got correct solution here.
The best way to correctly install gcc-4.9 and set it as your default gcc version use:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9
The --slave, with g++, will cause g++ to be switched along with gcc, to the same version. But, at this point gcc-4.9 will be your only version configured in update-alternatives, so add 4.8 to update-alternatives, so there actually is an alternative, by using:
sudo apt-get install gcc-4.8 g++-4.8
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8
Then you can check which one that is set, and change back and forth using:
sudo update-alternatives --config gcc
NOTE: You could skip installing the PPA Repository and just use /usr/bin/gcc-4.9-base but I prefer using the fresh updated toolchains.
Don't drop, just take the rows where EPS is not NA:
df = df[df['EPS'].notna()]
If you have loads of re-directs to create, having loads of virtual directories over the places is a nightmare to maintain. You could try using ISAPI redirect an IIS extension. Then all you re-directs are managed in one place.
http://www.isapirewrite.com/docs/
It allows also you to match patterns based on reg ex expressions etc. I've used where I've had to re-direct 100's of pages and its saved a lot of time.
When there is one commit only in the branch, I usually do
git merge branch_name --ff
If you declare your callback as mentioned by @lex82 like
callback = "callback(item.id, arg2)"
You can call the callback method in the directive scope with object map and it would do the binding correctly. Like
scope.callback({arg2:"some value"});
without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/
Update: There is a small example of this in the documentation:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
Maybe it will be to complex for this question but it surely do the job for you. I have created two classes to handle not only array insertion but also querying the database, updating and deleting files. "MySqliConnection" class is used to create only one instance of db connection (to prevent duplication of new objects).
<?php
/**
*
* MySQLi database connection: only one connection is allowed
*/
class MySqliConnection{
public static $_instance;
public $_connection;
public function __construct($host, $user, $password, $database){
$this->_connection = new MySQLi($host, $user, $password, $database);
if (isset($mysqli->connect_error)) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
}
/*
* Gets instance of connection to database
* @return (MySqliConnection) Object
*/
public static function getInstance($host, $user, $password, $database){
if(!self::$_instance){
self::$_instance = new self($host, $user, $password, $database); //if no instance were created - new one will be initialize
}
return self::$_instance; //return already exsiting instance of the database connection
}
/*
* Prevent database connection from bing copied while assignig the object to new wariable
* @return (MySqliConnection) Object
*/
public function getConnection(){
return $this->_connection;
}
/*
* Prevent database connection from bing copied/duplicated while assignig the object to new wariable
* @return nothing
*/
function __clone(){
}
}
/*// CLASS USE EXAMPLE
$db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
$mysqli = $db->getConnection();
$sql_query = 'SELECT * FROM users;
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['ID'];
}
*/
The second "TableManager" class is little bit more complex. It also make use of the MySqliConnection class which I posted above. So you would have to include both of them in your project. TableManager will allow you to easy make insertion updates and deletions. Class have separate placeholder for read and write.
<?php
/*
* DEPENDENCIES:
* include 'class.MySqliConnection.inc'; //custom class
*
*/
class TableManager{
private $lastQuery;
private $lastInsertId;
private $tableName;
private $tableIdName;
private $columnNames = array();
private $lastResult = array();
private $curentRow = array();
private $newPost = array();
/*
* Class constructor
* [1] (string) $tableName // name of the table which you want to work with
* [2] (string) $tableIdName // name of the ID field which will be used to delete and update records
* @return void
*/
function __construct($tableName, $tableIdName){
$this->tableIdName = $tableIdName;
$this->tableName = $tableName;
$this->getColumnNames();
$this->curentRow = $this->columnNames;
}
public function getColumnNames(){
$sql_query = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = "'.$this->tableName.'"';
$mysqli = $this->connection();
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->columnNames[$row['COLUMN_NAME']] = null;
}
}
/*
* Used by a Constructor to set native parameters or virtual array curentRow of the class
* [1] (array) $v
* @return void
*/
function setRowValues($v){
if(!is_array($v)){
$this->curentRow = $v;
return true;
}
foreach ($v as $a => $b) {
$method = 'set'.ucfirst($a);
if(is_callable(array($this, $method))){
//if method is callable use setSomeFunction($k, $v) to filter the value
$this->$method($b);
}else{
$this->curentRow[$a] = $b;
}
}
}
/*
* Used by a constructor to set native parameters or virtual array curentRow of the class
* [0]
* @return void
*/
function __toString(){
var_dump($this);
}
/*
* Query Database for information - Select column in table where column = somevalue
* [1] (string) $column_name // name od a column
* [2] (string) $quote_pos // searched value in a specified column
* @return void
*/
public function getRow($column_name = false, $quote_post = false){
$mysqli = $this->connection();
$quote_post = $mysqli->real_escape_string($quote_post);
$this->tableName = $mysqli->real_escape_string($this->tableName);
$column_name = $mysqli->real_escape_string($column_name);
if($this->tableName && $column_name && $quote_post){
$sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$column_name.' = "'.$quote_post.'"';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
if($this->tableName && $column_name && !$quote_post){
$sql_query = 'SELECT '.$column_name.' FROM '.$this->tableName.'';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[] = $row;
$this->setRowValues($row);
}
}
if($this->tableName && !$column_name && !$quote_post){
$sql_query = 'SELECT * FROM '.$this->tableName.'';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
}
/*
* Connection class gets instance of db connection or if not exsist creats one
* [0]
* @return $mysqli
*/
private function connection(){
$this->lastResult = "";
$db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
$mysqli = $db->getConnection();
return $mysqli;
}
/*
* ...
* [1] (string) $getMe
* @return void
*/
function __get($getMe){
if(isset($this->curentRow[$getMe])){
return $this->curentRow[$getMe];
}else{
throw new Exception("Error Processing Request - No such a property in (array) $this->curentRow", 1);
}
}
/*
* ...
* [2] (string) $setMe, (string) $value
* @return void
*/
function __set($setMe, $value){
$temp = array($setMe=>$value);
$this->setRowValues($temp);
}
/*
* Dumps the object
* [0]
* @return void
*/
function dump(){
echo "<hr>";
var_dump($this);
echo "<hr>";
}
/*
* Sets Values for $this->newPost array which will be than inserted by insertNewPost() function
* [1] (array) $newPost //array of avlue that will be inserted to $this->newPost
* @return bolean
*/
public function setNewRow($arr){
if(!is_array($arr)){
$this->newPost = $arr;
return false;
}
foreach ($arr as $k => $v) {
if(array_key_exists($k, $this->columnNames)){
$method = 'set'.ucfirst($k);
if(is_callable(array($this, $method))){
if($this->$method($v) == false){ //if something go wrong
$this->newPost = array(); //empty the newPost array and return flase
throw new Exception("There was a problem in setting up New Post parameters. [Cleaning array]", 1);
}
}else{
$this->newPost[$k] = $v;
}
}else{
$this->newPost = array(); //empty the newPost array and return flase
throw new Exception("The column does not exsist in this table. [Cleaning array]", 1);
}
}
}
/*
* Inserts new post held in $this->newPost
* [0]
* @return bolean
*/
public function insertNewRow(){
// check if is set, is array and is not null
if(isset($this->newPost) && !is_null($this->newPost) && is_array($this->newPost)){
$mysqli = $this->connection();
$count_lenght_of_array = count($this->newPost);
// preper insert query
$sql_query = 'INSERT INTO '.$this->tableName.' (';
$i = 1;
foreach ($this->newPost as $key => $value) {
$sql_query .=$key;
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
$i = 1;
$sql_query .=') VALUES (';
foreach ($this->newPost as $key => $value) {
$sql_query .='"'.$value.'"';
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
$sql_query .=')';
var_dump($sql_query);
if($mysqli->query($sql_query)){
$this->lastInsertId = $mysqli->insert_id;
$this->lastQuery = $sql_query;
}
$this->getInsertedPost($this->lastInsertId);
}
}
/*
* getInsertedPost function query the last inserted id and assigned it to the object.
* [1] (integer) $id // last inserted id from insertNewRow fucntion
* @return void
*/
private function getInsertedPost($id){
$mysqli = $this->connection();
$sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = "'.$id.'"';
$result = $mysqli->query($sql_query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
/*
* getInsertedPost function query the last inserted id and assigned it to the object.
* [0]
* @return bolean // if deletion was successful return true
*/
public function deleteLastInsertedPost(){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$this->lastInsertId.'';
$result = $mysqli->query($sql_query);
if($result){
$this->lastResult[$this->lastInsertId] = "deleted";
return true;
}else{
throw new Exception("We could not delete last inserted row by ID [{$mysqli->errno}] {$mysqli->error}");
}
var_dump($sql_query);
}
/*
* deleteRow function delete the row with from a table based on a passed id
* [1] (integer) $id // id of the table row to be delated
* @return bolean // if deletion was successful return true
*/
public function deleteRow($id){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$id.'';
$result = $mysqli->query($sql_query);
if($result){
$this->lastResult[$this->lastInsertId] = "deleted";
return true;
}else{
return false;
}
var_dump($sql_query);
}
/*
* deleteAllRows function deletes all rows from a table
* [0]
* @return bolean // if deletion was successful return true
*/
public function deleteAllRows(){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.'';
$result = $mysqli->query($sql_query);
if($result){
return true;
}else{
return false;
}
}
/*
* updateRow function updates all values to object values in a row with id
* [1] (integer) $id
* @return bolean // if deletion was successful return true
*/
public function updateRow($update_where = false){
$id = $this->curentRow[$this->tableIdName];
$mysqli = $this->connection();
$updateMe = $this->curentRow;
unset($updateMe[$this->tableIdName]);
$count_lenght_of_array = count($updateMe);
// preper insert query
$sql_query = 'UPDATE '.$this->tableName.' SET ';
$i = 1;
foreach ($updateMe as $k => $v) {
$sql_query .= $k.' = "'.$v.'"';
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
if($update_where == false){
//update row only for this object id
$sql_query .=' WHERE '.$this->tableIdName.' = '.$this->curentRow[$this->tableIdName].'';
}else{
//add your custom update where query
$sql_query .=' WHERE '.$update_where.'';
}
var_dump($sql_query);
if($mysqli->query($sql_query)){
$this->lastQuery = $sql_query;
}
$result = $mysqli->query($sql_query);
if($result){
return true;
}else{
return false;
}
}
}
/*TO DO
1 insertPost(X, X) write function to isert data and in to database;
2 get better query system and display data from database;
3 write function that displays data of a object not databsae;
object should be precise and alocate only one instance of the post at a time.
// Updating the Posts to curent object $this->curentRow values
->updatePost();
// Deleting the curent post by ID
// Add new row to database
*/
/*
USE EXAMPLE
$Post = new TableManager("post_table", "ID"); // New Object
// Getting posts from the database based on pased in paramerters
$Post->getRow('post_name', 'SOME POST TITLE WHICH IS IN DATABASE' );
$Post->getRow('post_name');
$Post->getRow();
MAGIC GET will read current object $this->curentRow parameter values by refering to its key as in a varible name
echo $Post->ID.
echo $Post->post_name;
echo $Post->post_description;
echo $Post->post_author;
$Task = new TableManager("table_name", "table_ID_name"); // creating new TableManager object
$addTask = array( //just an array [colum_name] => [values]
'task_name' => 'New Post',
'description' => 'New Description Post',
'person' => 'New Author',
);
$Task->setNewRow($addTask); //preper new values for insertion to table
$Task->getRow('ID', '12'); //load value from table to object
$Task->insertNewRow(); //inserts new row
$Task->dump(); //diplays object properities
$Task->person = "John"; //magic __set() method will look for setPerson(x,y) method firs if non found will assign value as it is.
$Task->description = "John Doe is a funny guy"; //magic __set() again
$Task->task_name = "John chellange"; //magic __set() again
$test = ($Task->updateRow("ID = 5")) ? "WORKS FINE" : "ERROR"; //update cutom row with object values
echo $test;
$test = ($Task->updateRow()) ? "WORKS FINE" : "ERROR"; //update curent data loaded in object
echo $test;
*/
The usual command line ping
tool uses ICMP Echo, but it's true that other protocols can also be used, and they're useful in debugging different kinds of network problems.
I can remember at least arping
(for testing ARP requests) and tcping
(which tries to establish a TCP connection and immediately closes it, it can be used to check if traffic reaches a certain port on a host) off the top of my head, but I'm sure there are others aswell.
Recently Combine method was added to Energy.Core package, so you might want to use it to join URL parts.
string url;
url = Energy.Base.Url.Combine("https://www.youtube.com", "watch?v=NHCgbs3TcYg");
Console.WriteLine(url);
url = Energy.Base.Url.Combine("https://www.youtube.com", "watch?v=NHCgbs3TcYg", "t=150");
Console.WriteLine(url);
Additionally it will recognize parameter part, so it will work as you might expect (joining path with slash and parameters with ampersand).
For those who don't want to create any models, use the following code:
var result = JsonConvert.DeserializeObject<
List<Dictionary<string,
Dictionary<string, string>>>>(content);
Note: This doesn't work for your JSON string. This is not a general solution for any JSON structure.
Here is my solution:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.pageSource = request.source;
var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title)
}
});
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
);
});
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
use array_map()
:
$yourArray = array_map('strtolower', $yourArray);
In case you need to lowercase nested array (by Yahya Uddin):
$yourArray = array_map('nestedLowercase', $yourArray);
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
String is a reference type, so you don't need to (and cannot) use Nullable<T>
here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.
For newer Android platforms, one can execute a system utility screencap
in /system/bin
to get the screenshot without root permission.
You can try /system/bin/screencap -h
to see how to use it under adb or any shell.
By the way, I think this method is only good for single snapshot. If we want to capture multiple frames for screen play, it will be too slow. I don't know if there exists any other approach for a faster screen capture.
This is a good example where you want to get count of Pincode which stored in the last of address field
SELECT DISTINCT
RIGHT (address, 6),
count(*) AS count
FROM
datafile
WHERE
address IS NOT NULL
GROUP BY
RIGHT (address, 6)
You coud use your own custom AjaxExceptionHandler or primefaces-extensions
Update your faces-config.xml
...
<factory>
<exception-handler-factory>org.primefaces.extensions.component.ajaxerrorhandler.AjaxExceptionHandlerFactory</exception-handler-factory>
</factory>
...
Add following code in your jsf page
...
<pe:ajaxErrorHandler />
...
Laravel tries to guess the name of the table, you have to specify it directly so that it does not give you that error..
Try this:
class NameModel extends Model {
public $table = 'name_exact_of_the_table';
I hope that helps!
In pymongo you can use:
db.mycollection.find({"IMAGE URL":{"$ne":None}});
Because pymongo represents mongo "null" as python "None".
There are many great open source projects that make detection a lot easier. To name two:
I was sending requests from angularjs using $http service to bottle running on http://localhost:8090/
and I had to apply CORS otherwise I got request errors like "No 'Access-Control-Allow-Origin' header is present on the requested resource"
from bottle import hook, route, run, request, abort, response
#https://github.com/defnull/bottle/blob/master/docs/recipes.rst#using-the-hooks-plugin
@hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
Im coming from react native but I think that this applies to this question as well. To specify.
Within the file android/app/build.gradle
search for applicationId
(within android
, defaultConfig
)
and ensure that that value is the same this
client[0]client_info.android_client_info.package_name
as the value within google-services.json
.
I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:
If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.
I had problems with viewport, specific layouts to different user agents and this is what solved my problem:
<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>
<script language="javascript" type="text/javascript">
function windowSize() {
let gist = document.querySelector('#gist92442763');
let isMobile = {
Android: function() {
return /Android/i.test(navigator.userAgent)
},
BlackBerry: function() {
return /BlackBerry/i.test(navigator.userAgent)
},
iOS: function() {
return /iPhone|iPod/i.test(navigator.userAgent)
},
Opera: function() {
return /Opera Mini/i.test(navigator.userAgent)
},
Windows: function() {
return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if(isMobile.any()) {
gist.style.width = "36%";
gist.style.WebkitOverflowScrolling = "touch"
gist.style.position = "absolute"
} else {
gist.style.width = "auto !important";
}
}
windowSize();
window.addEventListener('onresize', function() {
windowSize();
});
</script>
<style type="text/css">
.gist-data {
max-height: 300px;
}
.gist-meta {
display: none;
}
</style>
The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.
Basically, no. The following would be what you were after in theory:
div.a < div { border: solid 3px red; }
Unfortunately it doesn't exist.
There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:
http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors
After trying almost every key on my keyboard:
C:\Users\Tim>cd ^
Mehr? Desktop
C:\Users\Tim\Desktop>
So it seems to be the ^ key.
SQL Developer seems to only output the DBMS_OUTPUT text when you have explicitly turned on the DBMS_OUTPUT window pane.
Go to (Menu) VIEW -> Dbms_output to invoke the pane.
Click on the Green Plus sign to enable output for your connection and then run the code.
EDIT: Don't forget to set the buffer size according to the amount of output you are expecting.
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
Really simple:
remove-item -path <type in file or directory name>, press Enter
In addition to the excellent answers, I would like to emphasize here when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.
The answer is really simple
res.end() is used to quickly end the response without sending any data.
An example for this would be starting a process on a server
app.get(/start-service, (req, res) => {
// Some logic here
exec('./application'); // dummy code
res.end();
});
If you would like to send data in your response then you should use res.send() instead
app.get(/start-service, (req, res) => {
res.send('{"age":22}');
});
Here you can read more
Best is to just Apply margin-top: 2px
on the input element.
Bootstrap adds a margin-top: 4px
to input element causing radio button to move down than the content.
Though this question has been answered many times before, I thought I would add to it with a more complete and solid answer for future users. The main answer does solve the problem, but I believe it may be better to know/understand the some of various ways to show/hide things.
.
This is the way I used to do it until I found some of these other ways.
Javascript:
$("#element_to_hide").css("display", "none"); // To hide
$("#element_to_hide").css("display", ""); // To unhide
Pros:
Cons:
$("#element_to_hid").css("display", "inline");
otherwise it will default back to "block" or whatever else that it will be forced into.Example: https://jsfiddle.net/4chd6e5r/1/
.
While setting up the example for this one, I actually ran into some flaws on this method that make it very very unreliable.
Css/Javascript:
.hidden {display:none}
$("#element_to_hide").addClass("hidden"); // To hide
$("#element_to_hide").removeClass("hidden"); // To unhide
Pros:
$(".hidden")
.Cons:
Example: https://jsfiddle.net/476oha8t/8/
.
Javascript:
$("element_to_hide").toggle(); // To hide and to unhide
Pros:
Cons:
Example: https://jsfiddle.net/cxcawkyk/1/
.
Javascript:
$("#element_to_hide").hide(); // To hide
$("#element_to_hide").show(); // To show
Pros:
Cons:
Example: https://jsfiddle.net/k0ukhmfL/
.
Overall, I would say the best to be hide()/show() unless you specifically need it to be a toggle. I hope you found this information to be helpful.
A better way for setting multiple options:
setIcon/setLogo
method will only work if you have set DisplayOptions Try this -
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setIcon(R.drawable.ic_launcher);
You can also set options for displaying LOGO(just add constant ActionBar.DISPLAY_USE_LOGO
). More information - displayOptions
About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.
Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:
IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.
Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.
The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".
I know this is a bit old, but I thought I would provide another tip. In my situation, I inherited this application that I had to maintain. The VS2008 project came with the same string in C/C++->OutputFIles->"ObjectFIleName" and "Program Database File Name" (for both platforms Win32 and x64). So when I built Win32 platform, it built fine, but when I tried to build x64, I got the error:
\Debug64\Objects\common.obj : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'
Obviously, both patforms were storing common.obj at the same location, so when I tried to build x64, the linker took the existing object file, which was x86.
To fix I just replaced the existing string with the macro "$(IntDir)\" for x64 (no quotes), and made sure that the macro resolved to the correct path, as in the rest of the projects. That solved my problem.
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
Your chunk of code does not create a new one, it only checks if its already there and nothing else.
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
You could search for:
<li><a href="#">[^\n]+
And replace with:
$0</a>
Where $0
is the whole match. The exact semantics will depend on the language are you using though.
WARNING: You should avoid parsing HTML with regex. Here's why.
You can use regular expressions for this purpose, but it's good to avoid extra exceptions when input string mismatches against regular expression.
First to avoid extra headache of escaping to regex pattern - we could just use function for that purpose:
String reStrEnding = Regex.Escape("-");
I know that this does not do anything - as "-" is the same as Regex.Escape("=") == "="
, but it will make difference for example if character is @"\"
.
Then we need to match from begging of the string to string ending, or alternately if ending is not found - then match nothing. (Empty string)
Regex re = new Regex("^(.*?)" + reStrEnding);
If your application is performance critical - then separate line for new Regex, if not - you can have everything in one line.
And finally match against string and extract matched pattern:
String matched = re.Match(str).Groups[1].ToString();
And after that you can either write separate function, like it was done in another answer, or write inline lambda function. I've wrote now using both notations - inline lambda function (does not allow default parameter) or separate function call.
using System;
using System.Text.RegularExpressions;
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
}
}
class Program
{
static void Main(string[] args)
{
Regex re = new Regex("^(.*?)-");
Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };
Console.WriteLine(untilSlash("223232-1.jpg"));
Console.WriteLine(untilSlash("443-2.jpg"));
Console.WriteLine(untilSlash("34443553-5.jpg"));
Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
Console.WriteLine(untilSlash(""));
// Throws exception: Console.WriteLine(untilSlash(null));
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
}
}
Btw - changing regex pattern to "^(.*?)(-|$)"
will allow to pick up either until "-"
pattern or if pattern was not found - pick up everything until end of string.
db2 connect to MY_INSTACE_DB with myuser -- connect to db2
db2 "select TABNAME from syscat.tables where tabschema = 'mySchema' with ur"
db2 terminate -- end connection
To find out URI:
current_uri = request.env['PATH_INFO']
# If you are browsing http://example.com/my/test/path,
# then above line will yield current_uri as "/my/test/path"
To find out the route i.e. controller, action and params:
path = ActionController::Routing::Routes.recognize_path "/your/path/here/"
# ...or newer Rails versions:
#
path = Rails.application.routes.recognize_path('/your/path/here')
controller = path[:controller]
action = path[:action]
# You will most certainly know that params are available in 'params' hash
Mysql has this handy UPDATE INTO command ;)
edit Looks like they renamed it to REPLACE
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
If you don't want the Drop list
to show up like a popup. You can customize it this way just like me (it will show up as if on the same flat, see image below):
After expand:
Please follow the steps below:
First, create a dart file named drop_list_model.dart
:
import 'package:flutter/material.dart';
class DropListModel {
DropListModel(this.listOptionItems);
final List<OptionItem> listOptionItems;
}
class OptionItem {
final String id;
final String title;
OptionItem({@required this.id, @required this.title});
}
Next, create file file select_drop_list.dart
:
import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';
class SelectDropList extends StatefulWidget {
final OptionItem itemSelected;
final DropListModel dropListModel;
final Function(OptionItem optionItem) onOptionSelected;
SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);
@override
_SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}
class _SelectDropListState extends State<SelectDropList> with SingleTickerProviderStateMixin {
OptionItem optionItemSelected;
final DropListModel dropListModel;
AnimationController expandController;
Animation<double> animation;
bool isShow = false;
_SelectDropListState(this.optionItemSelected, this.dropListModel);
@override
void initState() {
super.initState();
expandController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 350)
);
animation = CurvedAnimation(
parent: expandController,
curve: Curves.fastOutSlowIn,
);
_runExpandCheck();
}
void _runExpandCheck() {
if(isShow) {
expandController.forward();
} else {
expandController.reverse();
}
}
@override
void dispose() {
expandController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 17),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black26,
offset: Offset(0, 2))
],
),
child: new Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(Icons.card_travel, color: Color(0xFF307DF1),),
SizedBox(width: 10,),
Expanded(
child: GestureDetector(
onTap: () {
this.isShow = !this.isShow;
_runExpandCheck();
setState(() {
});
},
child: Text(optionItemSelected.title, style: TextStyle(
color: Color(0xFF307DF1),
fontSize: 16),),
)
),
Align(
alignment: Alignment(1, 0),
child: Icon(
isShow ? Icons.arrow_drop_down : Icons.arrow_right,
color: Color(0xFF307DF1),
size: 15,
),
),
],
),
),
SizeTransition(
axisAlignment: 1.0,
sizeFactor: animation,
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.only(bottom: 10),
decoration: new BoxDecoration(
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 4,
color: Colors.black26,
offset: Offset(0, 4))
],
),
child: _buildDropListOptions(dropListModel.listOptionItems, context)
)
),
// Divider(color: Colors.grey.shade300, height: 1,)
],
),
);
}
Column _buildDropListOptions(List<OptionItem> items, BuildContext context) {
return Column(
children: items.map((item) => _buildSubMenu(item, context)).toList(),
);
}
Widget _buildSubMenu(OptionItem item, BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
child: GestureDetector(
child: Row(
children: <Widget>[
Expanded(
flex: 1,
child: Container(
padding: const EdgeInsets.only(top: 20),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
),
child: Text(item.title,
style: TextStyle(
color: Color(0xFF307DF1),
fontWeight: FontWeight.w400,
fontSize: 14),
maxLines: 3,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis),
),
),
],
),
onTap: () {
this.optionItemSelected = item;
isShow = false;
expandController.reverse();
widget.onOptionSelected(item);
},
),
);
}
}
Initialize value:
DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Ch?n quy?n truy c?p");
Finally use it:
SelectDropList(
this.optionItemSelected,
this.dropListModel,
(optionItem){
optionItemSelected = optionItem;
setState(() {
});
},
)
The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2)
, it should work
SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table
OR
SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table
The proper way is to look at the HTTP Accept-Language header sent to the server. This contains the ordered, weighted list of languages the user has configured their browser to prefer.
Unfortunately this header is not available for reading inside JavaScript; all you get is navigator.language
, which tells you what localised version of the web browser was installed. This is not necessarily the same thing as the user's preferred language(s). On IE you instead get systemLanguage
(OS installed language), browserLanguage
(same as language
) and userLanguage
(user configured OS region), which are all similarly unhelpful.
If I had to choose between those properties, I'd sniff for userLanguage
first, falling back to language
and only after that (if those didn't match any available language) looking at browserLanguage
and finally systemLanguage
.
If you can put a server-side script somewhere else on the net that simply reads the Accept-Language header and spits it back out as a JavaScript file with the header value in the string, eg.:
var acceptLanguage= 'en-gb,en;q=0.7,de;q=0.3';
then you could include a <script src> pointing at that external service in the HTML, and use JavaScript to parse the language header. I don't know of any existing library code to do this, though, since Accept-Language parsing is almost always done on the server side.
Whatever you end up doing, you certainly need a user override because it will always guess wrong for some people. Often it's easiest to put the language setting in the URL (eg. http?://www.example.com/en/site vs http?://www.example.com/de/site), and let the user click links between the two. Sometimes you do want a single URL for both language versions, in which case you have to store the setting in cookies, but this may confuse user agents with no support for cookies and search engines.
Just install libpq-dev
$ sudo apt-get install libpq-dev
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
// This is because your method .getElementById has the letter 's': .getElement**s**ById
I have written a code that lets you format string easily.
function format() {
if (arguments.length === 0) {
throw "No arguments";
}
const string = arguments[0];
const lst = string.split("{}");
if (lst.length !== arguments.length) {
throw "Placeholder format mismatched";
}
let string2 = "";
let off = 1;
for (let i = 0; i < lst.length; i++) {
if (off < arguments.length) {
string2 += lst[i] + arguments[off++]
} else {
string2 += lst[i]
}
}
return string2;
}
format('My Name is {} and my age is {}', 'Mike', 26);
My Name is Mike and my age is 26
The behaviour is not defined, so you must explicit set a commit or a rollback:
http://docs.oracle.com/cd/B10500_01/java.920/a96654/basic.htm#1003303
"If auto-commit mode is disabled and you close the connection without explicitly committing or rolling back your last changes, then an implicit COMMIT operation is executed."
Hsqldb makes a rollback
con.setAutoCommit(false);
stmt.executeUpdate("insert into USER values ('" + insertedUserId + "','Anton','Alaf')");
con.close();
result is
2011-11-14 14:20:22,519 main INFO [SqlAutoCommitExample:55] [AutoCommit enabled = false] 2011-11-14 14:20:22,546 main INFO [SqlAutoCommitExample:65] [Found 0# users in database]
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
POD classes are Plain-Old data classes that have only data members and nothing else. There are a few questions on stackoverflow about the same. Find one here.
Also, you can have functions as members of structs in C++ but not in C. You need to have pointers to functions as members in structs in C.
The most trivial way to upload a binary file to an FTP server using PowerShell is using WebClient.UploadFile
:
$client = New-Object System.Net.WebClient
$client.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
If you need a greater control, that WebClient
does not offer (like TLS/SSL encryption, etc), use FtpWebRequest
. Easy way is to just copy a FileStream
to FTP stream using Stream.CopyTo
:
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$fileStream.CopyTo($ftpStream)
$ftpStream.Dispose()
$fileStream.Dispose()
If you need to monitor an upload progress, you have to copy the contents by chunks yourself:
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$ftpStream.Write($buffer, 0, $read)
$pct = ($fileStream.Position / $fileStream.Length)
Write-Progress `
-Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
-PercentComplete ($pct * 100)
}
$ftpStream.Dispose()
$fileStream.Dispose()
If you want to upload all files from a folder, see
PowerShell Script to upload an entire folder to FTP
Use git gui
, there you can see a list of what changed in your actual commit. You can also use gitk
wich provides an easy interface for reflogs. Just compare between remotes/...
and master
to see, what will be pushed. It provides an interface similar to your screenshot.
Both programs are included in git.
If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker
GooglemLoc="https://www.google.com/maps/place/"&[Latitude]&"+"&[Longitude]&"/@"&[Latitude]&","&[Longitude]&",15z"
GooglemRute="https://www.google.co.ls/maps/dir/"&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en" 'route ?hl=en
OpenStreetLoc="https://www.openstreetmap.org/#map=16/"&[Latitude]&"/"&[Longitude]&"&layers=N"
OpenStreetRute="https://www.openstreetmap.org/directions?engine=osrm_car&route="&[FrmLatt]&"%2C"&[FrmLong]&"%3B"&[ToLatt]&"%2C"&[ToLong]&"#Map=15/"&[ScreenX]&"/"&[Screeny]&"&layers=N"
As @alex said, you could float it right, but if you wanted to keep the markup the same, float it to the left!
#ul_top_hypers li {
float: left;
}
Unlike C/C++ Long in Python have unlimited precision. Refer the section Numeric Types in python for more information.To determine the max value of integer you can just refer sys.maxint
. You can get more details from the documentation of sys.
we have to install the M2E Eclipse WTP plugin To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.
And restart eclipse
It is preferable to use rest parameter syntax as Ramast pointed out.
function (a, b, ...args) {}
I just want to add some nice property of the ...args argument
- It is an array, and not an object like arguments. This allows you to apply functions like map or sort directly.
- It does not include all parameters but only the one passed from it on. E.g. function (a, b, ...args) in this case args contains argument 3 to arguments.length
class B is only declared but not defined at the beginning, which is what the compiler complains about. The root cause is that in class A's Call Function, you are referencing instance b of type B
, which is incomplete and undefined. You can modify source like this without introducing new file(just for sake of simplicity, not recommended in practice):
using namespace std;
class A
{
public:
void CallFunction ();
};
class B: public A
{
public:
virtual void bFunction()
{
//stuff done here
}
};
// postpone definition of CallFunction here
void A::CallFunction ()
{
B b;
b.bFunction();
}
If you only have php code in one html file but have multiple other files that only contain html code, you can add the following to your .htaccess file so it will only serve that particular file as php.
<Files yourpage.html>
AddType application/x-httpd-php .html
//you may need to use x-httpd-php5 if you are using php 5 or higher
</Files>
This will make the PHP executable ONLY on the "yourpage.html" file and not on all of your html pages which will prevent slowdown on your entire server.
As to why someone might want to serve php via an html file, I use the IMPORTHTML function in google spreadsheets to import JSON data from an external url that must be parsed with php to clean it up and build an html table. So far I haven't found any way to import a .php file into google spreadsheets so it must be saved as an .html file for the function to work. Being able to serve php via an .html file is necessary for that particular use.
I recommend Dowser. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface.
# memdebug.py
import cherrypy
import dowser
def start(port):
cherrypy.tree.mount(dowser.Root())
cherrypy.config.update({
'environment': 'embedded',
'server.socket_port': port
})
cherrypy.server.quickstart()
cherrypy.engine.start(blocking=False)
You import memdebug, and call memdebug.start. That's all.
I haven't tried PySizer or Heapy. I would appreciate others' reviews.
UPDATE
The above code is for CherryPy 2.X
, CherryPy 3.X
the server.quickstart
method has been removed and engine.start
does not take the blocking
flag. So if you are using CherryPy 3.X
# memdebug.py
import cherrypy
import dowser
def start(port):
cherrypy.tree.mount(dowser.Root())
cherrypy.config.update({
'environment': 'embedded',
'server.socket_port': port
})
cherrypy.engine.start()
Why are you using WMI? Can't you use the standard .NET functionality?
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
I accidentally installed 'serial' (sudo python -m pip install serial
) instead of 'pySerial' (sudo python -m pip install pyserial
), which lead to the same error.
If the previously mentioned solutions did not work for you, double check if you installed the correct library.
In Laravel 8.x you can listen to the event by registering your query listener in a service provider as documented in laravel.com website.
//header
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
public function boot()
{
DB::listen(function ($query) {
Log::debug("SQL : " . $query->sql);
});
}
You can then see all the queries in the laravel.log file inside storage\logs\laravel.log
You don't want to synchronize on self... Since the self object doesn't exist yet! You end up locking on a temporary id value. You want to ensure that no one else can run class methods ( sharedInstance, alloc, allocWithZone:, etc ), so you need to synchronize on the class object instead:
@implementation MYSingleton
static MYSingleton * sharedInstance = nil;
+( id )sharedInstance {
@synchronized( [ MYSingleton class ] ) {
if( sharedInstance == nil )
sharedInstance = [ [ MYSingleton alloc ] init ];
}
return sharedInstance;
}
+( id )allocWithZone:( NSZone * )zone {
@synchronized( [ MYSingleton class ] ) {
if( sharedInstance == nil )
sharedInstance = [ super allocWithZone:zone ];
}
return sharedInstance;
}
-( id )init {
@synchronized( [ MYSingleton class ] ) {
self = [ super init ];
if( self != nil ) {
// Insert initialization code here
}
return self;
}
}
@end
Receiver converted to snake case: http://rubydoc.info/gems/extlib/0.9.15/String#snake_case-instance_method
This is the Support library for DataMapper and Merb. (http://rubygems.org/gems/extlib)
def snake_case
return downcase if match(/\A[A-Z]+\z/)
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
gsub(/([a-z])([A-Z])/, '\1_\2').
downcase
end
"FooBar".snake_case #=> "foo_bar"
"HeadlineCNNNews".snake_case #=> "headline_cnn_news"
"CNN".snake_case #=> "cnn"
for Google Maps v3, you need to trigger the resize event differently:
google.maps.event.trigger(map, "resize");
See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event
Update
This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.
$(function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map($("#map-canvas")[0], mapOptions);
// listen for the window resize event & trigger Google Maps to update too
$(window).resize(function() {
// (the 'map' here is the result of the created 'var map = ...' above)
google.maps.event.trigger(map, "resize");
});
});
_x000D_
html,
body {
height: 100%;
}
#map-canvas {
min-width: 200px;
width: 50%;
min-height: 200px;
height: 80%;
border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
UPDATE 2018-05-22
With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map
class.
The documentation states
When the map is resized, the map center is fixed
The full-screen control now preserves center.
There is no longer any need to trigger the resize event manually.
source: https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize");
doesn't have any effect starting from version 3.32
Please check the file "system/core/CodeIgniter.php". It is defined in const CI_VERSION = '3.1.10';
if (code.indexOf("ST1")>=0) { location = "stoke central"; }
Unfortunately for the top answer, Scala-IO is dead. If you don't mind using a third-party dependency, consider using my OS-Lib library. This makes working with files, paths and the filesystem very easy:
// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)
// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"
// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")
It has one-liners for writing to files, appending to files, overwriting files, and many other useful/common operations
Android SDK
Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
Cordova requires the ANDROID_HOME
environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk
directory (for example c:\android\android-sdk).
Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME
, you would add both %ANDROID_HOME%\tools
and %ANDROID_HOME%\platform-tools
.
Reference : http://ionicframework.com/docs/v1/guide/installation.html
That's what we have in our applications:
Attribute
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Actions decorated with it:
[HttpParamAction]
public ActionResult Save(MyModel model)
{
// ...
}
[HttpParamAction]
public ActionResult Publish(MyModel model)
{
// ...
}
HTML/Razor
@using (@Html.BeginForm())
{
<!-- form content here -->
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Publish" value="Publish" />
}
name
attribute of submit button should match action/method name
This way you do not have to hard-code urls in javascript
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");
You can use a redirect to that action :
redirect_to your_controller_action_url
More on : Rails Guide
To just render the new action :
redirect_to your_controller_action_url and return
This may also can help
input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile
Delete the .git
directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).
If you want to delete everything (git-data, code, etc), just delete the whole directory.
.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.
Regarding seek()
there's not too much to worry about.
First of all, it is useful when operating over an open file.
It's important to note that its syntax is as follows:
fp.seek(offset, from_what)
where fp
is the file pointer you're working with; offset
means how many positions you will move; from_what
defines your point of reference:
if omitted, from_what
defaults to 0.
Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek
will be useful to you when you need to walk
along that open file, just as a path you are traveling into.
in Mono Android you can use filter like this:
your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));
content: "";
background-image: url("yourimage.jpg");
background-size: 30px, 30px;
Deadlock is a situation occurs when there is less number of available resources as it is requested by the different process. It means that when the number of available resources become less than it is requested by the user then at that time the process goes in waiting condition .Some times waiting increases more and there is not any chance to check out the problem of lackness of resources then this situation is known as deadlock . Actually, deadlock is a major problem for us and it occurs only in multitasking operating system .deadlock can not occur in single tasking operating system because all the resources are present only for that task which is currently running......
An other cause of this problem is corruption of maven repository jars so you can use the following command to solve the problem :
mvn dependency:purge-local-repository
This will do the same as many of the other answers, but will make sides flush with the window, so there is no scroll bars.
<div class="container-fluid">
<div class="row">
<div class="col" style="padding: 0;">
<img src="example.jpg" class="img-responsive" alt="Example">
</div>
</div>
</div>
I faced this problem and this is how I solved it.
1) Delete all the migration records from your app's migration directory. These are files named 0001_,0002_,0003_ etc. Be careful as to not delete the _init__.py file.
2) Delete the db.sqlite3 file. It will be regenerated later.
Now, run the following commands:
python manage.py makemigrations appname
python manage.py migrate
Be sure to write the name of your app after makemigrations. You might have to create a superuser to access your database again. Do so by the following
python manage.py createsuperuser
I use FLTK because Qt is not free. I don't choose wxWidgets, because my first test with a simple Hello, World! program produced an executable of 24 MB, FLTK 0.8 MB...
The code below will write the 4 unicode chars (represented by decimals) for the word "be" in Japanese. Yes, the verb "be" in Japanese has 4 chars! The value of characters is in decimal and it has been read into an array of String[] -- using split for instance. If you have Octal or Hex, parseInt take a radix as well.
// pseudo code
// 1. init the String[] containing the 4 unicodes in decima :: intsInStrs
// 2. allocate the proper number of character pairs :: c2s
// 3. Using Integer.parseInt (... with radix or not) get the right int value
// 4. place it in the correct location of in the array of character pairs
// 5. convert c2s[] to String
// 6. print
String[] intsInStrs = {"12354", "12426", "12414", "12377"}; // 1.
char [] c2s = new char [intsInStrs.length * 2]; // 2. two chars per unicode
int ii = 0;
for (String intString : intsInStrs) {
// 3. NB ii*2 because the 16 bit value of Unicode is written in 2 chars
Character.toChars(Integer.parseInt(intsInStrs[ii]), c2s, ii * 2 ); // 3 + 4
++ii; // advance to the next char
}
String symbols = new String(c2s); // 5.
System.out.println("\nLooooonger code point: " + symbols); // 6.
// I tested it in Eclipse and Java 7 and it works. Enjoy
There is a great solution for this problem ,You can use the Merge Keyword of Sql
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
You can check this before following, below is the sample
IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
DROP TABLE dbo.TargetTable
GO
CREATE TABLE dbo.TargetTable
(
Id INT NOT NULL,
Name VARCHAR (255) NOT NULL,
CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
)
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
well, I know this is pretty old but I think that what you might need is:
var one = someObservable.take(1);
var two = someOtherObservable.pipe(
concatMap((twoRes) => one.pipe(mapTo(twoRes))),
take(1)
).subscribe((twoRes) => {
// one is completed and we get two's subscription.
})
Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).
You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.
# shell script ,ignore the first
$ $(dirname `which mysql`)\/mysql.server start
May be helpful.
Try this:
Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "xcopy.exe");
proc.StartInfo.Arguments = @"C:\source C:\destination /E /I";
proc.Start();
Your xcopy arguments may vary but you get the idea.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("file.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getChildNodes();
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("staff")) {
String name = el.getElementsByTagName("name").item(0).getTextContent();
String phone = el.getElementsByTagName("phone").item(0).getTextContent();
String email = el.getElementsByTagName("email").item(0).getTextContent();
String area = el.getElementsByTagName("area").item(0).getTextContent();
String city = el.getElementsByTagName("city").item(0).getTextContent();
}
}
}
Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE
is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.
For each node under stuff (name, phone, email, area, city)
el.getElementsByTagName("name").item(0).getTextContent();
el.getElementsByTagName("name")
will extract the "name" nodes under stuff,
.item(0)
will get you the first node
and .getTextContent()
will get the text content inside.
Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:
public class Staff {
private String name;
private String phone;
private String email;
private String area;
private String city;
...getters setters
}
Then using jackson:
JsonNode root = new XmlMapper().readTree(xml.getBytes());
ObjectMapper mapper = new ObjectMapper();
root.forEach(node -> consume(node, mapper));
private void consume(JsonNode node, ObjectMapper mapper) {
try {
Staff staff = mapper.treeToValue(node, Staff.class);
//TODO your job with staff
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
No siblings solution:
var x = $('#xxx').parent().html();
alert(x);
Universal solution:
// no cloning necessary
var x = $('#xxx').wrapAll('<div>').parent().html();
alert(x);
Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/
User interactive approach:
git clean -i -fd
Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y
-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)
Note: Add -n or --dry-run to just check what it will do.
Since it's in bootstrap 3, the site will be using jQuery. So the solution could also be the following, instead of trying to play with complex CSS:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<style>
.my-footer {
border-radius : 0px;
margin : 0px; /* pesky margin below .navbar */
position : absolute;
width : 100%;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<!-- Content of any length -->
asdfasdfasdfasdfs <br />
asdfasdfasdfasdfs <br />
asdfasdfasdfasdfs <br />
</div>
</div>
<div class="navbar navbar-inverse my-footer">
<div class="container-fluid">
<div class="row">
<p class="navbar-text">My footer content goes here...</p>
</div>
</div>
</div>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $docH = $(document).height();
// The document height will grow as the content on the page grows.
$('.my-footer').css({
/*
The default height of .navbar is 50px with a 1px border,
change this 52 if you change the height of your footer.
*/
top: ($docH - 52) + 'px'
});
});
</script>
</body>
</html>
A different take on it, hope it helps.
Kind regards.
alter table table_name add field_name (size);
alter table arnicsc add place number(10);
From your question, it is unclear as-to which columns you want to use to determine duplicates. The general idea behind the solution is to create a key based on the values of the columns that identify duplicates. Then, you can use the reduceByKey or reduce operations to eliminate duplicates.
Here is some code to get you started:
def get_key(x):
return "{0}{1}{2}".format(x[0],x[2],x[3])
m = data.map(lambda x: (get_key(x),x))
Now, you have a key-value RDD
that is keyed by columns 1,3 and 4.
The next step would be either a reduceByKey
or groupByKey
and filter
.
This would eliminate duplicates.
r = m.reduceByKey(lambda x,y: (x))
After coming back to my own question after 5 year and seeing so many people found this useful, a little update.
A string variable can be split into a list
by using the split function (it can contain similar values, set
is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
or
{% set list1 = variable1.split(';') %}
{% for item in list1 %}
<p>{{ item }}<p/>
{% endfor %}
or
{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}
eumiro's answer is better, however I'm just posting this for variety:
>>> "%08d" % int(bin(6)[2:])
00000110
Many of the answers are correct but I feel like they could be more complete / simplistic etc. for example :
Example 1 : Basic if statement
# BASH4+ example on Linux :
typeset read_file="/tmp/some-file.txt"
if [ ! -s "${read_file}" ] || [ ! -f "${read_file}" ] ;then
echo "Error: file (${read_file}) not found.. "
exit 7
fi
if $read_file is empty or not there stop the show with exit. More than once I have had misread the top answer here to mean the opposite.
Example 2 : As a function
# -- Check if file is missing /or empty --
# Globals: None
# Arguments: file name
# Returns: Bool
# --
is_file_empty_or_missing() {
[[ ! -f "${1}" || ! -s "${1}" ]] && return 0 || return 1
}
In the folder where you installed Anaconda (Example: C:\Users\username\Anaconda3
) there should be an executable called Uninstall-Anaconda.exe
. Double click on this file to start uninstall Anaconda.
That should do the trick as well.
You can just use nextLine();
as pause
import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);
void Read()
{
System.out.print("Press any key to continue . . . ");
scan.nextLine();
}
However any button you press except Enter
means you will have to press Enter after that but I found it better than scan.next();
Possible alternatives
js-floating-table-headers
js-floating-table-headers (Google Code)
In Drupal
I have a Drupal 6 site. I was on the admin "modules" page, and noticed the tables had this exact feature!
Looking at the code, it seems to be implemented by a file called tableheader.js
. It applies the feature on all tables with the class sticky-enabled
.
For a Drupal site, I'd like to be able to make use of that tableheader.js
module as-is for user content. tableheader.js
doesn't seem to be present on user content pages in Drupal. I posted a forum message to ask how to modify the Drupal theme so it's available. According to a response, tableheader.js
can be added to a Drupal theme using drupal_add_js()
in the theme's template.php
as follows:
drupal_add_js('misc/tableheader.js', 'core');
In addition to previous post you can have
<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />
Jsf 2.0
You cannot. A basic numeric constant is considered an integer (or long if followed by a "L"), so you must explicitly downcast it to a byte to pass it as a parameter. As far as I know there is no shortcut.
Not sure if it is what you want, but just simple example:
var input = document.getElementById('input');
input.addEventListener("change", function() {
var file = this.files[0];
var img = new Image();
img.onload = function() {
var sizes = {
width:this.width,
height: this.height
};
URL.revokeObjectURL(this.src);
console.log('onload: sizes', sizes);
console.log('onload: this', this);
}
var objectURL = URL.createObjectURL(file);
console.log('change: file', file);
console.log('change: objectURL', objectURL);
img.src = objectURL;
});
Use .push:
items.push({'id':5});
I'd use B because that in conjunction with worker process recycling means there'd only be a delay while it's recycling. This avoids the delay normally associated with initialization in response to the first request after idle. You also get to keep the benefits of recycling.
If you just want to convert the values to nice looking strings do the following:
twodecimals = ["%.2f" % v for v in vars]
Alternatively, you could also print out the units like you have in your question:
vars = [0, 1, 2, 3] # just some example values
units = ['kg', 'lb', 'gal', 'l']
delimiter = ', ' # or however you want the values separated
print delimiter.join(["%.2f %s" % (v,u) for v,u in zip(vars, units)])
Out[189]: '0.00 kg, 1.00 lb, 2.00 gal, 3.00 l'
The second way allows you to easily change the delimiter (tab, spaces, newlines, whatever) to suit your needs easily; the delimiter could also be a function argument instead of being hard-coded.
Edit: To use your 'name = value' syntax simply change the element-wise operation within the list comprehension:
print delimiter.join(["%s = %.2f" % (u,v) for v,u in zip(vars, units)])
Out[190]: 'kg = 0.00, lb = 1.00, gal = 2.00, l = 3.00'
You can use the ScriptManager.RegisterStartupScript();
to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();
, you can do this:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
//----or alternatively and to be more proper
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}
To be exact for you, do this...
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
In General to get rid of
Object of class stdClass could not be converted to string.
try to use echo '<pre>'; print_r($sql_query);
for my SQL Query got the result as
stdClass Object
(
[num_rows] => 1
[row] => Array
(
[option_id] => 2
[type] => select
[sort_order] => 0
)
[rows] => Array
(
[0] => Array
(
[option_id] => 2
[type] => select
[sort_order] => 0
)
)
)
In order to acces there are different methods E.g.: num_rows, row, rows
echo $query2->row['option_id'];
Will give the result as 2
it doesn't, however, solve the problem, because on e.g. open SUSE Tumbleweed, custom source build is triggering the same 401 error on default web page, which is configured accordingly with Indexes and
Require all granted
My problem was also the mysql.sock-file.
During the drupal installation process, i had to say which database i want to use but my database wasn't found
mkdir /var/mysql
ln -s /tmp/mysql.sock /var/mysql/mysql.sock
the system is searching mysql.sock but it's in the wrong directory
all you have to do is to link it ;)
it took me a lot of time to google all important informations but it took me even hours to find out how to adapt , but now i can present the result :D
ps: if you want to be exactly you have to link your /tmp/mysql.sock-file
(if it is located in your system there too) to the directory given by the php.ini (or php.default.ini) where pdo_mysql.default_socket= ...
This link explains how to apply a cell style to a range of cells: http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx
See this snippet:
Microsoft.Office.Tools.Excel.NamedRange rangeStyles =
this.Controls.AddNamedRange(this.Range["A1"], "rangeStyles");
rangeStyles.Value2 = "'Style Test";
rangeStyles.Style = "NewStyle";
rangeStyles.Columns.AutoFit();
here's a nice solution for putting a rotated drawable for an imageView:
Drawable getRotateDrawable(final Bitmap b, final float angle) {
final BitmapDrawable drawable = new BitmapDrawable(getResources(), b) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
super.draw(canvas);
canvas.restore();
}
};
return drawable;
}
usage:
Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);
another alternative:
private Drawable getRotateDrawable(final Drawable d, final float angle) {
final Drawable[] arD = { d };
return new LayerDrawable(arD) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
super.draw(canvas);
canvas.restore();
}
};
}
also, if you wish to rotate the bitmap, but afraid of OOM, you can use an NDK solution i've made here
This is what you need :
if (Value1.StartsWith("abc"))
{
found = true;
}
Just try beeprint
it prints something like this:
instance(Animal):
legs: 2,
name: 'Dog',
color: 'Spotted',
smell: 'Alot',
age: 10,
kids: 0,
I think is exactly what you need.
You should be able to use OrderBy
in LINQ...
var sortedItems = myList.OrderBy(s => s);
TensorFlow makes life easier. file path gives us the location of downloaded file.
import tensorflow as tf
tf.keras.utils.get_file(origin='https://storage.googleapis.com/tf-datasets/titanic/train.csv',
fname='train.csv',
untar=False, extract=False)
You have a ; at the end of the if
.
Change:
if (fp == NULL);
return 0;
to
if (fp == NULL)
return 0;
crypto now supports base64 (reference):
cipher.final('base64')
So you could simply do:
var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');
var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');
SQlite does not have a specific datetime type. You can use TEXT
, REAL
or INTEGER
types, whichever suits your needs.
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
- TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
- REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
- INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
SQLite built-in Date and Time functions can be found here.
For me, only git reset --hard
worked.
Commiting was not an option, as there was nothing to commit.
Stashing wasn't an option because there was nothing to stash.
Looks like it could have been from excluded files in .git/info/exclude
and having git update-index --assume-unchanged <file>
'ed some files.
I'm using yarn. I had to do the following to overcome the error.
yarn add @babel/plugin-proposal-class-properties --dev
pthread.h
isn't on Windows. But Windows has extensive threading functionality, beginning with CreateThread.
My advice is don't get caught looking at WinAPI through the lens of another system's API. These systems are different. It's like insisting on riding the Win32 bike with your comfortable Linux bike seat. Well, the seat might not fit right and in some cases it'll just fall off.
Threads pretty much work the same on different systems, you have ThreadPools and mutexes. Having worked with both pthreads
and Windows threads, I can say the Windows threading offers quite a bit more functionality than pthread
does.
Learning another API is pretty easy, just think in terms of the concepts (mutex, etc), then look up how to create one of those on MSDN.
IIRC, the ConfigurationManager.RefreshSection requires a string parameter specifying the name of the Section to refresh :
ConfigurationManager.RefreshSection("connectionStrings");
I think that the ASP.NET application should automatically reload when the ConnectionStrings element is modified and the configuration does not need to be manually reloaded.
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site