Since there is only one WiFi hardware on the computer its not possible to connect one WiFi hardware to multiple WiFi networks, if you want to that I think you have to map WiFi hardware to guest OS and how host you'll have to use some other hardware (may be Ethernet) but I'm sure that it will work in that way as no VM software allow us to allocate Hardware to Guest except for USB, you can also get USB WiFI and allocate that to VM only.
I had kafka running as a Docker container and similar messages were flooding to the log.
And KAFKA_ADVERTISED_HOST_NAME
was set to 'kafka'.
In my case the reason for error was the missing /etc/hosts
record for 'kafka' in 'kafka' container itself.
So, for example, running ping kafka
inside 'kafka' container would fail with ping: bad address 'kafka'
In terms of Docker this problem gets solved by specifying hostname
for the container.
Options to achieve it:
For me, ant apparently refuses to listen to any configuration for eclipse default, project JDK, and the suggestion of "Ant Home Entries" just didn't have traction - there was nothing there referring to JDK.
However, this works:
Menu "Run" -> "External Tools" -> "External Tools Configuration".
Goto the node "Ant build", choose the ant buildfile in question.
Choose tab "JRE".
Select e.g. "Run in same JRE as workspace", or whatever you want.
I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.
This two threads explain it better:
stClass is an empty class created by php itself , and should be used by php only, because it is not just an "empty" class , php uses stdClass to convert arrays to object style if you need to use stdClass , I recommend two better options : 1- use arrays (much faster than classes) 2- make your own empty class and use it
//example 1
$data=array('k1'=>'v1' , 'k2'=>'v2',....);
//example 2
//creating an empty class is faster than instances an stdClass
class data={}
$data=new data();
$data->k1='v1';
$data->k2='v2';
what makes someone to think about using the object style instead of array style???
That's as easy as
IsNull(FieldName, 0)
Or more completely:
SELECT iar.Description,
ISNULL(iai.Quantity,0) as Quantity,
ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail',
iar.Compliance
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
A slightly simper version in PHP of what others have posted:
if (!isset($_COOKIE, $_COOKIE['PHPSESSID'])) {
print '<script>top.window.location="https://example.com/?start_session=true";</script>';
exit();
}
if (isset($_GET['start_session'])) {
header("Location: https://apps.facebook.com/YOUR_APP_ID/");
exit();
}
The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from
and Deny from
directives that are preventing access. Read the mod_authz_host documentation for more details.
You should be able to solve this in your VirtualHost by adding something like:
<Location />
Allow from all
Order Deny,Allow
</Location>
Or alternatively with a Directory
directive:
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.
How about
Try like this..
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Your Prepared data.
List<double[]> values = new ArrayList<double[]>(2);
double[] element1 = new double[] { 100, 100, 100, 100, 100 };
double[] element2 = new double[] { 50, 35, 25, 45, 65 };
values.add(element1);
values.add(element2);
// Add the result to arraylist.
List<Double> temp = new ArrayList<Double>();
for(int j=0;j<values.size(); j++) {
for (int i = 0; i < values.get(0).length; i++) {
temp.add(values.get(0)[i]);
temp.add(values.get(1)[i]);
}
}
// Convert arraylist to int[].
Double[] result = temp.toArray(new Double[temp.size()]);
double[] finalResult = new double[result.length]; // This hold final result.
for (int i = 0; i < result.length; i++) {
finalResult[i] = result[i].doubleValue();
}
for (int i = 0; i < finalResult.length; i++) {
System.out.println(finalResult[i]);
}
}
}
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
You don't add any variables to the System Variables. You take the existing 'Path' system variable, and modify it by adding a semi-colon after, then c:\Python27
You will have to use Array.find
or Array.filter
or Array.forEach
.
Since you value is array and you need position of element, you will have to iterate over it.
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
if(item.name === val){
index = i;
return i;
}
});
console.log(index, filteredObj);
_x000D_
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var val = "allInterests"
var index = data.findIndex(function(item, i){
return item.name === val
});
console.log(index);
_x000D_
Default Array.indexOf()
will match searchValue to current element and not its properties. You can refer Array.indexOf - polyfill on MDN
Maybe this could be a little older article. but must of the above answers don´t help me as I need. Then I wrote a little snippet for that.
This accepts any XML that hast at least 3 levels (Like this sample):
<XmlData>
<XmlRow>
<XmlField1>Data 1</XmlField1>
<XmlField2>Data 2</XmlField2>
<XmlField3>Data 3</XmlField3>
.......
</XmlRow>
</XmlData>
public static class XmlParser
{
/// <summary>
/// Converts XML string to DataTable
/// </summary>
/// <param name="Name">DataTable name</param>
/// <param name="XMLString">XML string</param>
/// <returns></returns>
public static DataTable BuildDataTableFromXml(string Name, string XMLString)
{
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(XMLString));
DataTable Dt = new DataTable(Name);
try
{
XmlNode NodoEstructura = doc.FirstChild.FirstChild;
// Table structure (columns definition)
foreach (XmlNode columna in NodoEstructura.ChildNodes)
{
Dt.Columns.Add(columna.Name, typeof(String));
}
XmlNode Filas = doc.FirstChild;
// Data Rows
foreach (XmlNode Fila in Filas.ChildNodes)
{
List<string> Valores = new List<string>();
foreach (XmlNode Columna in Fila.ChildNodes)
{
Valores.Add(Columna.InnerText);
}
Dt.Rows.Add(Valores.ToArray());
}
} catch(Exception)
{
}
return Dt;
}
}
This solve my problem
I just come across this brilliantly simple solution if you are using .Net 4.5 (not supported this easily in lower versions) and you can use jQuery to make things really simple and painless.
Uploading Multiple Files Using jQuery and Generic Handler in ASP.Net 4.5
Of course there is the commercial version for classic ASP which can be found at ASP Uploader
leftclickben answer worked for me, but I wanted a path from a given node back up the tree to the root, and these seemed to be going the other way, down the tree. So, I had to flip some of the fields around and renamed for clarity, and this works for me, in case this is what anyone else wants too--
item | parent
-------------
1 | null
2 | 1
3 | 1
4 | 2
5 | 4
6 | 3
and
select t.item_id as item, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;
gives:
item | parent
-------------
6 | 3
3 | 1
1 | null
For Mac Users:
It could be that another instance of eclipse is running in the background. If so, use either Force Quit eclipse or
ps -ef |grep eclipse kill -9 pid
to all the eclipse instances, and start the new workspace
The problem was that the ID column wasn't getting any value. I saw on @Martin Smith SQL Fiddle that he declared the ID column with DEFAULT newid
and I didn't..
Try this:
$.ajax({
type: 'get',
url: 'manageproducts.do',
data: 'option=1',
success: function(data) {
availableProductNames = data.split(",");
alert(availableProductNames);
}
});
Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.
function unicode_to_textstring($str){
$rawstr = pack('H*', $str);
$newstr = iconv('UTF-16BE', 'UTF-8', $rawstr);
return $newstr;
}
$msg = '67714eac99c500200054006f006b0079006f002000530074006100740069006f006e003a0020';
echo unicode_to_textstring($str);
Visual examples help with this kind of question.
In order to create a gradient, you create an xml file in res/drawable. I am calling mine my_gradient_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
</shape>
You set it to the background of some view. For example:
<View
android:layout_width="200dp"
android:layout_height="100dp"
android:background="@drawable/my_gradient_drawable"/>
Set the angle
for a linear
type. It must be a multiple of 45 degrees.
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
Set the gradientRadius
for a radial
type. Using %p
means it is a percentage of the smallest dimension of the parent.
<gradient
android:type="radial"
android:gradientRadius="10%p"
android:startColor="#f6ee19"
android:endColor="#115ede" />
I don't know why anyone would use a sweep, but I am including it for completeness. I couldn't figure out how to change the angle, so I am only including one image.
<gradient
android:type="sweep"
android:startColor="#f6ee19"
android:endColor="#115ede" />
You can also change the center of the sweep or radial types. The values are fractions of the width and height. You can also use %p
notation.
android:centerX="0.2"
android:centerY="0.7"
A Pure Python solution.
Does not rely on either ANSI, or external commands.
Only your terminal has to have the ability to tell you how many lines are in view.
from shutil import get_terminal_size
print("\n" * get_terminal_size().lines, end='')
Python version >= 3.3.0
Who can't control backend for Options 405 Method Not Allowed
.
Workaround for Chrome browser.
execute in command line:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="path_to_profile"
Example:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\Users\vital\AppData\Local\Google\Chrome\User Data\Profile 2"
You could simply use:
select {
border: none;
outline: none;
scroll-behavior: smooth;
}
As the drop down list border is non editable you can not do anything with that but surely this will fix your initial outlook.
The data-reactid
attribute is a custom attribute used so that React can uniquely identify its components within the DOM.
This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).
{
id: '.1oqi7occu80',
node: DivRef,
children: [
{
id: '.1oqi7occu80.0',
node: SpanRef,
children: [
{
id: '.1oqi7occu80.0.0',
node: InputRef,
children: []
}
]
}
]
}
There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid
attributes.
<div data-reactid='.loqi70ccu80'>
<span data-reactid='.loqi70ccu80.0'>
<input data-reactid='.loqi70ccu80.0' />
</span>
</div>
It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid
attributes. This is called inflating the component tree.
You might also notice that if React renders at the client-side, it uses the data-reactid
attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML
then it inflates the component tree straight away, as a performance boost.
The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3
), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3
). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.
React 15 uses document.createElement
instead, so client rendered markup won't include these attributes anymore.
You can check if the value is undefined or null by simply using typeof:
if(typeof value == 'undefined'){
If these errors occur randomly, there is high probability that you encountered data-races. Please, check: do you modify shared memory pointers from different threads? Intel Thread Checker may help to detect such issues in multithreaded program.
RedirectToAction("actionName", "controllerName");
It has other overloads as well, please check up!
Also, If you are new and you are not using T4MVC, then I would recommend you to use it!
It gives you intellisence for actions,Controllers,views etc (no more magic strings)
A "Login" grants the principal entry into the SERVER.
A "User" grants a login entry into a single DATABASE.
One "Login" can be associated with many users (one per database).
Each of the above objects can have permissions granted to it at its own level. See the following articles for an explanation of each
There are 3 ways:
First way
You need specify the directory to store mysql data on your host machine. You can then remove the data container. Your mysql data will be saved on you local filesystem.
Mysql container definition must look like this:
mysql:
container_name: flask_mysql
restart: always
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
MYSQL_USER: 'test'
MYSQL_PASS: 'pass'
volumes:
- /opt/mysql_data:/var/lib/mysql
ports:
- "3306:3306"
Second way
Would be to commit the data container before typing docker-compose down
:
docker commit my_data_container
docker-compose down
Third way
Also you can use docker-compose stop
instead of docker-compose down
(then you don't need to commit the container)
You can use this:
window.setInterval(yourfunction, 10000);
function yourfunction() { alert('test'); }
you can put your json in a parameter and send it instead of put only your json in header:
$post_string= 'json_param=' . json_encode($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
//execute post
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
on the service side you can get your json string as a parameter:
$json_string = $_POST['json_param'];
$obj = json_decode($json_string);
then you can use your converted data as object.
Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.
Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.
Incase of string literals(character arrays defined at declaration), they are automatically
appended by \0
.
printf
prints using the format specifier and the address provided. Since, you use %s
it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'
Checking for MSIE only is not enough to detect IE. You need also "Trident" which is only used in IE11. So here is my solution which worked an versions 8 to 11.
$agent=strtoupper($_SERVER['HTTP_USER_AGENT']);
$isIE=(strpos($agent,'MSIE')!==false || strpos($agent,'TRIDENT')!==false);
select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''
You can see whether the output of the following code is 0 or not.
'import re
x=' beer '
len(re.findall('\s', x))
Maybe the solution someone is looking for is this:
Response.Redirect("/Sucesso")
This work when used in the View as well.
You can use this to get a name of any provided member:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
To get name of a variable:
string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
To get name of a parameter:
public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}
You can use the nameof operator for parameters, variables and properties alike:
string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);
If you are using a GNU compiler, the compiler can assemble a list of dependencies for you. Makefile fragment:
depend: .depend
.depend: $(SRCS)
rm -f "$@"
$(CC) $(CFLAGS) -MM $^ -MF "$@"
include .depend
or
depend: .depend
.depend: $(SRCS)
rm -f "$@"
$(CC) $(CFLAGS) -MM $^ > "$@"
include .depend
where SRCS
is a variable pointing to your entire list of source files.
There is also the tool makedepend
, but I never liked it as much as gcc -MM
SELECT [ReportId],
SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
(
SELECT DISTINCT [ReportId]
FROM Table1
) a
CROSS APPLY
(
SELECT [Email] + ', '
FROM Table1 AS B
WHERE A.[ReportId] = B.[ReportId]
FOR XML PATH('')
) D (EmailList)
Yes:
Use this to experiment with mailto form elements and link encoding.
You can enter subject, body (i.e. content), etc. into the form, hit the button and see the mailto html link that you can paste into your page.
You can even specify elements that are rarely known and used: cc, bcc, from emails.
Download .msi from https://www.mongodb.com/download-center#community
Double click install - complete option
Installation folder C:\Program Files\MongoDB\Server\3.6\bin
Create database folder in C:// - c:/data/db and c:/data/log and c:/data/log/mongo.log and set write permission if not
Open cmd prompt in Administrator mode , navigate to C:\Program Files\MongoDB\Server\3.6\bin
Type the following
C:\Program Files\MongoDB\Server\3.6\bin>mongod --dbpath="c:/data/db" --logpath="c:/data/log/mongo.log"
Check folder c:/data/db - there should be many files and folder
Create a config file named "mongo.config" ** inside C:\data\
Type the following to set the config values from newly created config file
C:\Program Files\MongoDB\Server\3.6\bin>mongod --config C:\data\mongo.config
Open another new cmd prompt in Administrator mode , navigate to C:\Program Files\MongoDB\Server\3.6\bin execute the following lines on the console.
Type the following to create service for MongoDB
C:\Program Files\MongoDB\Server\3.6\bin>mongod --install --config C:\data\mongo.config --logpath="c:/data/log/mongo.log"
If old MongoDB service exists then need to delete the old service first before mongod --install command, run the following in a new console to delete old mongodb service
SC STOP MongoDB
>> SC DELETE MongoDB
Type the following to start MongoDB
C:\Program Files\MongoDB\Server\3.6\bin>net start MongoDB
Type the following to stop MongoDB
C:\Program Files\MongoDB\Server\3.6\bin>net stop MongoDB
Now connect the DB on ip - 127.0.0.1 or 192.168.5.64 on port 27017 .
** File name - "mongo.config" , paste the following on config file -
bind_ip = 127.0.0.1,192.168.5.64
port = 27017
dbpath=C:\data\db
logpath=C:\data\log\mongo.log
Are you sure a core dump is what you want here? That will contain the raw guts of the running JVM, rather than java-level information. Perhaps a JVM heap dump is more what you need.
JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.
JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.
Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:
$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);
#!/bin/bash
word=$(echo 'Your Message' |fold -w 1)
for letter in ${word} ; do echo "${letter} is a letter"; done
Here is the output:
Y is a letter o is a letter u is a letter r is a letter M is a letter e is a letter s is a letter s is a letter a is a letter g is a letter e is a letter
PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.
So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.
As suggest by @TheMatrixRecoder took a bit of finding for me so maybe this will help someone else.
Unitick these options to prevent annoying automated formatting when you places a semicolon or hit return at the end of a line.
I encountered the same error. My linker command did have the rt library included -lrt
which is correct and it was working for a while. After re-installing Kubuntu it stopped working.
A separate forum thread suggested the -lrt
needed to come after the project object files.
Moving the -lrt
to the end of the command fixed this problem for me although I don't know the details of why.
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
$this->db->like('title', 'match', 'before');
// Produces: WHERE title LIKE '%match'
$this->db->like('title', 'match', 'after');
// Produces: WHERE title LIKE 'match%'
$this->db->like('title', 'match', 'both');
// Produces: WHERE title LIKE '%match%'
For that you need to install binary of GNU GCC compiler, which comes with MinGW package. You can download MinGW( and put it under C:/ ) and later you have to download gnu -c, c++ related Binaries, so select required package and install them(in the MinGW ). Then in the Code::Blocks, go to Setting, Compiler, ToolChain Executable. In that you will find Path, there set C:/MinGW. Then mentioned error will be vanished.
In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None
and usecols=[3,6]
for the 4th and 7th columns:
df = pd.read_csv(file_path, header=None, usecols=[3,6])
See the docs
I ended up using one extra view with desired background, added after TableView and placed under status bar:
self.CoverView = [[UIView alloc]init];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
self.CoverView.frame = CGRectMake(0,0,self.view.bounds.size.width,20);
}
self.CoverView.backgroundColor = [UIColor whiteColor];
self.TableView = [[UITableView alloc]initWithFrame:CGRectMake(0,
self.CoverView.bounds.size.height,XXX, YYY)];
[self.view addSubview:self.TableView];
[self.view addSubview:self.CoverView];
It's not very pretty, but it's rather simple solution, if you need work with xib-less views, and both IOS6 and IOS7
In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.
A "large" object is never a constant expression in C, even if the object is declared as const
.
Moreover, in C language, the term "constant" refers to literal constants (like 1
, 'a'
, 0xFF
and so on), enum members, and results of such operators as sizeof
. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.
For example, this is NOT a constant
const int N = 5; /* `N` is not a constant in C */
The above N
would be a constant in C++, but it is not a constant in C. So, if you try doing
static int j = N; /* ERROR */
you will get the same error: an attempt to initialize a static object with a non-constant.
This is the reason why, in C language, we predominantly use #define
to declare named constants, and also resort to #define
to create named aggregate initializers.
I accomplished this today by loading my SQL from a text file into one string. I then used the string Split function to separate the string into individual commands which were then sent to the server individually. Simples :)
Just realised that you need to split on \nGO just in case the letters GO appear in any of your table names etc. Guess I was lucky there!
Throwing in a late contribution:
^(?!\.)((^|\.)([1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d))){4}$
Of the answers I checked, they're either longer or incomplete in their verification. Longer, in my experience, means harder to overlook and therefore more prone to be erroneous. And I like to avoid repeating similar patters, for the same reason.
The main part is, of course, the test for a number - 0 to 255, but also making sure it doesn't allow initial zeroes (except for when it's a single one):
[1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d)
Three alternations - one for sub 100: [1-9]?\d
, one for 100-199: 1\d\d
and finally 200-255: 2(5[0-5]|[0-4]\d)
.
This is preceded by a test for start of line or a dot .
, and this whole expression is tested for 4 times by the appended {4}
.
This complete test for four byte representations is started by testing for start of line followed by a negative look ahead to avoid addresses starting with a .
: ^(?!\.)
, and ended with a test for end of line ($
).
get product images in magento using product id
$product_id = $_POST['product_id'];
$storeId = Mage::app()->getStore()->getId();
$loadpro = Mage::getModel('catalog/product')->load($product_id);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApiItems = $mediaApi->items($loadpro->getId());
foreach ($mediaApiItems as $item) {
//for getting existing Images
echo $item['file'];
}
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.
public static class DateTimeWithZone
{
private static readonly TimeZoneInfo timeZone;
static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}
public static DateTime LocalTime(this DateTime t)
{
return TimeZoneInfo.ConvertTime(t, timeZone);
}
}
I'd like to propose
np.min(np.append(np.where(aa>5)[0],np.inf))
This will return the smallest index where the condition is met, while returning infinity if the condition is never met (and where
returns an empty array).
this code worked for me..
//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
For this to work, you must have the following permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
It looks like what you want to do is remove your first merge. You could follow the following procedure:
git checkout master # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull # or git merge remote/master
git merge topic
That would give you what you want.
Here is how I implemented the encoding. I took inspiration from the answers given above.
function encodeHTML(str) {
const code = {
' ' : ' ',
'¢' : '¢',
'£' : '£',
'¥' : '¥',
'€' : '€',
'©' : '©',
'®' : '®',
'<' : '<',
'>' : '>',
'"' : '"',
'&' : '&',
'\'' : '''
};
return str.replace(/[\u00A0-\u9999<>\&''""]/gm, (i)=>code[i]);
}
// TEST
console.log(encodeHTML("Dolce & Gabbana"));
console.log(encodeHTML("Hamburgers < Pizza < Tacos"));
console.log(encodeHTML("Sixty > twelve"));
console.log(encodeHTML('Stuff in "quotation marks"'));
console.log(encodeHTML("Schindler's List"));
console.log(encodeHTML("<>"));
_x000D_
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.setLayoutParams(labelLayoutParams);
// If you want to add some controls in this Relative Layout
labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView mImage = new ImageView(this);
mImage.setBackgroundResource(R.drawable.popupnew_bg);
layout.addView(mImage,labelLayoutParams);
setContentView(layout);
alert("xxxxxxxxxxx_456".substr(-3))
caveat: according to mdc, not IE compatible
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
If you didn't want to use a regular expression...
var chunks = [];
for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
chunks.push(str.substring(i, i + 3));
}
...otherwise the regex solution is pretty good :)
You can do the folllwoing: import the jar file inside you class:
import javax.servlet.http.HttpServletResponse
add the Apache Tomcat library as follow:
Project > Properties > Java Build Path > Libraries > Add library from library tab > Choose server runtime > Next > choose Apache Tomcat v 6.0 > Finish > Ok
Also First of all, make sure that Servlet jar is included in your class path in eclipse as PermGenError said.
I think this will solve your error
For PostgreSQL example:
UPDATE TableA AS a
SET param_from_table_a=FALSE -- param FROM TableA
FROM TableB AS b
WHERE b.id=a.param_id AND a.amount <> 0;
Try like this for query string:
from flask import Flask, request
app = Flask(__name__)
@app.route('/parameters', methods=['GET'])
def query_strings():
args1 = request.args['args1']
args2 = request.args['args2']
args3 = request.args['args3']
return '''<h1>The Query String are...{}:{}:{}</h1>''' .format(args1,args2,args3)
if __name__ == '__main__':
app.run(debug=True)
#import <Foundation/Foundation.h>
// clang -framework Foundation Siegfried.m
int
main() {
NSArray *arr = @[
@{@"1" : @"Fafner"},
@{@"1" : @"Fasolt"}
];
NSPredicate *p = [NSPredicate predicateWithFormat:
@"SELF['1'] CONTAINS 'e'"];
NSArray *res = [arr filteredArrayUsingPredicate:p];
NSLog(@"Siegfried %@", res);
return 0;
}
Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-
There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.
Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/
The visible width of an element is width + padding + border + outline
, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width
on the input, or making your div wider.
Install PAR::Packer from CPAN (it is free) and use pp utility.
This gives a sorted list:
find . -type f -ls 2>/dev/null | sort -M -k8,10 | head -n5
Reverse the order by placing a '-r' in the sort command. If you only want filenames, insert "awk '{print $11}' |" before '| head'
and at the same time for Cordova (a.k.a Phonegap), React-Native and all other development platforms
Format : 9-Patch PNG (recommended)
Dimensions
- LDPI:
- Portrait: 200x320px
- Landscape: 320x200px
- MDPI:
- Portrait: 320x480px
- Landscape: 480x320px
- HDPI:
- Portrait: 480x800px
- Landscape: 800x480px
- XHDPI:
- Portrait: 720px1280px
- Landscape: 1280x720px
- XXHDPI
- Portrait: 960x1600px
- Landscape: 1600x960px
- XXXHDPI
- Portrait: 1280x1920px
- Landscape: 1920x1280px
Note: Preparing XXXHDPI is not needed and also maybe XXHDPI size too because of the repeating areas of 9-patch images. On the other hand, if only Portrait sizes are used the App size could be more less. More pictures mean more space is need.
I think there is no an exact size for the all devices. I use Xperia Z 5". If you develop a crossplatform-webview app you should consider a lot of things (whether screen has softkey navigation buttons or not, etc). Therefore, I think there is only one suitable solution. The solution is to prepare a 9-patch splash screen (find How to design a new splash screen
heading below).
That's it!
Cordova specific code
To be added lines into the config.xml for 9-patch splash screens
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="6000" />
<platform name="android">
<splash src="res/screen/android/ldpi.9.png" density="ldpi"/>
<splash src="res/screen/android/mdpi.9.png" density="mdpi"/>
<splash src="res/screen/android/hdpi.9.png" density="hdpi"/>
<splash src="res/screen/android/xhdpi.9.png" density="xhdpi"/>
</platform>
To be added lines into the config.xml when using non-9-patch splash screens
<platform name="android">
<splash src="res/screen/android/splash-land-hdpi.png" density="land-hdpi"/>
<splash src="res/screen/android/splash-land-ldpi.png" density="land-ldpi"/>
<splash src="res/screen/android/splash-land-mdpi.png" density="land-mdpi"/>
<splash src="res/screen/android/splash-land-xhdpi.png" density="land-xhdpi"/>
<splash src="res/screen/android/splash-port-hdpi.png" density="port-hdpi"/>
<splash src="res/screen/android/splash-port-ldpi.png" density="port-ldpi"/>
<splash src="res/screen/android/splash-port-mdpi.png" density="port-mdpi"/>
<splash src="res/screen/android/splash-port-xhdpi.png" density="port-xhdpi"/>
</platform>
I would describe a simple way to create proper splash screen using this way. Assume we're designing a 1280dp x 720dp - xhdpi (x-large) screen. I've written for the sake of example the below;
In Photoshop: File -> New in new dialog window set your screens
Width: 720 Pixels Height: 1280 Pixels
I guess the above sizes mean Resolution is 320 Pixels/Inch. But to ensure you can change resolution value to 320 in your dialog window. In this case Pixels/Inch = DPI
Congratulations... You have a 720dp x 1280dp splash screen template.
After you designed your splash screen, if you want to design 9-Patch splash screen, you should insert 1 pixel gap for every side. For this reason you should increase +2 pixel your canvas size's width and height ( now your image sizes are 722 x 1282 ).
I've left the blank 1 pixel gap at every side as directed the below.
Changing the canvas size by using Photoshop:
- Open a splash screen png file in Photoshop
- Click onto the lock icon next to the 'Background' name in the Layers field (to leave blank instead of another color like white) if there is like the below:
- Change the canvas size from Image menu ( Width: 720 pixels to 722 pixels and Height: 1280 pixels to 1282 pixels). Now, should see 1 pixel gap at every side of the splash screen image.
Then you can use C:\Program Files (x86)\Android\android-studio\sdk\tools\draw9patch.bat to convert a 9-patch file. For that open your splash screen on draw9patch app. You should define your logo and expandable areas. Notice the black line the following example splash screen. The black line's thickness is just 1 px ;) Left and Top sides black lines define your splash screen's must display area. Exactly as your designed. Right and Bottom lines define the addable and removable area (automatically repeating areas).
Just do that: Zoom your image's top edge on draw9patch application. Click and drag your mouse to draw line. And press shift + click and drag your mouse to erase line.
If you develop a cross-platform app (like Cordova/PhoneGap) you can find the following address almost all mabile OS splash screen sizes. Click for Windows Phone, WebOS, BlackBerry, Bada-WAC and Bada splash screen sizes.
https://github.com/phonegap/phonegap/wiki/App-Splash-Screen-Sizes
And if you need IOS, Android etc. app icon sizes you can visit here.
Format : PNG (recommended)
Dimensions
- Tablet (iPad)
- Non-Retina (1x)
- Portrait: 768x1024px
- Landscape: 1024x768px
- Retina (2x)
- Portrait: 1536x2048px
- Landscape: 2048x1536px
- Handheld (iPhone, iPod)
- Non-Retina (1x)
- Portrait: 320x480px
- Landscape: 480x320px
- Retina (2x)
- Portrait: 640x960px
- Landscape: 960x640px
- iPhone 5 Retina (2x)
- Portrait: 640x1136px
- Landscape: 1136x640px
- iPhone 6 (2x)
- Portrait: 750x1334px
- Landscape: 1334x750px
- iPhone 6 Plus (3x)
- Portrait: 1242x2208px
- Landscape: 2208x1242px
If you think less code means more efficient, so using construct function is better. You also can use code like:
Person p=new Person(){
Name='abc',
Age=15
}
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.
To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.
The following will return the string represention you wanted:
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)
Use a HTML parser like DOMDocument
and then evaluate the value you're looking for with DOMXpath
:
$html = '<img id="12" border="0" src="/images/image.jpg"
alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"
Or for those who really need to save space:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
And for the one-liners out there:
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));
Open Git Bash.
Set a Git username:
$ git config --global user.name "name family" Confirm that you have set the Git username correctly:
$ git config --global user.name
name family
Set a Git email:
$ git config --global user.email [email protected] Confirm that you have set the Git email correctly:
$ git config --global user.email
You don't actually need to run a command from an xterm session, you can run it directly:
String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();
If the process responds interactively to the input stream, and you want to inject values, then do what you did before:
OutputStream out = proc.getOutputStream();
out.write("command\n");
out.flush();
Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.
We can write directly too...
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter
AND REGION = 'WY'
Both these will work
You can use Hash Map as given in the example below:
import java.util.HashMap;
import java.util.Set;
/**
*
* @author Abdul Rab Khan
*
*/
public class CounterExample {
public static void main(String[] args) {
String[] array = { "name1", "name1", "name2", "name2", "name2" };
countStringOccurences(array);
}
/**
* This method process the string array to find the number of occurrences of
* each string element
*
* @param strArray
* array containing string elements
*/
private static void countStringOccurences(String[] strArray) {
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
for (String string : strArray) {
if (!countMap.containsKey(string)) {
countMap.put(string, 1);
} else {
Integer count = countMap.get(string);
count = count + 1;
countMap.put(string, count);
}
}
printCount(countMap);
}
/**
* This method will print the occurrence of each element
*
* @param countMap
* map containg string as a key, and its count as the value
*/
private static void printCount(HashMap<String, Integer> countMap) {
Set<String> keySet = countMap.keySet();
for (String string : keySet) {
System.out.println(string + " : " + countMap.get(string));
}
}
}
If using Angular Material Design, you can use the datepicker component there and this will work in Firefox, IE etc.
https://material.angularjs.org/latest/demo/datepicker
Fair warning though - personal experience is that there are problems with this, and seemingly it is being re-worked at present. See here:
For me the solution is to change Enable 32-bit Applications to False
None of the answers worked for me. So I'd like to share what I found after hours of research..
Keep seeing this message from event logs: The Module DLL C:\Windows\system32\RpcProxy\RpcProxy.dll failed to load. The data is the error.
Turns out that dll is 64bit and cannot be loaded into 32bit process.
It's all in your things.size()
type. It isn't int
, but size_t
(it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int
for x86_32.
Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.
It would be correct to write it like
for (size_t i = 0; i < things.size(); ++i) { /**/ }
or even faster
for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }
Simple and easy :
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
Other bash alternatives that do not involve a subshell:
read str <<END # here-doc
hello
END
read str <<< "hello" # here-string
read str < <(echo hello) # process substitution
If you want to get the exact date of another commit (say you rebase edited a commit and want it to have the date of the original pre-rebase version):
git commit --amend --date="$(git show -s --format=%ai a383243)"
This corrects the date of the HEAD commit to be exactly the date of commit a383243 (include more digits if there are ambiguities). It will also pop up an editor window so you can edit the commit message.
That's for the author date which is what you care for usually - see other answers for the committer date.
here's a native javascript inline code to change image onmouseover & onmouseout:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png" onmouseover="this.src='/ico/view.hover.png'" onmouseout="this.src='/ico/view.png'" />
</a>
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.
I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json
${#str_var}
where str_var
is your string.
Note: my answer is about really deleting the tables and other database objects; for deleting all data in the tables, i.e. truncating all tables, Endre Both has provided a similarily well-executed (direct execution) statement a month later.
For the cases where you can’t just DROP SCHEMA public CASCADE;
, DROP OWNED BY current_user;
or something, here’s a stand-alone SQL script I wrote, which is transaction-safe (i.e. you can put it between BEGIN;
and either ROLLBACK;
to just test it out or COMMIT;
to actually do the deed) and cleans up “all” database objects… well, all those used in the database our application uses or I could sensibly add, which is:
CHECK
, UNIQUE
)VIEW
s (normal or materialised)public
or DB-internal) schemata “we” own: the script is useful when run as “not a database superuser”; a superuser can drop all schemata (the really important ones are still explicitly excluded, though)Not dropped are (some deliberate; some only because I had no example in our DB):
public
schema (e.g. for extension-provided stuff in them)This is really useful for the cases when the dump you want to restore is of a different database schema version (e.g. with Debian dbconfig-common
, Flyway or Liquibase/DB-Manul) than the database you want to restore it into.
I’ve also got a version which deletes “everything except two tables and what belongs to them” (a sequence, tested manually, sorry, I know, boring) in case someone is interested; the diff is small. Contact me or check this repo if interested.
-- Copyright © 2019, 2020
-- mirabilos <[email protected]>
--
-- Provided that these terms and disclaimer and all copyright notices
-- are retained or reproduced in an accompanying document, permission
-- is granted to deal in this work without restriction, including un-
-- limited rights to use, publicly perform, distribute, sell, modify,
-- merge, give away, or sublicence.
--
-- This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
-- the utmost extent permitted by applicable law, neither express nor
-- implied; without malicious intent or gross negligence. In no event
-- may a licensor, author or contributor be held liable for indirect,
-- direct, other damage, loss, or other issues arising in any way out
-- of dealing in the work, even if advised of the possibility of such
-- damage or existence of a defect, except proven that it results out
-- of said person’s immediate fault when using the work as intended.
-- -
-- Drop everything from the PostgreSQL database.
DO $$
DECLARE
q TEXT;
r RECORD;
BEGIN
-- triggers
FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pt.tgisinternal=false
) LOOP
EXECUTE format('DROP TRIGGER %I ON %I.%I;',
r.tgname, r.nspname, r.relname);
END LOOP;
-- constraints #1: foreign key
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype='f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- constraints #2: the rest
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype<>'f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- indices
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='i'
) LOOP
EXECUTE format('DROP INDEX %I.%I;',
r.nspname, r.relname);
END LOOP;
-- normal and materialised views
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind IN ('v', 'm')
) LOOP
EXECUTE format('DROP VIEW %I.%I;',
r.nspname, r.relname);
END LOOP;
-- tables
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='r'
) LOOP
EXECUTE format('DROP TABLE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- sequences
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='S'
) LOOP
EXECUTE format('DROP SEQUENCE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- extensions (only if necessary; keep them normally)
FOR r IN (SELECT pns.nspname, pe.extname
FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
WHERE pns.oid=pe.extnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
) LOOP
EXECUTE format('DROP EXTENSION %I;', r.extname);
END LOOP;
-- aggregate functions first (because they depend on other functions)
FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pagg.aggfnoid=pp.oid
) LOOP
EXECUTE format('DROP AGGREGATE %I.%I(%s);',
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- routines (functions, aggregate functions, procedures, window functions)
IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='prokind' -- PostgreSQL 11+
) THEN
q := 'CASE pp.prokind
WHEN ''p'' THEN ''PROCEDURE''
WHEN ''a'' THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='proisagg' -- PostgreSQL =10
) THEN
q := 'CASE pp.proisagg
WHEN true THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSE
q := '''FUNCTION''';
END IF;
FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
' LOOP
EXECUTE format('DROP %s %I.%I(%s);', r.pt,
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- non-default schemata we own; assume to be run by a not-superuser
FOR r IN (SELECT pns.nspname
FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
WHERE pr.oid=pns.nspowner
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
AND pr.rolname=current_user
) LOOP
EXECUTE format('DROP SCHEMA %I;', r.nspname);
END LOOP;
-- voilà
RAISE NOTICE 'Database cleared!';
END; $$;
Tested, except later additions (extensions
contributed by Clément Prévost), on PostgreSQL 9.6 (jessie-backports
). Aggregate removal tested on 9.6 and 12.2, procedure removal tested on 12.2 as well. Bugfixes and further improvements welcome!
The memory associated with arr
is freed automatically when arr
goes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.
A simple rule for you to follow is that you must only every call free()
on a pointer that was returned by a call to malloc
, calloc
or realloc
.
You could also use Joe Blau's gitignore.io
Either through the web interfase https://www.gitignore.io/
Or by installing the CLI tool, it's very easy an fast, just type the following on your terminal:
Linux:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bashrc && source ~/.bashrc
OSX:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bash_profile && source ~/.bash_profile
And then you can just type gi
followd by the all the platform/environment elements you need gitignore criteria for.
Example!
Lets say you're working on a node project that includes grunt and you're using webstorm on linux, then you may want to type:
gi linux,webstorm,node,grunt > .gitignore
( to make a brand new file)
or
gi linux,webstorm,node,grunt >> .gitignore
( to append/add the new rules to an existing file)
bam, you're good to go
See this link
Resize or Modify a MS SQL Server Table Column with Default Constraint using T-SQL Commands
the solution for such a SQL Server problem is going to be
Dropping or disabling the DEFAULT Constraint on the table column.
Modifying the table column data type and/or data size.
Re-creating or enabling the default constraint back on the sql table column.
Bye
I get the best looking results by using a 9 patch graphic.
You can simply create an individual 9 patch graphic by using the following editor: http://inloop.github.io/shadow4android/
Example:
The 9 patch graphic:
The result:
The source:
<LinearLayout
android:layout_width="200dp"
android:layout_height="200dp"
android:orientation="vertical"
android:background="@drawable/my_nine_patch"
You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;
readonly MyStruct[] MyArray = new MyStruct[]{
new MyStruct{ label = "a", id = 1},
new MyStruct{ label = "b", id = 5},
new MyStruct{ label = "c", id = 1}
};
Thx to @Alexander.Iljushkin for:
gem update --system --source http://rubygems.org/
After that bundler still failed and the solution to that was:
gem install bundler
As usual, create an SSH key and paste the public key to GitHub. Add the private key to ssh-agent. (I assume this is what you have done.)
To check everything is correct, use ssh -T [email protected]
Next, don't forget to modify the remote point as follows:
git remote set-url origin [email protected]:username/your-repository.git
h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:
<h:form>
<h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>
this code generates the follwing html:
<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">
whereas the h:button is simpler and just used for static or rule based navigation as follows
<h:button outcome="page.xhtml" value="button"/>
the generated html is
<title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />
If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.
As previously mentioned, just multiplying by -1 is not cool, as int.MinValue * -1 == int.MinValue
It really depends on your application, but for mine (Inverting Joystick axes) I want to ensure that all extremes are still reachable, and maintain as much fidelity as possible.
To this end, I map Max <--> Min and everything in-between gets a * -1
Using this technique, -32767 is unreachable when inverting.
private static int Invert(int value)
{
if (value == int.MaxValue) return int.MinValue;
if (value == int.MinValue) return int.MaxValue;
return value * -1;
}
Simply add your themes to the font link separated by a pipe (|
), like this
<link href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined" rel="stylesheet">
Then reference the class, like this:
// class="material-icons" or class="material-icons-outlined"
<i class="material-icons">account_balance</i>
<i class="material-icons-outlined">account_balance</i>
This pattern will also work with Angular Material:
<mat-icon>account_balance</mat-icon>
<mat-icon class="material-icons-outlined">account_balance</mat-icon>
There are a few characters which can indicate a new line. The usual ones are these two: '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF). '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).
Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:
DOS and Windows
They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).
Unix (and hence Linux as well)
Unix uses a single '\n' to indicate a new line.
Mac
Macs use a single '\r'.
jQuery's each(callback)
method uses for( ; ; )
loop by default, and will use for( in )
only if the length is undefined
.
Therefore, I would say it is safe to assume the correct order when using this function.
Example:
$(['a','b','c']).each(function() {
alert(this);
});
//Outputs "a" then "b" then "c"
The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The each()
function is probably best reserved for use with jQuery selectors and for( ; ; )
might be advisable otherwise.
Even if you do not have the pid, you can trigger 'wait;' after triggering all background processes. For. eg. in commandfile.sh-
bteq < input_file1.sql > output_file1.sql &
bteq < input_file2.sql > output_file2.sql &
bteq < input_file3.sql > output_file3.sql &
wait
Then when this is triggered, as -
subprocess.call(['sh', 'commandfile.sh'])
print('all background processes done.')
This will be printed only after all the background processes are done.
Take a peek at the ng-click
directive source:
...
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
It shows how the event
object is being passed on to the ng-click
expression, using $event
as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event
object any other way but through the callback parameter.
Have you tried the SVG text element?
.append("text").text(function(d, i) { return d[whichevernode];})
rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>
) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>
)
Append the text element as a sibling and work on positioning.
UPDATE
Using g grouping, how about something like this? fiddle
You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)
As per my understanding sys.stdout.flush() pushes out all the data that has been buffered to that point to a file object. While using stdout, data is stored in buffer memory (for some time or until the memory gets filled) before it gets written to terminal. Using flush() forces to empty the buffer and write to terminal even before buffer has empty space.
To sum up, the quick linkedlist method:
List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);
It is bad practice to throw Exception, as that requires anyone who calls your constructor to catch Exception which is a bad practice.
It is a good idea to have a constructor (or any method) throw an exception, generally speaking IllegalArgumentException, which is unchecked, and thus the compiler doesn't force you to catch it.
You should throw checked exceptions (things that extend from Exception, but not RuntimeException) if you want the caller to catch it.
In the XML file set the android:checkedButton
field in your RadioGroup
, with the id of your default RadioButton
:
<RadioGroup
....
android:checkedButton="@+id/button_1">
<RadioButton
android:id="@+id/button_1"
...../>
<RadioButton
android:id="@+id/button_2"
...../>
<RadioButton
android:id="@+id/button_3"
...../>
</RadioGroup>
SELECT t1.credit,
t2.debit
FROM (SELECT Sum(c.total_amount) AS credit
FROM credit c
WHERE c.status = "a") AS t1,
(SELECT Sum(d.total_amount) AS debit
FROM debit d
WHERE d.status = "a") AS t2
If you're allowed to use predefined Java classes, you could do something like:
private static ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
Then you can add new elements, something like:
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
biDemArrList.add(temp);
Hope you can understand what I mean and what's going on. Also, you'll need to import java.util.ArrayList; for this, if you're making use of the Java class.
Add this in the head section of your html
<link rel="icon" type="image/gif/png" href="mouse_select_left.png">
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
A simple way would be to use pandas. I adapted an example from the plotting documentation:
In [1]: import pandas as pd, numpy as np
In [2]: df = pd.DataFrame(np.random.rand(12,2), columns=['Apples', 'Oranges'] )
In [3]: df['Categories'] = pd.Series(list('AAAABBBBCCCC'))
In [4]: pd.options.display.mpl_style = 'default'
In [5]: df.boxplot(by='Categories')
Out[5]:
array([<matplotlib.axes.AxesSubplot object at 0x51a5190>,
<matplotlib.axes.AxesSubplot object at 0x53fddd0>], dtype=object)
Typescript
async resizeImg(file: Blob): Promise<Blob> {
let img = document.createElement("img");
img.src = await new Promise<any>(resolve => {
let reader = new FileReader();
reader.onload = (e: any) => resolve(e.target.result);
reader.readAsDataURL(file);
});
await new Promise(resolve => img.onload = resolve)
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let MAX_WIDTH = 1000;
let MAX_HEIGHT = 1000;
let width = img.naturalWidth;
let height = img.naturalHeight;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
return result;
}
You can also open a new tab calling to an action method with parameter like this:
var reportDate = $("#inputDateId").val();
var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
window.open(window.location.href = url.replace('findme', reportDate), '_blank');
I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.
$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});
All you'd need in your case is:
return expression;
The reason why is that the expression itself evaluates to a boolean value of true
or false
, so it's redundant to have an if
block (or even a ?:
operator).
Returning false
from the function will stop the event continuing. I.e. it will stop the form submitting.
i.e.
function someFunction()
{
if (allow) // For example, checking that a field isn't empty
{
return true; // Allow the form to submit
}
else
{
return false; // Stop the form submitting
}
}
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column
.
or you can check against last 90 days.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE())
You could use an anonymous type:
.Select(i => new { i.name, i.category_name })
The compiler will generate the code for a class with name
and category_name
properties and returns instances of that class. You can also manually specify property names:
i => new { Id = i.category_id, Name = i.category_name }
You can have arbitrary number of properties.
echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';
I think that's what you're looking for?
In other words, use htmlspecialchars() in PHP
If you just want the bug fix to be integrated into the branch, git cherry-pick
the relevant commit(s).
Integer
objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer
and replace the existing one.
playerID = new Integer(playerID.intValue() + 1);
I believe to check if a key exists in a hash you just do
if (exists $strings{$string}) {
...
} else {
...
}
If you like to write CoffeeScript you could do:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript actually IS javascript, but with a much better syntax.
For an overview of CoffeeScript check this beginner's guide.
We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.
use range, or DateDiff function
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test
where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test
Add DateOnly As
DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test
Add DateOnly As
Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test
where DateOnly = '03/19/2014'
For Windows:
You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.
Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.
Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.
Set the DNS Record type you wish to lookup by typing set type=##
where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.
Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.
NSLOOKUP will now return the record entries for the domain you entered.
You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.
Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)
For Linux:
1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.
2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.
Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.
Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.
3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.
Centerlized Model: You can use it from any where!
You just need to call Below Format From your function to this class
DataSet ds = new DataSet();
SqlParameter[] p = new SqlParameter[1];
string Query = "Describe Query Information/either sp, text or TableDirect";
DbConnectionHelper dbh = new DbConnectionHelper ();
ds = dbh. DBConnection("Here you use your Table Name", p , string Query, CommandType.StoredProcedure);
That's it. it's perfect method.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = @ "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:
$contents = (string) $response->getBody();
You can also do it with
$contents = $response->getBody()->getContents();
The difference between the two approaches is that getContents
returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind
or seek
.
$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents
Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.
$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents
Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses
Looking again at your question, I think I see what's wrong with your conf file. You set:
fullresolution=1366x768 windowresolution=1366x768
That's why you're getting the letterboxing (black on either side). You've essentially told Dosbox that your screen is the same size as your window, but your screen is actually bigger, 1600x900 (or higher) per the Googled specs for that computer. So the 'difference' shows up in black. So you either should change fullresolution to your actual screen resolution, or revert to fullresolution=original default, and only specify the window resolution.
So now I wonder if you really want fullscreen, though your question asks about only a window. For you are getting a window, but you sized it short of your screen, hence the two black stripes (letterboxing). If you really want fullscreen, then you need to specify the actual resolution of your screen. 1366x768 is not big enough.
The next issue is, what's the resolution of the program itself? It won't go past its own resolution. So if the program/game is (natively) say 1280x720 (HD), then your window resolution setting shouldn't be bigger than that (remember, it's fixed not dynamic when you use AxB as windowresolution).
Example: DOS Lotus 123 will only extend eight columns and 20 rows. The bigger the Dosbox, the bigger the text, but not more columns and rows. So setting a higher windowresolution for that, only results in bigger text, not more columns and rows. After that you'll have letterboxing.
Hope this helps you better.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
if the project is not a big ,
1- change the name of folder project
2- make a new project with the same project (before renaming)
3- add existing files from the old project to the new project (totally same , same folders , same names , ...)
4- open the the new project file (as xml ) and the old project
5- copy the new project file (xml content ) and paste it in the old project file
6- delete the old project
7- rename the old folder project to old name
Try this to fix the error:
node_modules
directory.npm i gulp-sass@latest --save-dev
I just had this issue from a namespace mismatch. My XAML file was getting ported over and it had a different namespace from that in the code behind file.
For me the solution was: Settings
? Version Control
? Git
? Use Credential helper
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
You can set the border by two methods. One is by drawable and the second is programmatic.
<shape>
<solid android:color="@color/txt_white"/>
<stroke android:width="1dip" android:color="@color/border_gray"/>
<corners android:bottomLeftRadius="10dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="10dp"
android:topRightRadius="0dp"/>
<padding android:bottom="0dip"
android:left="0dip"
android:right="0dip"
android:top="0dip"/>
</shape>
Programmatic
public static GradientDrawable backgroundWithoutBorder(int color) {
GradientDrawable gdDefault = new GradientDrawable();
gdDefault.setColor(color);
gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
radius, radius });
return gdDefault;
}
Here’s another algorithm for ensuring the numbers are unique:
Compared to the method of generating random numbers until you get a unique one, this method uses more memory, but it has a more stable running time – the results are guaranteed to be found in finite time. This method works better if the upper limit is relatively low or if the amount to take is relatively high.
My answer uses the Lodash library for simplicity, but you could also implement the algorithm described above without that library.
// assuming _ is the Lodash library
// generates `amount` numbers from 0 to `upperLimit` inclusive
function uniqueRandomInts(upperLimit, amount) {
var possibleNumbers = _.range(upperLimit + 1);
var shuffled = _.shuffle(possibleNumbers);
return shuffled.slice(0, amount);
}
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
Most answers aren't addressing UAC. This covers UAC issues.
First install PowerShell Community Extensions: choco install pscx
via http://chocolatey.org/ (you may have to restart your shell environment).
Then enable pscx
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx
Then use Invoke-Elevated
Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR
The apache zeta components library is a general purpose library of loosly coupled components for development of applications based on PHP 5.
eZ Components - DatabaseSchema allows you to:
.Create/Save a database schema definition; .Compare database schemas; .Generate synchronization queries;
You can check the tutorial here: http://incubator.apache.org/zetacomponents/documentation/trunk/DatabaseSchema/tutorial.html
I recommend you exit the Python interpreter with Ctrl-D. This is the old ASCII code for end-of-file or end-of-transmission.
You could use the href and remove all links that have only hashes:
HTML:
<a href="#" onclick="run_foo()"> foo </a>
JS:
$(document).ready(function(){ // on DOM ready or some other event
$('a[href=#]').attr('href',''); // set all reference handles to blank strings
// for anchors that have only hashes
});
use a proxy property in your code it should work just fine
const https = require('https');
const request = require('request');
request({
'url':'https://teamtreehouse.com/chalkers.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body;
console.log(data);
}
}
);
We store our URLs in a database and load them at runtime.
public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
public TChannel Create(string url)
{
this.Endpoint.Address = new EndpointAddress(new Uri(url));
return this.Channel;
}
}
Implementation
var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);
Just to continue to all the answers that were given here, especially @James Lanes
the size of the integer type can be expressed by this formula:
total range = (2 ^ bit system)
lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1
It is undefined behaviour to attempt to modify string literals, which is what something like:
strcat ("Hello, ", name);
will attempt to do. It will try to tack on the name
string to the end of the string literal "Hello, "
, which is not well defined.
Try something this. It achieves what you appear to be trying to do:
char message[1000];
strcpy (message, "TEXT ");
strcat (message, var);
This creates a buffer area that is allowed to be modified and then copies both the string literal and other text to it. Just be careful with buffer overflows. If you control the input data (or check it before-hand), it's fine to use fixed length buffers like I have.
Otherwise, you should use mitigation strategies such as allocating enough memory from the heap to ensure you can handle it. In other words, something like:
const static char TEXT[] = "TEXT ";
// Make *sure* you have enough space.
char *message = malloc (sizeof(TEXT) + strlen(var) + 1);
if (message == NULL)
handleOutOfMemoryIntelligently();
strcpy (message, TEXT);
strcat (message, var);
// Need to free message at some point after you're done with it.
Another thing that throws this error, when you use php's json_encode function, is when unicode characters are upper case \U and not lower case \u
Try this
li = soup.find('li', {'class': 'text'})
children = li.findChildren("a" , recursive=False)
for child in children:
print(child)
For benchmarking, like in your example, I use the pear Benchmark package. You set markers for measuring. The class also provides a few presentation helpers, or you can process the data as you see fit.
I actually have it wrapped in another class with a __destruct method. When a script exits, the output is logged via log4php to syslog, so I have a lot of performance data to work from.
Make sure you have a service started and listening on the port.
netstat -ln | grep 8080
and
sudo netstat -tulpn
header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.
client.h
#ifndef CLIENT_H
#define CLIENT_H
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);
#endif /** CLIENT_H */
Then you'd implement the .h in a .c file like so:
client.c
#include "client.h"
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
short ret = -1;
//some implementation here
return ret;
}
I have this article bookmarked on setting this up for Java 5 and below.
Basically run it with:
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044
For Java 5 and above, run it with:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044
PhpUnit is an amazing library, but this specific point is a bit frustrating. This is why we can use the turbotesting-php opensource library which has a very convenient assertion method to help us testing exceptions. It is found here:
And to use it, we would simply do the following:
AssertUtils::throwsException(function(){
// Some code that must throw an exception here
}, '/expected error message/');
If the code we type inside the anonymous function does not throw an exception, an exception will be thrown.
If the code we type inside the anonymous function throws an exception, but its message does not match the expected regexp, an exception will also be thrown.
I was looking for something similar and the official answer is no. However, I was able to find an interesting concept by Daniel at ExcelHero.com.
Basically, you need to create worker vbscripts to execute the various things you want and have it report back to excel. For what I am doing, retrieving HTML data from various website, it works great!
Take a look:
http://www.excelhero.com/blog/2010/05/multi-threaded-vba.html
In your menu folder make a .menu xml file and add this xml
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="@string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
In your fragment class overide this method and
implement SearchView.OnQueryTextListener in your fragment class
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
Now just setup your menu xml file in fragment class
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView)
MenuItemCompat.getActionView(item);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
On the comments:
sscanf(Abcd, "%f %s", &f,&s);
Gives an Error.
This is the right way:
sscanf(Abcd, "%f %s", &f,qPrintable(s));
For those using RestSharp, it might fail when using SimpleAuthenticator (possibly due to not using ISO-8859-1 behind the scene). I managed to get it done by explicitly sending Basic Authentication headers:
string username = "...";
string password = "...";
public IRestResponse GetResponse(string url, Method method = Method.GET)
{
string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"));
var client = new RestClient(url);
var request = new RestRequest(method );
request.AddHeader("Authorization", $"Basic {encoded}");
IRestResponse response = client.Execute(request);
return response;
}
var response = GetResponse(url);
txtResult.Text = response.Content;
An example of the mathematically only calculation, without any Date
functions.
const date = new Date();_x000D_
const ts = +date;_x000D_
_x000D_
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);_x000D_
_x000D_
const monday = new Date(mondayTS);_x000D_
console.log(monday.toISOString(), 'Day:', monday.getDay());
_x000D_
const formatTS = v => new Date(v).toISOString();_x000D_
const adjust = (v, d = 1) => v - v % (d * 1000);_x000D_
_x000D_
const d = new Date('2020-04-22T21:48:17.468Z');_x000D_
const ts = +d; // 1587592097468_x000D_
_x000D_
const test = v => console.log(formatTS(adjust(ts, v)));_x000D_
_x000D_
test(); // 2020-04-22T21:48:17.000Z_x000D_
test(60); // 2020-04-22T21:48:00.000Z_x000D_
test(60 * 60); // 2020-04-22T21:00:00.000Z_x000D_
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z_x000D_
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday_x000D_
_x000D_
// So, what does `(7-4)` mean?_x000D_
// 7 - days number in the week_x000D_
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second._x000D_
// new Date(0) ---> 1970-01-01T00:00:00.000Z_x000D_
// new Date(0).getDay() ---> 4
_x000D_
First of all create a model POJO
import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "class_id")
public int classId;
@Column(name = "user_name")
public String userName;
//getter,setter
}
Controller
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;
@RestController
public class HomeController {
@PersistenceUnit
private EntityManagerFactory emf;
@GetMapping("/")
public List<StdUser> actionIndex() {
EntityManager em = emf.createEntityManager(); // Without parameter
List<StdUser> arr_cust = (List<StdUser>)em
.createQuery("SELECT c FROM StdUser c")
.getResultList();
return arr_cust;
}
@GetMapping("/paramter")
public List actionJoin() {
int id = 3;
String userName = "Suresh Shrestha";
EntityManager em = emf.createEntityManager(); // With parameter
List arr_cust = em
.createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
.setParameter("Id",id)
.setParameter("UserName",userName)
.getResultList();
return arr_cust;
}
}
if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId,true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
This works for me
sed '/^all:/ s/$/ anotherthing/' file
The first part is a pattern to find and the second part is an ordinary sed's substitution using $
for the end of a line.
If you want to change the file during the process, use -i
option
sed -i '/^all:/ s/$/ anotherthing/' file
Or you can redirect it to another file
sed '/^all:/ s/$/ anotherthing/' file > output
Or you could simply do this:
@foreach(var myItem in Model.Members)
{
<span>@Model.Members.IndexOf(myItem)</span>
}
For swift change navigation bar color:
self.navigationController?.navigationBar.barTintColor = UIColor.red
change title font,size, color:
self.title = "title"
self.navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.font : UIFont(name: "Futura", size: 30)!
]
yourImageView.contentMode = .center
You can use the following options to position your image:
scaleToFill
scaleAspectFit
// contents scaled to fit with fixed
aspect. remainder is transparentredraw
// redraw on bounds change (calls -setNeedsDisplay)center
// contents remain same size. positioned adjusted.top
bottom
left
right
topLeft
topRight
bottomLeft
bottomRight
Assume I have below array:
Skins[
{Id: 1, Name: "oily skin"},
{Id: 2, Name: "dry skin"}
];
If we want to get item with Id = 1
and Name = "oily skin"
, We'll try as below:
var skinName = skins.find(x=>x.Id == "1").Name;
The result will return the skinName is "Oily skin".
there's also ndisasm, which has some quirks, but can be more useful if you use nasm. I agree with Michael Mrozek that objdump is probably best.
[later] you might also want to check out Albert van der Horst's ciasdis: http://home.hccnet.nl/a.w.m.van.der.horst/forthassembler.html. it can be hard to understand, but has some interesting features you won't likely find anywhere else.
Here is one more variant of how to replace all(HTML Tags | HTML Entities | Empty Space in HTML content)
content.replaceAll("(<.*?>)|(&.*?;)|([ ]{2,})", "");
where content is a String.
Don`t forget to use DataGrid.Columns, all columns must be inside that collection. In my project I format date a little bit differently:
<tk:DataGrid>
<tk:DataGrid.Columns>
<tk:DataGridTextColumn Binding="{Binding StartDate, StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" />
</tk:DataGrid.Columns>
</tk:DataGrid>
With AutoGenerateColumns you won`t be able to contol formatting as DataGird will add its own columns.
Depends on how did you configure your PATH environmental variable. When your shell resolves the call to pip, which is the first bin it will find?
(test)$ whereis pip
pip: /home/borja/anaconda3/envs/test/bin/pip /home/borja/anaconda3/bin/pip
Make sure the bin folder from your anaconda installation is before /usr/lib (depending on how you did install pip). So an example:
(test) borja@xxxx:~$ pip install djangorestframework
....
Successfully installed asgiref-3.2.3 django-3.0.3 djangorestframework-3.11.0 pytz-2019.3 sqlparse-0.3.1
(test) borja@xxxx:~$ conda list | grep django
django 3.0.3 pypi_0 pypi
djangorestframework 3.11.0 pypi_0 pypi
We can see the djangorestframework was installed in my test environment but if I check my base:
(base) borja@xxxx:~$ conda list | grep django
It is empty.
Personally I like to handle all my PATH configuration using .pam_environment, here an example:
(base) borja@xxxx:~$ cat .pam_environment
PATH DEFAULT=/home/@{PAM_USER}/anaconda3/bin:${PATH}
One extra commet. The way how you install pip might create issues:
You should use: conda install pip --> new packages installed with pip will be added to conda list.
You shodul NOT use: sudo apt install python3-pip --> new packages will not be added to conda list (so are not managed by conda) but you will still be able to use them (chance of conflict).
You could just use a for loop and there is no need to add an extra if
inside the for
body:
for (int i = 0; i < Model.Results.Count - 1; i++) {
var item = Model.Results[i];
}
The -1
in the for
condition takes care of skipping the last item.
Use .gitattributes instead, with the following setting:
# Ignore all differences in line endings
* -crlf
.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
The git blame
command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame
", especially in a linear history (which is the norm we should optimize for).
See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre
).
(Merged by Junio C Hamano -- gitster
-- in commit 4d8c4da, 25 Apr 2019)
blame.c
: don't drop origin blobs as eagerlyWhen a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.
Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.
The FontView library lets you use normal/unicode font characters as icons/graphics in your app. It can load the font via assets or a network location.
The benefit of this library is that:
1 - it takes care of remote resources for you
2 - scales the font size in dynamically sized views
3 - allows the font to easily be styled.
https://github.com/shellum/fontView
Example:
Layout:
<com.finalhack.fontview.FontView
android:id="@+id/someActionIcon"
android:layout_width="80dp"
android:layout_height="80dp" />
Java:
fontView.setupFont("fonts/font.ttf", character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);
Use <br />
OR <br>
-
<li>Post by<br /><a>Author</a></li>
OR
<li>Post by<br><a>Author</a></li>
or
make the a
element display:block;
<li>Post by <a style="display:block;">Author</a></li>
You may need user name and password:
mysqlcheck -A --auto-repair -uroot -p
You will be prompted for password.
mysqlcheck -A --auto-repair -uroot -p{{password here}}
If you want to put in cron, BUT your password will be visible in plain text!
I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with
module.exports = NAME_OF_CONSTRUCTOR
will also cause the "Not a constructor" exception.
You'll have more flexibility if you turn the values in your filter object into arrays:
var filter = {address: ['England'], name: ['Mark'] };
That way you can filter for things like "England" or "Scotland", meaning that results may include records for England, and for Scotland:
var filter = {address: ['England', 'Scotland'], name: ['Mark'] };
With that setup, your filtering function can be:
const applyFilter = (data, filter) => data.filter(obj =>
Object.entries(filter).every(([prop, find]) => find.includes(obj[prop]))
);
// demo
var users = [{name: 'John',email: '[email protected]',age: 25,address: 'USA'},{name: 'Tom',email: '[email protected]',age: 35,address: 'England'},{name: 'Mark',email: '[email protected]',age: 28,address: 'England'}];var filter = {address: ['England'], name: ['Mark'] };
var filter = {address: ['England'], name: ['Mark'] };
console.log(applyFilter(users, filter));
_x000D_
Try this
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
//your code here that talks with the UI level widgets/ try to access the UI
//elements from this block because this piece of snippet will run in the UI/MainThread.
}
});