I think this is what you want:
REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'
echo "$1" | grep -P -q $REGEX_DATE
echo $?
I've used the -P switch to get perl regex.
If the targeted thread has been waiting (by calling wait()
, or some other related methods that essentially do the same thing, such as sleep()
), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.
It is completely up to the thread itself (the code that called wait()
) to decide what to do in this situation. It does not automatically terminate the thread.
It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.
Notice that you're using Observable#map to convert the raw Response
object your base Observable emits to a parsed representation of the JSON response.
If I understood you correctly, you want to map
again. But this time, converting that raw JSON to instances of your Model
. So you would do something like:
http.get('api/people.json')
.map(res => res.json())
.map(peopleData => peopleData.map(personData => new Person(personData)))
So, you started with an Observable that emits a Response
object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.
Refering to Oliver Gierke's hint:
When the manipulation of the persistance.xml does the trick, then you created a normal java-class instead of a entity-class.
When creating a new entity-class then the entry in the persistance.xml should be set by Netbeans (in my case).
But as mentioned by Oliver Gierke you can add the entry later to the persistance.xml (if you created a normal java-class).
let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
self.showLoginError(error)
create an NSError object and typecast it to Error ,show it anywhere
private func showLoginError(_ error: Error?) {
if let errorObj = error {
UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
}
}
Try this instead:
var myArray = [];
myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });
or will this not work for your situation?
Has to be more complex test if you really want to handle just about anything as function argument.
type(a) != type('') and hasattr(a, "__iter__")
Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('')
.
Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.
I have try twitter geo api, failed.
Google map api, failed, so far, no way you can get city limit by any api.
twitter api geo endpoint will NOT give you city boundary,
what they provide you is ONLY bounding box with 5 point(lat, long)
First, one of Perlis's epigrams:
"If you have a procedure with 10 parameters, you probably missed some."
Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.
Making an example up, because there's not enough information in the question to answer directly:
class PersonInfo(object):
def __init__(self, name, age, iq):
self.name = name
self.age = age
self.iq = iq
Then your 10 argument function:
def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
...
becomes:
def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
...
and the caller changes to:
personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)
code to generate a password with password will be given length (default to 8) and have at least one upper case, one lower, one number and one symbol
(2 functions and one const variable called 'allowed')
const allowed = {
uppers: "QWERTYUIOPASDFGHJKLZXCVBNM",
lowers: "qwertyuiopasdfghjklzxcvbnm",
numbers: "1234567890",
symbols: "!@#$%^&*"
}
const getRandomCharFromString = (str) => str.charAt(Math.floor(Math.random() * str.length))
const generatePassword = (length = 8) => { // password will be @Param-length, default to 8, and have at least one upper, one lower, one number and one symbol
let pwd = "";
pwd += getRandomCharFromString(allowed.uppers); //pwd will have at least one upper
pwd += getRandomCharFromString(allowed.lowers); //pwd will have at least one lower
pwd += getRandomCharFromString(allowed.numbers); //pwd will have at least one number
pwd += getRandomCharFromString(allowed.symbols);//pwd will have at least one symbolo
for (let i = pwd.length; i < length; i++)
pwd += getRandomCharFromString(Object.values(allowed).join('')); //fill the rest of the pwd with random characters
return pwd
}
This isn't a very beautiful answer, but it's what I use to create zero-length vectors:
0[-1] # numeric
""[-1] # character
TRUE[-1] # logical
0L[-1] # integer
A literal is a vector of length 1, and [-1]
removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.
As a bonus, if you want a single NA
of the respective type:
0[NA] # numeric
""[NA] # character
TRUE[NA] # logical
0L[NA] # integer
This will find all .c or .cpp files on linux
$ find . -name "*.c" -o -name "*.cpp"
You don't need the escaped parenthesis unless you are doing some additional mods. Here from the man page they are saying if the pattern matches, print it. Perhaps they are trying to control printing. In this case the -print acts as a conditional and becomes an "AND'd" conditional. It will prevent any .c files from being printed.
$ find . -name "*.c" -o -name "*.cpp" -print
But if you do like the original answer you can control the printing. This will find all .c files as well.
$ find . \( -name "*.c" -o -name "*.cpp" \) -print
One last example for all c/c++ source files
$ find . \( -name "*.c" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -print
$('.class')[$(this).length - 1]
or
$( "p" ).last().addClass( "selected" );
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
One could use Where-Object
if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) {
"Service Exists"
}
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
I noticed the exact same issue when logging onto servers running Red Hat from an OSX Lion machine.
Try adding or editing the ~/.profile
file for it to correctly export your locale settings upon initiating a new session.
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
These two lines added to the file should suffice to set the locale [replace en_US
for your desired locale, and check beforehand that it is indeed installed on your system (locale -a
)].
After that, you can start a new session and check using locale
:
$ locale
The following should be the output:
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
This an example from my code how to address a widget(button) in popupwindow
View v=LayoutInflater.from(getContext()).inflate(R.layout.popupwindow, null, false);
final PopupWindow pw = new PopupWindow(v,500,500, true);
final Button button = rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pw.showAtLocation(rootView.findViewById(R.id.constraintLayout), Gravity.CENTER, 0, 0);
}
});
final Button popup_btn=v.findViewById(R.id.popupbutton);
popup_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popup_btn.setBackgroundColor(Color.RED);
}
});
Hope this help you
Get the version of Boost that you require. This is for 1.55 but feel free to change or manually download yourself:
wget -O boost_1_55_0.tar.gz https://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.tar.gz/download
tar xzvf boost_1_55_0.tar.gz
cd boost_1_55_0/
Get the required libraries, main ones are icu
for boost::regex
support:
sudo apt-get update
sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev libbz2-dev libboost-all-dev
Boost's bootstrap setup:
./bootstrap.sh --prefix=/usr/
Then build it with:
./b2
and eventually install it:
sudo ./b2 install
class Program
{
public static EventHandler AsyncHandler;
static void Main(string[] args)
{
AsyncHandler+= async (sender, eventArgs) => { await AsyncMain(); };
AsyncHandler?.Invoke(null, null);
}
private async Task AsyncMain()
{
//Your Async Code
}
}
External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.
Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.
public class GetUsers extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect()
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost htopost = new HttpPost("URL");
htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));
try {
JSONObject param = new JSONObject();
param.put("PageSize",100);
param.put("Userid",userId);
param.put("CurrentPage",1);
htopost.setEntity(new StringEntity(param.toString()));
// Execute the request
HttpResponse response;
response = httpclient.execute(htopost);
// Examine the response status
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
json = new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
return ""+response.getStatusLine().getStatusCode();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected String doInBackground(String... urls) {
return connect();
}
@Override
protected void onPostExecute(String status){
try {
if(status.equals("200"))
{
Global.defaultMoemntLsit.clear();
for (int i = 0; i < json.length(); i++) {
JSONObject ojb = json.getJSONObject(i);
UserMomentModel u = new UserMomentModel();
u.setId(ojb.getString("Name"));
u.setUserId(ojb.getString("ID"));
Global.defaultMoemntLsit.add(u);
}
userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
recycleView.setAdapter(userMomentAdapter);
recycleView.setLayoutManager(mLayoutManager);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
You can try this code
select (Convert(Date, '2018-04-01'))
You should do this
if (!image_array) {
// image_array defined but not assigned automatically coerces to false
} else if (!(0 in image_array)) {
// empty array
// doSomething
}
You can do so starting with Postgres 9.1:
with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows
In the meanwhile, if you're only interested in the id, you can do so with a trigger:
create function t1_ins_into_t2()
returns trigger
as $$
begin
insert into table2 (val) values (new.id);
return new;
end;
$$ language plpgsql;
create trigger t1_ins_into_t2
after insert on table1
for each row
execute procedure t1_ins_into_t2();
In the service project do the following:
Now you need to make a setup project. The best thing to do is use the setup wizard.
Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard
a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer
On the second step select "Create a Setup for a Windows Application."
On the 3rd step, select "Primary output from..."
Click through to Finish.
Next edit your installer to make sure the correct output is included.
You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name
, Title
, Manufacturer
, etc...
Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.
As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.
Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,
int main()
{
int a = func();
}
int func()
{
return 1;
}
However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.
int func();
int main()
{
int a = func();
}
int func()
{
return 1;
}
file_get_contents()
is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.
fopen()
with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.
When the JVM
tries to run your application, it calls your main method statically; something like this:
LinkedList.main();
That means there is no instance of your LinkedList
class. In order to call your toString()
method, you can create a new instance of your LinkedList
class.
So the body of your main
method should be like this:
public static void main(String[] args){
// creating an instance of LinkedList class
LinkedList ll = new LinkedList();
// adding some data to the list
ll.insertFront(1);
ll.insertFront(2);
ll.insertFront(3);
ll.insertBack(4);
System.out.println(ll.toString());
}
this one gives the exact md5 as you get from mysql's md5 function or php's md5 functions etc. This is the one I use (you can change according to your needs)
public static String md5( String input ) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(input.getBytes( "UTF-8" ));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append( String.format( "%02x", array[i]));
}
return sb.toString();
} catch ( NoSuchAlgorithmException | UnsupportedEncodingException e) {
return null;
}
}
From similar question here MySQL Inner Join Query To Get Records Not Present in Other Table I got this to work
SELECT * FROM bigtable
LEFT JOIN smalltable ON bigtable.id = smalltable.id
WHERE smalltable.id IS NULL
smalltable
is where you have missing records, bigtable
is where you have all the records. The query list all the records that not exist in smalltable
but exists on the bigtable
. You could replace id
by any other matching criteria.
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
This answer has been resolved for a while and all the available options are already out there. However in this answer I'll attempt to shed a bit more light on these options to help you understand when to use what.
This post will go through the following topics:
merge
, join
, concat
There are a few options, some simpler than others depending on the use case.
DataFrame.merge
withleft_index
andright_index
(orleft_on
andright_on
using named indexes)DataFrame.join
(joins on index)pd.concat
(joins on index)
PROS | CONS | |
---|---|---|
merge |
• supports inner/left/right/full |
• can only join two frames at a time |
join |
• supports inner/left (default)/right/full |
• only supports index-index joins |
concat |
• specializes in joining multiple DataFrames at a time |
• only supports inner/full (default) joins |
Typically, an inner join on index would look like this:
left.merge(right, left_index=True, right_index=True)
Other types of joins (left, right, outer) follow similar syntax (and can be controlled using how=...
).
Notable Alternatives
DataFrame.join
defaults to a left outer join on the index.
left.join(right, how='inner',)
If you happen to get ValueError: columns overlap but no suffix specified
, you will need to specify lsuffix
and rsuffix=
arguments to resolve this. Since the column names are same, a differentiating suffix is required.
pd.concat
joins on the index and can join two or more DataFrames at once. It does a full outer join by default.
pd.concat([left, right], axis=1, sort=False)
For more information on concat
, see this post.
To perform an inner join using index of left, column of right, you will use DataFrame.merge
a combination of left_index=True
and right_on=...
.
left.merge(right, left_index=True, right_on='key')
Other joins follow a similar structure. Note that only merge
can perform index to column joins. You can join on multiple levels/columns, provided the number of index levels on the left equals the number of columns on the right.
join
and concat
are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index
.
This post is an abridged version of my work in Pandas Merging 101. Please follow this link for more examples and other topics on merging.
Assuming the original date is in cell A1:
=DATE(YEAR(A1), MONTH(A1), DAY(A1)-180)
You should use the class name like this
$(document).ready(function(){
$('input.addCheck').prop('checked',true);
});
Try Using this a live demo
I was working on project a
that I wanted users to install via pip install a
with the following file list:
.
+-- setup.py
+-- MANIFEST.in
+-- a
+-- __init__.py
+-- a.py
+-- b
+-- __init__.py
+-- b.py
setup.py
from setuptools import setup
setup (
name='a',
version='0.0.1',
packages=['a'],
package_data={
'a': ['b/*'],
},
)
MANIFEST.in
recursive-include b *.*
a/init.py
from __future__ import absolute_import
from a.a import cats
import a.b
a/a.py
cats = 0
a/b/init.py
from __future__ import absolute_import
from a.b.b import dogs
a/b/b.py
dogs = 1
I installed the module by running the following from the directory with MANIFEST.in
:
python setup.py install
Then, from a totally different location on my filesystem /moustache/armwrestle
I was able to run:
import a
dir(a)
Which confirmed that a.cats
indeed equalled 0 and a.b.dogs
indeed equalled 1, as intended.
Use the below command to copy data from CSV in a single line without casting and changing your datatype. Please replace "NULL" by your string which creating error in copy data
copy table_name from 'path to csv file' (format csv, null "NULL", DELIMITER ',', HEADER);
HTML snippet:
<select data-selected="public" class="form-control" name="role">
<option value="public">
Pubblica
</option>
<option value="user">
Utenti
</option>
<option value="admin">
Admin
</option>
</select>
Native JavaScript snippet:
document.querySelectorAll('[data-selected]').forEach(e => {
e.value = e.dataset.selected
});
Try this:
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print([s.strip('8') for s in lst]) # remove the 8 from the string borders
print([s.replace('8', '') for s in lst]) # remove all the 8s
On Django 1.9, I tried django-admin runserver
and got the same error, but when I used python manage.py runserver
I got the intended result. This may solve this error for a lot of people!
A blazingly faster approach is to do the multiplication in a vectorized manner instead of looping over the list. Numpy has already provided a very simply and handy way for this that you can use.
>>> import numpy as np
>>>
>>> my_list = np.array([1, 2, 3, 4, 5])
>>>
>>> my_list * 5
array([ 5, 10, 15, 20, 25])
Note that this doesn't work with Python's native lists. If you multiply a number with a list it will repeat the items of the as the size of that number.
In [15]: my_list *= 1000
In [16]: len(my_list)
Out[16]: 5000
If you want a pure Python-based approach using a list comprehension is basically the most Pythonic way to go.
In [6]: my_list = [1, 2, 3, 4, 5]
In [7]: [5 * i for i in my_list]
Out[7]: [5, 10, 15, 20, 25]
Beside list comprehension, as a pure functional approach, you can also use built-in map()
function as following:
In [10]: list(map((5).__mul__, my_list))
Out[10]: [5, 10, 15, 20, 25]
This code passes all the items within the my_list
to 5
's __mul__
method and returns an iterator-like object (in python-3.x). You can then convert the iterator to list using list()
built in function (in Python-2.x you don't need that because map
return a list by default).
In [18]: %timeit [5 * i for i in my_list]
463 ns ± 10.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [19]: %timeit list(map((5).__mul__, my_list))
784 ns ± 10.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [20]: %timeit [5 * i for i in my_list * 100000]
20.8 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [21]: %timeit list(map((5).__mul__, my_list * 100000))
30.6 ms ± 169 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [24]: arr = np.array(my_list * 100000)
In [25]: %timeit arr * 5
899 µs ± 4.98 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.
Make sure your data is in the right encoding and everything will work fine.
In my case I needed the configuration stage to be blocking as a whole, but execute each role in parallel. I've tackled this issue using the following code:
echo webserver loadbalancer database | tr ' ' '\n' \
| xargs -I % -P 3 bash -c 'ansible-playbook $1.yml' -- %
the -P 3 argument in xargs makes sure that all the commands are ran in parallel, each command executes the respective playbook and the command as a whole blocks until all parts are finished.
I had an issue where I was putting in the override = "Allow" values (mentioned here already)......but on a x64 bit system.......my 32 notepad++ was phantom saving them. Switching to Notepad (which is a 64bit application on a x64 bit O/S) allowed me to save the settings.
See :
http://dpotter.net/technical/2009/11/editing-applicationhostconfig-on-64-bit-windows/
The relevant text:
One of the problems I’m running down required that I view and possibly edit applicationHost.config. This file is located at %SystemRoot%\System32\inetsrv\config. Seems simple enough. I was able to find it from the command line easily, but when I went to load it in my favorite editor (Notepad++) I got a file not found error. Turns out that the System32 folder is redirected for 32-bit applications to SysWOW64. There appears to be no way to view the System32 folder using a 32-bit app. Go figure. Fortunately, 64-bit versions of Windows ship with a 64-bit version of Notepad. As much as I dislike it, at least it works.
As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images. I got it to compile ok, but it didn't actually work. I also tried building gohlke's library, and it compiled also but failed to open any images. Someone mentioned PythonMagick above, but it only compiles on Windows. See PythonMagick on the wxPython wiki.
PIL was last updated in 2009, and while it's website says they are working on a Python 3 port, it's been 3 years, and the mailing list has gone cold.
To solve my Python 3 image manipulation problem, I am using subprocess.call()
to execute ImageMagick shell commands. This method works.
Apparently, action
was required prior to HTML5 (and #
was just a stand in), but you no longer have to use it.
See The Action Attribute:
When specified with no attributes, as below, the data is sent to the same page that the form is present on:
<form>
Try this.This one is written in typescript.
export function safeJsonParse(str: string) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
The short version is that you cannot use variable-width patterns in lookbehinds using Python's re
module. There is no way to change this:
>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
re.sub("(?<=fo+)bar(?=baz)", "quux", string)
File "C:\Development\Python25\lib\re.py", line 150, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "C:\Development\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:
>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)
This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.
If you are reading unicode escaped chars from a file, then you will have a tough time doing that because the string will be read literally along with an escape for the back slash:
my_file.txt
Blah blah...
Column delimiter=;
Word delimiter=\u0020 #This is just unicode for whitespace
.. more stuff
Here, when you read line 3 from the file the string/line will have:
"Word delimiter=\u0020 #This is just unicode for whitespace"
and the char[] in the string will show:
{...., '=', '\\', 'u', '0', '0', '2', '0', ' ', '#', 't', 'h', ...}
Commons StringUnescape will not unescape this for you (I tried unescapeXml()). You'll have to do it manually as described here.
So, the sub-string "\u0020" should become 1 single char '\u0020'
But if you are using this "\u0020" to do String.split("... ..... ..", columnDelimiterReadFromFile)
which is really using regex internally, it will work directly because the string read from file was escaped and is perfect to use in the regex pattern!! (Confused?)
unittest comes with the standard library, but I would recomend you nosetests.
"nose extends unittest to make testing easier."
I would also recomend you pylint
"analyzes Python source code looking for bugs and signs of poor quality."
As per Firebase Cloud Messaging documentation-If Activity is in foreground then onMessageReceived will get called. If Activity is in background or closed then notification message is shown in the notification center for app launcher activity. You can call your customized activity on click of notification if your app is in background by calling rest service api for firebase messaging as:
URL-https://fcm.googleapis.com/fcm/send
Method Type- POST
Header- Content-Type:application/json
Authorization:key=your api key
Body/Payload:
{ "notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
},
"data": {
"keyname": "any value " //you can get this data as extras in your activity and this data is optional
},
"to" : "to_id(firebase refreshedToken)"
}
And with this in your app you can add below code in your activity to be called:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
git pull origin master --allow-unrelated-histories
You might want to use this if your histories doesnt match and want to merge it anyway..
refer here
I had to run this first
sudo xcode-select --reset
then
sudo xcode-select -switch /Library/Developer/CommandLineTools
and then it worked.
Use the following code to insert the date into MySQL. Instead of changing our date's format to meet MySql's requirement, we can help data base to recognize our date by setting the STR_TO_DATE(?, '%l:%i %p')
parameters.
For example, 2014-03-12 can be represented as STR_TO_DATE('2014-03-12', '%Y-%m-%d')
preparedStatement = connect.prepareStatement("INSERT INTO test.msft VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)");
You may try to add separator row:
html:
<tr class="separator" />
css:
table tr.separator { height: 10px; }
Your PersonSheets has a property int Id
, Id
isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .
To run or debug tests in Visual Studio 2017, we need to install "NUnit3TestAdapter". We can install it in any version of Visual Studio, but it is working properly in the Visual Studio "community" version.
To install this, you can add it through the NuGet package.
If your class inherits from Thread, you can use methods getName
and setName
to name each thread. Otherwise you could just add a name
field to MyTask
, and initialize it in your constructor.
For those looking for a workaround, you can use an attribute selector, for instance, if your class begins with a number. Change:
.000000-8{background:url(../../images/common/000000-0.8.png);} /* DOESN'T WORK!! */
to this:
[class="000000-8"]{background:url(../../images/common/000000-0.8.png);} /* WORKS :) */
Also, if there are multiple classes, you will need to specify them in selector I think.
Sources:
(Updated for 2017)
When you installed MySQL it generated a password for the root user. You can connect using
/usr/local/mysql/bin/mysql -u root -p
and type in the generated password.
Previously, the root
user in MySQL used to not have a password and could only connect from localhost. So you would connect using
/usr/local/mysql/bin/mysql -u root
As others have correctly pointed out, the first part of the ternary needs to return true
or false
and in your question the return value is a jQuery object.
The problem that you may have in the comparison is that the web color will be converted to RGB so you have to text for that in the ternary condition.
So with the CSS:
#blackbox {
background:pink;
width:10px;
height:10px;
}
The following jQuery will flip the colour:
var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));
@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%
Setting the android:textCursorDrawable
attribute to @null
should result in the use of android:textColor
as the cursor color.
Attribute "textCursorDrawable" is available in API level 12 and higher
1.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);is best solution for Native Android.
2. if you want to do with React android application then please use the below code.
@ReactMethod
public void activate() {
final Activity activity = getCurrentActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
}
}
Your element does not have an ID but just a name. So you could either use getElementsByName()
method to get a list of all elements with this name:
var jobValue = document.getElementsByName('txtJob')[0].value // first element in DOM (index 0) with name="txtJob"
Or you assign an ID to the element:
<input type="text" name="txtJob" id="txtJob" value="software engineer">
I think, this example suggests a small nuance on how the partitioning works and how group by works. My example is from Oracle 12, if my example happens to be a compiling bug.
I tried :
SELECT t.data_key
, SUM ( CASE when t.state = 'A' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_a_rows
, SUM ( CASE when t.state = 'B' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_b_rows
, SUM ( CASE when t.state = 'C' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_c_rows
, COUNT (1) total_rows
from mytable t
group by t.data_key ---- This does not compile as the compiler feels that t.state isn't in the group by and doesn't recognize the aggregation I'm looking for
This however works as expected :
SELECT distinct t.data_key
, SUM ( CASE when t.state = 'A' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_a_rows
, SUM ( CASE when t.state = 'B' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_b_rows
, SUM ( CASE when t.state = 'C' THEN 1 ELSE 0 END)
OVER (PARTITION BY t.data_key) count_c_rows
, COUNT (1) total_rows
from mytable t;
Producing the number of elements in each state based on the external key "data_key". So, if, data_key = 'APPLE' had 3 rows with state 'A', 2 rows with state 'B', a row with state 'C', the corresponding row for 'APPLE' would be 'APPLE', 3, 2, 1, 6.
function NumValidate(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert('Only Number ');
return false;
} return true;
} function NumValidateWithDecimal(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
alert('Only Number With desimal e.g.: 0.0');
return false;
}
else {
return true;
} } function onlyAlphabets(e) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
return true;
else
alert("Only text And White Space And . Allow");
return false;
}
catch (err) {
alert(err.Description);
}} function checkAlphaNumeric(e) {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
return true;
} else {
alert('Only Text And Number');
return false;
}}
Select * is a SQL antipattern. It should not be used in production code for many reasons including:
It takes a tiny bit longer to process. When things are run millions of times, those tiny bits can matter. A slow database where the slowness is caused by this type of sloppy coding throughout is the hardest kind to performance tune.
It means you are probably sending more data than you need which causes both server and network bottlenecks. If you have an inner join, the chances of sending more data than you need are 100%.
It causes maintenance problems especially when you have added new columns that you do not want seen everywhere. Further if you have a new column, you may need to do something to the interface to determine what to do with that column.
It can break views (I know this is true in SQl server, it may or may not be true in mysql).
If someone is silly enough to rebuild the tables with the columns in a differnt order (which you shouldn't do but it happens all teh time), all sorts of code can break. Espcially code for an insert for example where suddenly you are putting the city into the address_3 field becasue without specifying, the database can only go on the order of the columns. This is bad enough when the data types change but worse when the swapped columns have the same datatype becasue you can go for sometime inserting bad data that is a mess to clean up. You need to care about data integrity.
If it is used in an insert, it will break the insert if a new column is added in one table but not the other.
It might break triggers. Trigger problems can be difficult to diagnose.
Add up all this against the time it take to add in the column names (heck you may even have an interface that allows you to drag over the columns names (I know I do in SQL Server, I'd bet there is some way to do this is some tool you use to write mysql queries.) Let's see, "I can cause maintenance problems, I can cause performance problems and I can cause data integrity problems, but hey I saved five minutes of dev time." Really just put in the specific columns you want.
I also suggest you read this book: http://www.amazon.com/SQL-Antipatterns-Programming-Pragmatic-Programmers-ebook/dp/B00A376BB2/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1389896688&sr=1-1&keywords=sql+antipatterns
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
Another way to do it is in your class:
import android.graphics.Color; // add to top of class
Button btn = (Button)findViewById(R.id.btn);
// set button text colour to be blue
btn.setTextColor(Color.parseColor("blue"));
// set button text colour to be red
btn.setTextColor(Color.parseColor("#FF0000"));
// set button text color to be a color from your resources (could be strings.xml)
btn.setTextColor(getResources().getColor(R.color.yourColor));
// set button background colour to be green
btn.setBackgroundColor(Color.GREEN);
jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)
Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in
$("#mydiv").load(location.href + " #mydiv");
Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.
If you added your .gitignore
too late, git will continue to track already commited files regardless. To fix this, you can always remove all cached instances of the unwanted files.
First, to check what files are you actually tracking, you can run:
git ls-tree --name-only --full-tree -r HEAD
Let say that you found unwanted files in a directory like cache/
so, it's safer to target that directory instead of all of your files.
So instead of:
git rm -r --cached .
It's safer to target the unwanted file or directory:
git rm -r --cached cache/
Then proceed to add all changes,
git add .
and commit...
git commit -m ".gitignore is now working"
Reference: https://amyetheredge.com/code/13.html
In NodeJS if you know the ID
, the looping through the array is very slow compared to object[ID]
.
const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;
//create data
for(var i=0;i<1000000;i++){
var getUnique = `${uniqueString()}`;
if(i===888555) seeking = getUnique;
arr.push(getUnique);
obj[getUnique] = true;
}
//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
if(arr[x]===seeking){
console.log('Array result:');
console.timeEnd('arrTimer');
break;
}
}
//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');
And the results:
Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms
Even if the seeking ID is the first one in the array/object:
Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms
You are trying to use the string as a function:
"Your new price is: $"(float(price) * 0.1)
Because there is nothing between the string literal and the (..)
parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Seems you forgot to concatenate (and call str()
):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
The next line needs fixing as well:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Alternatively, use string formatting with str.format()
:
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))
where {:02.2f}
will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
Use @Deprecated
on method. Don't forget about clarifying javadoc field:
/**
* Does some thing in old style.
*
* @deprecated use {@link #new()} instead.
*/
@Deprecated
public void old() {
// ...
}
The accepted answer is great, but if you need to interact programmatically with PostgreSQL version maybe it's better to do:
SELECT current_setting('server_version_num'); -- Returns 90603 (9.6.3)
-- Or using SHOW command:
SHOW server_version_num; -- Returns 90603 too
It will return server version as an integer. This is how server version is tested in PostgreSQL source, e.g.:
/*
* This is a C code from pg_dump source.
* It will do something if PostgreSQL remote version (server) is lower than 9.1.0
*/
if (fout->remoteVersion < 90100)
/*
* Do something...
*/
To get the currently logged in user:
System.getProperty("user.name"); //platform independent
and the hostname of the machine:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
Is it possible to restart a single container
Not through kubectl
, although depending on the setup of your cluster you can "cheat" and docker kill the-sha-goes-here
, which will cause kubelet to restart the "failed" container (assuming, of course, the restart policy for the Pod says that is what it should do)
how do I restart the pod
That depends on how the Pod was created, but based on the Pod name you provided, it appears to be under the oversight of a ReplicaSet, so you can just kubectl delete pod test-1495806908-xn5jn
and kubernetes will create a new one in its place (the new Pod will have a different name, so do not expect kubectl get pods
to return test-1495806908-xn5jn
ever again)
Try this:
onclick="javascript:location.href='http://www.uol.com.br/'"
Worked fine for me in Firefox, Chrome and IE (wow!!)
Xcode 12 and iOS 14 update. I have try the previous options to opt-out dark mode and this sentence in the info.plist file is not working for me:
<key>UIUserInterfaceStyle</key>
<string>Light</string>
Now it is renamed to:
<key>Appearance</key>
<string>Light</string>
This setting will block all dark mode in the full app.
EDITED:
Fixed typo thank you to @sarah
While working on Visual Studio 2008, right click on Project -> Add New Item
and then chose Application Manifest File
.
In the manifest file, you will find the tag requestedExecutionLevel
, and you may set the level to three values:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
OR
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
OR
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
To set your application to run as administrator, you have to chose the middle one.
i think the main things to remember about parsing csv is that it follows some simple rules:
a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns
have a read of this post to see what i am talking about
it's actually very easy to do once you have the hang of it and becomes very useful.
It seems that resource filtering/searching can be implemented in a RESTful way. The idea is to introduce a new endpoint called /filters/
or /api/filters/
.
Using this endpoint filter can be considered as a resource and hence created via POST
method. This way - of course - body can be used to carry all the parameters as well as complex search/filter structures can be created.
After creating such filter there are two possibilities to get the search/filter result.
A new resource with unique ID will be returned along with 201 Created
status code. Then using this ID a GET
request can be made to /api/users/
like:
GET /api/users/?filterId=1234-abcd
After new filter is created via POST
it won't reply with 201 Created
but at once with 303 SeeOther
along with Location
header pointing to /api/users/?filterId=1234-abcd
. This redirect will be automatically handled via underlying library.
In both scenarios two requests need to be made to get the filtered results - this may be considered as a drawback, especially for mobile applications. For mobile applications I'd use single POST
call to /api/users/filter/
.
How to keep created filters?
They can be stored in DB and used later on. They can also be stored in some temporary storage e.g. redis and have some TTL after which they will expire and will be removed.
What are the advantages of this idea?
Filters, filtered results are cacheable and can be even bookmarked.
If you think about the performace ,may be you can use "PERFORM" in a function just like this:
PERFORM 1 FROM skytf.test_2 WHERE id=i LIMIT 1;
IF FOUND THEN
RAISE NOTICE ' found record id=%', i;
ELSE
RAISE NOTICE ' not found record id=%', i;
END IF;
You can do this way
@Html.HiddenFor(model=>model.title, new {ng_init = string.Format("model.title='{0}'", Model.title) })
Use the return
keyword.
From MSDN:
The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return the value of the optional expression. If the method is of the type void, the return statement can be omitted.
So in your case, the usage would be:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
return; //exit this event
}
}
Now this may include more than you need (and may not even work for command line applications in a non-graphical environment, I don't know), but there is nw.js. It's Blink (i.e. Chromium/Webkit) + io.js (i.e. Node.js).
You can use node-webkit-builder to build native executable binaries for Linux, OS X and Windows.
If you want a GUI, that's a huge plus. You can build one with web technologies.
If you don't, specify "node-main"
in the package.json
(and probably "window": {"show": false}
although maybe it works to just have a node-main
and not a main
)
I haven't tried to use it in exactly this way, just throwing it out there as a possibility. I can say it's certainly not an ideal solution for non-graphical Node.js applications.
This specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.
A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.
The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.
The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.
This depends a bit from your package system ... if the java
command works, you can type readlink -f $(which java)
to find the location of the java command. On the OpenSUSE system I'm on now it returns /usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/bin/java
(but this is not a system which uses apt-get
).
On Ubuntu, it looks like it is in /usr/lib/jvm/java-6-openjdk/
for OpenJDK, and in some other subdirectory of /usr/lib/jvm/
for Suns JDK (and other implementations as well, I think).
For any given package you can determine what files it installs and where it installs them by querying dpkg. For example for the package 'openjdk-6-jdk': dpkg -L openjdk-6-jdk
In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:
Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"
In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… />
as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head>
section
<link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
In your server.js file, you need to use the app.use()
middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use()
middleware there is already a function/method provided by express called express.static()
. Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:
// using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
// app.use("/route", express.static("foldername"));
app.use('/public', express.static('public'));
After following these simple 3 steps, every time you res.render('ejsfile')
in your app.get()
methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.
It's very important that the input field does not have display: none
. The browser will not select the text and therefore will not be copied. Use opacity: 0
with a width of 0px to fix the problem.
Not numpy but scipy provides exactly the shift functionality you want,
import numpy as np
from scipy.ndimage.interpolation import shift
xs = np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
shift(xs, 3, cval=np.NaN)
where default is to bring in a constant value from outside the array with value cval
, set here to nan
. This gives the desired output,
array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])
and the negative shift works similarly,
shift(xs, -3, cval=np.NaN)
Provides output
array([ 3., 4., 5., 6., 7., 8., 9., nan, nan, nan])
Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:
"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage
which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh
"thought" that it is run in the regular terminal and since it may be accomplished by simple posix
functions, it is beyond what simple bash
offers.
Rather than going the harder route of downloading specific packages. I prefer to go the faster route of using Conda. pip has its issues.
Conda , install conda from : https://conda.io/docs/install/quick.html#windows-miniconda-install
C:\Users\xyz>conda install -c anaconda scipy=0.18.1
Fetching package metadata .............
Solving package specifications:
Package plan for installation in environment C:\Users\xyz\Miniconda3:
The following NEW packages will be INSTALLED:
mkl: 2017.0.1-0 anaconda
numpy: 1.12.0-py36_0 anaconda
scipy: 0.18.1-np112py36_1 anaconda
The following packages will be SUPERCEDED by a higher-priority channel:
conda: 4.3.11-py36_0 --> 4.3.11-py36_0 anaconda
conda-env: 2.6.0-0 --> 2.6.0-0 anaconda
Proceed ([y]/n)? y
conda-env-2.6. 100% |###############################| Time: 0:00:00 32.92 kB/s
mkl-2017.0.1-0 100% |###############################| Time: 0:00:24 5.45 MB/s
numpy-1.12.0-p 100% |###############################| Time: 0:00:00 5.09 MB/s
scipy-0.18.1-n 100% |###############################| Time: 0:00:02 5.59 MB/s
conda-4.3.11-p 100% |###############################| Time: 0:00:00 4.70 MB/s
Instead of using -c, just pipe it to wc -l.
grep string * | wc -l
This will list each occurrence on a single line and then count the number of lines.
This will miss instances where the string occurs 2+ times on one line, though.
I think best way is to use string stream. simple and quick !!!
#include <fstream>
#include <iostream>
#include <sstream> //std::stringstream
int main() {
std::ifstream inFile;
inFile.open("inFileName"); //open the input file
std::stringstream strStream;
strStream << inFile.rdbuf(); //read the file
std::string str = strStream.str(); //str holds the content of the file
std::cout << str << "\n"; //you can do anything with the string!!!
}
Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.
We have two ways to change default port number in Angular.
First way is by CLI command:
ng serve --port 2400 --open
Second way is by configuration at the location:
ProjectName\node_modules\@angular-devkit\build-angular\src\dev-server\schema.json.
Make changes in schema.json file.
{
"title": "Dev Server Target",
"description": "Dev Server target options for Build Facade.",
"type": "object",
"properties": {
"browserTarget": {
"type": "string",
"description": "Target to serve."
},
"port": {
"type": "number",
"description": "Port to listen on.",
"default": 2400
},
You might want to look into my fork of pbzx
here: https://github.com/NiklasRosenstein/pbzx
It allows you to stream pbzx files that are not wrapped in a XAR archive. I've experienced this with recent XCode Command-Line Tools Disk Images (eg. 10.12 XCode 8).
pbzx -n Payload | cpio -i
Using Lambda expressions:
If we don't have a specific class to bind the result:
var stores = context.Stores.Select(x => new { x.id, x.name, x.city }).ToList();
If we have a specific class then we need to bind the result with it:
List<SelectListItem> stores = context.Stores.Select(x => new SelectListItem { Id = x.id, Name = x.name, City = x.city }).ToList();
Using simple LINQ expressions:
If we don't have a specific class to bind the result:
var stores = (from a in context.Stores select new { x.id, x.name, x.city }).ToList();
If we have a specific class then we need to bind the result with it:
List<SelectListItem> stores = (from a in context.Stores select new SelectListItem{ Id = x.id, Name = x.name, City = x.city }).ToList();
You can do via Page directive.
For example:
<%@ page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.
You can use autoPrint() and set output to 'dataurlnewwindow' like this:
function printPDF() {
var printDoc = new jsPDF();
printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180});
printDoc.autoPrint();
printDoc.output("dataurlnewwindow"); // this opens a new popup, after this the PDF opens the print window view but there are browser inconsistencies with how this is handled
}
WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the ButtonAutomationPeer
to accomplish this task.
ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();
Here is a blog post on the subject.
Note: IInvokeProvider
interface is defined in the UIAutomationProvider
assembly.
SQL Server does not have literal true or false values. You'll need to use the 1=1
method (or similar) in the rare cases this is needed.
One option is to create your own named variables for true and false
DECLARE @TRUE bit
DECLARE @FALSE bit
SET @TRUE = 1
SET @FALSE = 0
select * from SomeTable where @TRUE = @TRUE
But these will only exist within the scope of the batch (you'll have to redeclare them in every batch in which you want to use them)
result_array()
returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result()
is recursive in that it returns an std class object where as result_array()
just returns a pure array, so result_array()
would be choice regarding performance.
Try below code snippet
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
/* This is one ajax call */
}
It escapes a string that cannot be passed to XML as usual:
Example:
The string contains "&" in it.
You can not:
<FL val="Company Name">Dolce & Gabbana</FL>
Therefore, you must use CDATA:
<FL val="Company Name"> <![CDATA["Dolce & Gabbana"]]> </FL>
In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.
<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
$cur_hd = "$name: $value\n";
fwrite($fp, $cur_hd);
echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>
>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]
Although it wouldn't be a "true object", you could always do something like this:
var foo = [
{Key1: "key1"},
{Key2: "key2"},
{Key3: "key3"}
];
alert(foo.length); // === 3
I think Internal and External Linkage in C++ gives a clear and concise explanation:
A translation unit refers to an implementation (.c/.cpp) file and all header (.h/.hpp) files it includes. If an object or function inside such a translation unit has internal linkage, then that specific symbol is only visible to the linker within that translation unit. If an object or function has external linkage, the linker can also see it when processing other translation units. The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.
The compiler defaults the linkage of symbols such that:
Non-const global variables have external linkage by default
Const global variables have internal linkage by default
Functions have external linkage by default
Calling libc stdio printf
, implementing int main(){ return printf(message); }
; ----------------------------------------------------------------------------
; helloworld.asm
;
; This is a Win32 console program that writes "Hello, World" on one line and
; then exits. It needs to be linked with a C library.
; ----------------------------------------------------------------------------
global _main
extern _printf
section .text
_main:
push message
call _printf
add esp, 4
ret
message:
db 'Hello, World', 10, 0
Then run
nasm -fwin32 helloworld.asm
gcc helloworld.obj
a
There's also The Clueless Newbies Guide to Hello World in Nasm without the use of a C library. Then the code would look like this.
16-bit code with MS-DOS system calls: works in DOS emulators or in 32-bit Windows with NTVDM support. Can't be run "directly" (transparently) under any 64-bit Windows, because an x86-64 kernel can't use vm86 mode.
org 100h
mov dx,msg
mov ah,9
int 21h
mov ah,4Ch
int 21h
msg db 'Hello, World!',0Dh,0Ah,'$'
Build this into a .com
executable so it will be loaded at cs:100h
with all segment registers equal to each other (tiny memory model).
Good luck.
This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module.
def sliceindex(x):
i = 0
for c in x:
if c.isalpha():
i = i + 1
return i
i = i + 1
def upperfirst(x):
i = sliceindex(x)
return x[:i].upper() + x[i:]
x = '0thisIsCamelCase'
y = upperfirst(x)
print(y)
# 0ThisIsCamelCase
As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence - however I'm omitting edge cases to illustrate the technique)
Updated per @normanius comment (thanks!)
Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -fixed that
System.Reflection.Assembly.GetExecutingAssembly().Location
How about a very simple method
+call your while loop in a function
- set your value inside (nonsense, but shows the example)
- return your value inside
+capture your value outside
+set outside
+display outside
#!/bin/bash
# set -e
# set -u
# No idea why you need this, not using here
foo=0
bar="hello"
if [[ "$bar" == "hello" ]]
then
foo=1
echo "Setting \$foo to $foo"
fi
echo "Variable \$foo after if statement: $foo"
lines="first line\nsecond line\nthird line"
function my_while_loop
{
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2; return 2;
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2;
echo "Variable \$foo updated to $foo inside if inside while loop"
return 2;
fi
# Code below won't be executed since we returned from function in 'if' statement
# We aready reported the $foo var beint set to 2 anyway
echo "Value of \$foo in while loop body: $foo"
done
}
my_while_loop; foo="$?"
echo "Variable \$foo after while loop: $foo"
Output:
Setting $foo 1
Variable $foo after if statement: 1
Value of $foo in while loop body: 1
Variable $foo after while loop: 2
bash --version
GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Copyright (C) 2007 Free Software Foundation, Inc.
If your merge was not too complicated another option would be to:
After that you are left with only the changes from the stash you dropped too early.
It's not a bug in ARel, it's a bug in your logic.
What you want here is:
Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))
For repeating an action in the future, there is the built in setInterval
function that you can use instead of setTimeout
.
It has a similar signature, so the transition from one to another is simple:
setInterval(function() {
// do stuff
}, duration);
I hope the above answer works for elastic search <7.0 but in 7.0 we cannot specify doc type and it is no longer supported. And in that case if we specify doc type we get similar error.
I you are making use of Elastic search 7.0 and Nest C# lastest version(6.6). There are some breaking changes with ES 7.0 which is causing this issue. This is because we cannot specify doc type and in the version 6.6 of NEST they are using doctype. So in order to solve that untill NEST 7.0 is released, we need to download their beta package
Please go through this link for fixing it
https://xyzcoder.github.io/elasticsearch/nest/2019/04/12/es-70-and-nest-mapping-error.html
EDIT: NEST 7.0 is now released. NEST 7.0 works with Elastic 7.0. See the release notes here for details.
This works for me (Python 2)
s = "ABCD"
b = bytearray(s)
# if you print whole b, it still displays it as if its original string
print b
# but print first item from the array to see byte value
print b[0]
Reference: http://www.dotnetperls.com/bytes-python
The problem is probably somewhere else. Try this code for example:
Sub test()
origNum = "006260006"
creditOrDebit = "D"
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
MsgBox "OK"
End If
End Sub
And you will see that your Or
works as expected. Are you sure that your ElseIf
statement is executed (it will not be executed if any of the if/elseif before is true)?
You can create new User library,
On
"Configure Build Paths" page -> Add Library -> User Library (on list) -> User Libraries Button (rigth side of page)
and create your library and (add Jars buttons) include your specific Jars.
I hope this can help you.
In swift 2.2
func filterContentForSearchText(searchText: String, scope: String) {
var resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
searchResults = (recipes as NSArray).filteredArrayUsingPredicate(resultPredicate)
}
In swift 3.0
func filterContent(forSearchText searchText: String, scope: String) {
var resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
searchResults = recipes.filtered(using: resultPredicate)
}
I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.
first define a generic callback:
public interface ITypedCallback<T> {
void execute(T type);
}
create a new ITypedCallback instance on ServerConnections instantiation:
public Server(int _address) {
serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
@Override
public void execute(Socket socket) {
// do something with your socket here
}
});
}
call the execute methode on the callback object.
public class ServerConnections implements Runnable {
private ITypedCallback<Socket> callback;
public ServerConnections(ITypedCallback<Socket> _callback) {
callback = _callback;
}
@Override
public void run() {
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
callback.execute(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
btw: I didn't check if it's 100% correct, directly coded it here.
@CommonsWare's answer doesn't not actually work. I found that this is working properly :
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));
Jeez! Thanks to umair.ashfr answer here below, I finally hit the nail with an issue that was eating my neurons.
I had a password like DB_PASSWORD=ffjdh5#fgr on my .env, and MySQL connection was gracefully saying that "SQLSTATE[HY000] [1045] Access denied for user...", no matter what flavor of php artisan I was trying to run.
The problem was that "#" sign inside the password. BEWARE! That means the start of a comment, thus my password was silently truncated! The solution is to declare password like DB_PASSWORD="ffjdh5#fgr"
Regards
Minimal example varying azim
, dist
and elev
To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245
Here is my test program:
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
if len(sys.argv) > 1:
azim = int(sys.argv[1])
else:
azim = None
if len(sys.argv) > 2:
dist = int(sys.argv[2])
else:
dist = None
if len(sys.argv) > 3:
elev = int(sys.argv[3])
else:
elev = None
# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)
# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
if azim is not None:
ax.azim = azim
if dist is not None:
ax.dist = dist
if elev is not None:
ax.elev = elev
print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))
plt.savefig(
'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
format='png',
bbox_inches='tight'
)
Running it without arguments gives the default values:
ax.azim = -60
ax.dist = 10
ax.elev = 30
main_-60_10_30.png
Vary azim
The azimuth is the rotation around the z axis e.g.:
main_-60_10_30.png
main_0_10_30.png
main_60_10_30.png
Vary dist
dist
seems to be the distance from the center visible point in data coordinates.
main_-60_10_30.png
main_-60_5_30.png
main_-60_20_-30.png
Vary elev
From this we understand that elev
is the angle between the eye and the xy plane.
main_-60_10_60.png
main_-60_10_30.png
main_-60_10_0.png
main_-60_10_-30.png
Tested on matpotlib==3.2.2.
I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:
test:
( NODE_ENV=test mocha --harmony --reporter spec test )
The following code implements a default context menu known from Windows
with copy, cut, paste, select all, undo and redo functions. It also works on Linux
and Mac OS X
:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DefaultContextMenu extends JPopupMenu
{
private Clipboard clipboard;
private UndoManager undoManager;
private JMenuItem undo;
private JMenuItem redo;
private JMenuItem cut;
private JMenuItem copy;
private JMenuItem paste;
private JMenuItem delete;
private JMenuItem selectAll;
private JTextComponent textComponent;
public DefaultContextMenu()
{
undoManager = new UndoManager();
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
addPopupMenuItems();
}
private void addPopupMenuItems()
{
undo = new JMenuItem("Undo");
undo.setEnabled(false);
undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
undo.addActionListener(event -> undoManager.undo());
add(undo);
redo = new JMenuItem("Redo");
redo.setEnabled(false);
redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
redo.addActionListener(event -> undoManager.redo());
add(redo);
add(new JSeparator());
cut = new JMenuItem("Cut");
cut.setEnabled(false);
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
cut.addActionListener(event -> textComponent.cut());
add(cut);
copy = new JMenuItem("Copy");
copy.setEnabled(false);
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
copy.addActionListener(event -> textComponent.copy());
add(copy);
paste = new JMenuItem("Paste");
paste.setEnabled(false);
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
paste.addActionListener(event -> textComponent.paste());
add(paste);
delete = new JMenuItem("Delete");
delete.setEnabled(false);
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
delete.addActionListener(event -> textComponent.replaceSelection(""));
add(delete);
add(new JSeparator());
selectAll = new JMenuItem("Select All");
selectAll.setEnabled(false);
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
selectAll.addActionListener(event -> textComponent.selectAll());
add(selectAll);
}
private void addTo(JTextComponent textComponent)
{
textComponent.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent pressedEvent)
{
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canUndo())
{
undoManager.undo();
}
}
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canRedo())
{
undoManager.redo();
}
}
}
});
textComponent.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
@Override
public void mouseReleased(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
});
textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
}
private void handleContextMenu(MouseEvent releasedEvent)
{
if (releasedEvent.getButton() == MouseEvent.BUTTON3)
{
processClick(releasedEvent);
}
}
private void processClick(MouseEvent event)
{
textComponent = (JTextComponent) event.getSource();
textComponent.requestFocus();
boolean enableUndo = undoManager.canUndo();
boolean enableRedo = undoManager.canRedo();
boolean enableCut = false;
boolean enableCopy = false;
boolean enablePaste = false;
boolean enableDelete = false;
boolean enableSelectAll = false;
String selectedText = textComponent.getSelectedText();
String text = textComponent.getText();
if (text != null)
{
if (text.length() > 0)
{
enableSelectAll = true;
}
}
if (selectedText != null)
{
if (selectedText.length() > 0)
{
enableCut = true;
enableCopy = true;
enableDelete = true;
}
}
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
{
enablePaste = true;
}
undo.setEnabled(enableUndo);
redo.setEnabled(enableRedo);
cut.setEnabled(enableCut);
copy.setEnabled(enableCopy);
paste.setEnabled(enablePaste);
delete.setEnabled(enableDelete);
selectAll.setEnabled(enableSelectAll);
// Shows the popup menu
show(textComponent, event.getX(), event.getY());
}
public static void addDefaultContextMenu(JTextComponent component)
{
DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
defaultContextMenu.addTo(component);
}
}
Usage:
JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);
Now the textArea
will have a context menu when it is right-clicked on.
Now that's the thing about software development, there's no consistent knowledge about anything, everybody seems to have it their own way, but that's because it is a relatively young discipline anyway.
Here's my plain simple way,
trunk - The trunk directory contains the most current, approved, and merged body of work. Contrary to what many have confessed, my trunk is only for clean, neat, approved work, and not a development area, but rather a release area.
At some given point in time when the trunk seems all ready to release, then it is tagged and released.
branches - The branches directory contains experiments and ongoing work. Work under a branch stays there until is approved to be merged into the trunk. For me, this is the area where all the work is done.
For example: I can have an iteration-5 branch for a fifth round of development on the product, maybe a prototype-9 branch for a ninth round of experimenting, and so on.
tags - The tags directory contains snapshots of approved branches and trunk releases. Whenever a branch is approved to merge into the trunk, or a release is made of the trunk, a snapshot of the approved branch or trunk release is made under tags.
I suppose with tags I can jump back and forth through time to points interest quite easily.
Yes. It is also true for for
scope. But not functions of course.
In your example: if the condition in the if
statement is false, x
will not be defined though.
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __future__
:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
I am actually very surprised that over 30 answers were given, and yet none gave a full deep solution for this problem. Some had shallow solution, while others had deep but faulty (it'll crash if undefined, function or symbol will be in the json).
Here is the full solution:
function sortObject(unordered, sortArrays = false) {
if (!unordered || typeof unordered !== 'object') {
return unordered;
}
if (Array.isArray(unordered)) {
const newArr = unordered.map((item) => sortObject(item, sortArrays));
if (sortArrays) {
newArr.sort();
}
return newArr;
}
const ordered = {};
Object.keys(unordered)
.sort()
.forEach((key) => {
ordered[key] = sortObject(unordered[key], sortArrays);
});
return ordered;
}
const json = {
b: 5,
a: [2, 1],
d: {
b: undefined,
a: null,
c: false,
d: true,
g: '1',
f: [],
h: {},
i: 1n,
j: () => {},
k: Symbol('a')
},
c: [
{
b: 1,
a: 1
}
]
};
console.log(sortObject(json, true));
Just a simplified version of @T.J. Crowder and @RegarBoy's answers.
Less is more in my opinion.
Check out onmousemove event for more info about the event.
There's a new value of posX
and posY
every time the mouse moves according to the horizontal and vertical coordinates.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example Mouse Tracker</title>
<style>
body {height: 3000px;}
.dot {width: 2px;height: 2px;background-color: black;position: absolute;}
</style>
</head>
<body>
<p>Mouse tracker</p>
<script>
onmousemove = function(e){
//Logging purposes
console.log("mouse location:", e.clientX, e.clientY);
//meat and potatoes of the snippet
var pos = e;
var dot;
dot = document.createElement('div');
dot.className = "dot";
dot.style.left = pos.x + "px";
dot.style.top = pos.y + "px";
document.body.appendChild(dot);
}
</script>
</body>
</html>
Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.
In my opinion, the performance is significantly better than all previous workarounds.
Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
You can do this alike here but with your package. In my case, it was lsb_release
Run: yum whatprovides lsb_release
Response:
redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release
redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release
redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release
redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release`
Run to install: yum install redhat-lsb-core
The package name SHOULD be without number and system type so yum packager can choose what is best for him.
This worked for me.
First of all give the view controller in your storyboard a Storyboard ID inside the identity inspector. Then use the following example code (ensuring the class, storyboard name and story board ID match those that you are using):
let viewController:
UIViewController = UIStoryboard(
name: "Main", bundle: nil
).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
// .instantiatViewControllerWithIdentifier() returns AnyObject!
// this must be downcast to utilize it
self.presentViewController(viewController, animated: false, completion: nil)
For more details see http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.html best wishes
here's my refactored version which accepts multiline/single as an option
public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
{
var prompt = new Form
{
Width = formWidth,
Height = isMultiline ? formHeight : formHeight - 70,
FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
MaximizeBox = isMultiline
};
var textLabel = new Label
{
Left = 10,
Padding = new Padding(0, 3, 0, 0),
Text = text,
Dock = DockStyle.Top
};
var textBox = new TextBox
{
Left = isMultiline ? 50 : 4,
Top = isMultiline ? 50 : textLabel.Height + 4,
Multiline = isMultiline,
Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
Width = prompt.Width - 24,
Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
};
var confirmationButton = new Button
{
Text = @"OK",
Cursor = Cursors.Hand,
DialogResult = DialogResult.OK,
Dock = DockStyle.Bottom,
};
confirmationButton.Click += (sender, e) =>
{
prompt.Close();
};
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmationButton);
prompt.Controls.Add(textLabel);
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
}
You can use StringTemplate library, it offers what you want and much more.
import org.antlr.stringtemplate.*;
final StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());
There are 2 types of multidimensional arrays in C#, called Multidimensional
and Jagged
.
For multidimensional you can by:
string[,] multi = new string[3, 3];
For jagged array you have to write a bit more code:
string[][] jagged = new string[3][];
for (int i = 0; i < jagged.Length; i++)
{
jagged[i] = new string[3];
}
In short jagged array is both faster and has intuitive syntax. For more information see: this Stackoverflow question
Here's a suggestion for Swift 3+ projects from StackOverflow users PassKit and Kheldar:
UserDefaults.standard.register(defaults: ["UserAgent" : "Custom Agent"])
Source: https://stackoverflow.com/a/27330998/128579
With iOS 5 changes, I recommend the following approach, originally from this StackOverflow question: UIWebView iOS5 changing user-agent as pointed out in an answer below. In comments on that page, it appears to work in 4.3 and earlier also.
Change the "UserAgent" default value by running this code once when your app starts:
NSDictionary *dictionary = @{@"UserAgent": @"Your user agent"}; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; [[NSUserDefaults standardUserDefaults] synchronize];
See previous edits on this post if you need methods that work in versions of iOS before 4.3/5.0. Note that because of the extensive edits, the following comments / other answers on this page may not make sense. This is a four year old question, after all. ;-)
Scrolling with animation:
Your DIV:
<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>
jQuery part:
jQuery(document).ready(function(){
var $t = $('.messageScrollArea');
$t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});
Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :
select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';
You can add any condition or ignore based on your requirement.
The output of the query is resulted as :
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| 5 | ssss | localhost:41060 | somedb | Sleep | 3 | | NULL |
| 58169 | root | localhost | somedb | Query | 0 | executing | select * from sometable where tblColumnName = 'someName' |
Do git rebase -i <sha before the branches diverged>
this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more. The reason that your rebase wasn't working was that you weren't going back far enough.
WARNING: You are rewriting history doing this. Doing this with changes that have been pushed to a remote repo will cause issues. I recommend only doing this with commits that are local.
I've created the following example based on Scott Wales' answer. I've tested it in macOS High Sierra 10.13.3 running go
version go1.10 darwin/amd64
.
(1) Code for library.hpp
, the C++ API we aim to call.
#pragma once
class Foo {
public:
Foo(int value);
~Foo();
int value() const;
private:
int m_value;
};
(2) Code for library.cpp
, the C++ implementation.
#include "library.hpp"
#include <iostream>
Foo::Foo(int value) : m_value(value) {
std::cout << "[c++] Foo::Foo(" << m_value << ")" << std::endl;
}
Foo::~Foo() { std::cout << "[c++] Foo::~Foo(" << m_value << ")" << std::endl; }
int Foo::value() const {
std::cout << "[c++] Foo::value() is " << m_value << std::endl;
return m_value;
}
(3) Code for library-bridge.h
the bridge needed to expose a C
API implemented in C++
so that go
can use it.
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void* LIB_NewFoo(int value);
void LIB_DestroyFoo(void* foo);
int LIB_FooValue(void* foo);
#ifdef __cplusplus
} // extern "C"
#endif
(4) Code for library-bridge.cpp
, the implementation of the bridge.
#include <iostream>
#include "library-bridge.h"
#include "library.hpp"
void* LIB_NewFoo(int value) {
std::cout << "[c++ bridge] LIB_NewFoo(" << value << ")" << std::endl;
auto foo = new Foo(value);
std::cout << "[c++ bridge] LIB_NewFoo(" << value << ") will return pointer "
<< foo << std::endl;
return foo;
}
// Utility function local to the bridge's implementation
Foo* AsFoo(void* foo) { return reinterpret_cast<Foo*>(foo); }
void LIB_DestroyFoo(void* foo) {
std::cout << "[c++ bridge] LIB_DestroyFoo(" << foo << ")" << std::endl;
AsFoo(foo)->~Foo();
}
int LIB_FooValue(void* foo) {
std::cout << "[c++ bridge] LIB_FooValue(" << foo << ")" << std::endl;
return AsFoo(foo)->value();
}
(5) Finally, library.go
, the go program calling the C++ API.
package main
// #cgo LDFLAGS: -L. -llibrary
// #include "library-bridge.h"
import "C"
import "unsafe"
import "fmt"
type Foo struct {
ptr unsafe.Pointer
}
func NewFoo(value int) Foo {
var foo Foo
foo.ptr = C.LIB_NewFoo(C.int(value))
return foo
}
func (foo Foo) Free() {
C.LIB_DestroyFoo(foo.ptr)
}
func (foo Foo) value() int {
return int(C.LIB_FooValue(foo.ptr))
}
func main() {
foo := NewFoo(42)
defer foo.Free() // The Go analog to C++'s RAII
fmt.Println("[go]", foo.value())
}
Using the following Makefile
liblibrary.so: library.cpp library-bridge.cpp
clang++ -o liblibrary.so library.cpp library-bridge.cpp \
-std=c++17 -O3 -Wall -Wextra -fPIC -shared
I can run the example program as follows:
$ make
clang++ -o liblibrary.so library.cpp library-bridge.cpp \
-std=c++17 -O3 -Wall -Wextra -fPIC -shared
$ go run library.go
[c++ bridge] LIB_NewFoo(42)
[c++] Foo::Foo(42)
[c++ bridge] LIB_NewFoo(42) will return pointer 0x42002e0
[c++ bridge] LIB_FooValue(0x42002e0)
[c++] Foo::value() is 42
[go] 42
[c++ bridge] LIB_DestroyFoo(0x42002e0)
[c++] Foo::~Foo(42)
Important
The comments above import "C"
in the go
program are NOT OPTIONAL. You must put them exactly as shown so that cgo
knows which header and library to load, in this case:
// #cgo LDFLAGS: -L. -llibrary
// #include "library-bridge.h"
import "C"
After combining the information in this thread with the R-help ?rect, I came up with this nice graph for circadian rhythm data (24h plot). The script for the background rectangles is this:
>rect(xleft, ybottom, xright, ytop, col = NA, border = NULL)
>i <- 24*(0:8)
>rect(8+i, 1, 24+i, 130, col = "lightgrey", border=NA)
>rect(8+i, -10, 24+i, 0.1, col = "black", border=NA)
The idea is to represent days of 24 hours with 8 h light and 16 h dark.
Cheers,
Romário
Use setDate
.datepicker( "setDate" , date )
Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.
Use this code to set height of the image slider to the full screen / upto 100 view port height. This will helpful when using bootstrap carousel theme slider. I face some issue with height the i use following classes to set image width 100% & height 100vh.
<img class="d-block w-100" src="" alt="" >
use this class in image tags & write following css code in style tags or style.css file
.carousel-inner > .carousel-item > img {
height: 100vh;
}
Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"
To change the size of a button called button1
you simple call
button1.config( height = WHATEVER, width = WHATEVER2 )
If you know what size you want at initialization these options can be added to the constructor.
button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100)
Most likely, the difference in compiler options between your test binary and the Google Test library is to blame on such errors. That's why it's recommended to bring in Google Test in the source form and build it along with your tests. It's very easy to do in CMake. You just invoke ADD_SUBDIRECTORY
with the path to the gtest root and then you can use public library targets (gtest
and gtest_main
) defined there. There is more background information in this CMake thread in the googletestframework group.
[edit]
The BUILD_SHARED_LIBS
option is only effective on Windows for now. It specifies the type of libraries that you want CMake to build. If you set it to ON
, CMake will build them as DLLs as opposed to static libs. In that case you have to build your tests with -DGTEST_LINKED_AS_SHARED_LIBRARY=1 and copy the DLL files produced by the CMake to the directory with your test binary (CMake places them in a separate output directory by default). Unless gtest in static lib doesn't work for you, it's easier not to set that option.
begin
dbms_output.put_line('Hi, '||CHR(10)|| 'good'||CHR(10)|| 'morning' ||CHR(10)|| 'friends');
end;
I believe that the blog post JavaScript Beginners – Select a dropdown option by value might help you.
<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a>
function selectItemByValue(elmnt, value){
for(var i=0; i < elmnt.options.length; i++)
{
if(elmnt.options[i].value === value) {
elmnt.selectedIndex = i;
break;
}
}
}
It didn't work for me when I used
http://localhost{port}/
http://localhost:{port}/something-else/here
However, removing the http did the trick for me. I just added localhost:8000
without prefixing it with the http.
Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.
read month day year << DATE_COMMAND
$(date "+%m %d %Y")
DATE_COMMAND
echo $month $day $year
You could also pipe into the read command, but then you'd have to use the variables within a subshell:
day=n/a; month=n/a; year=n/a
date "+%d %m %Y" | { read day month year ; echo $day $month $year; }
echo $day $month $year
results in...
13 08 2013
n/a n/a n/a
Here are some paths for tabs:
https://codepen.io/mochime/pen/VxxzMW
<!-- left tab -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10,10 _x000D_
a10 10 0 0 1 10 -10_x000D_
h 50 _x000D_
v 47_x000D_
h -50_x000D_
a10 10 0 0 1 -10 -10_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>_x000D_
_x000D_
<!-- right tab -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10 0 _x000D_
h 40_x000D_
a10 10 0 0 1 10 10_x000D_
v 27_x000D_
a10 10 0 0 1 -10 10_x000D_
h -40_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>_x000D_
_x000D_
<!-- tab tab :) -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10,40 _x000D_
v -30_x000D_
a10 10 0 0 1 10 -10_x000D_
h 30_x000D_
a10 10 0 0 1 10 10_x000D_
v 30_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
The other answers explained the mechanics. I especially liked hossein-maktoobian's answer.
The paths in the pen do the brunt of the work, the values can be modified to suite whatever desired dimensions.
try this
<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>
Expose this iframe in the master page's codebehind:
public HtmlControl iframe
{
get
{
return this.myIframe;
}
}
Add the MasterType directive for the content page to strongly typed Master Page.
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>
In code behind
protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}
This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.
$( "#date_start" ).datepicker({
minDate: 0,
dateFormat: "mm/dd/yy",
onSelect: function(selected) {
$("#date_end").datepicker("option","minDate", selected); // mindate on the End datepicker cannot be less than start date already selected.
var date = $(this).datepicker('getDate');
var tempStartDate = new Date(date);
var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
$('#date_end').datepicker('setDate', default_end); // Set as default
}
});
$( "#date_end" ).datepicker({
minDate: 0,
dateFormat: "mm/dd/yy",
onSelect: function(selected) {
$("#date_start").datepicker("option","maxDate", selected); // maxdate on the Start datepicker cannot be more than end date selected.
}
});
@maciej-cygan described the process well, however in order to find your java path:
$ which java
it gives you the path of java
binary file which is a linked file in /usr/bin
directory. next:
$ cd /usr/bin/ && ls -la | grep java
find the pointed location which is something as follows (for me):
then cd
to the pointed directory to find the real home directory for Java. next:
$ ls -la | grep java
which is as follows in this case:
so as it's obvious in the screenshot, my Java home directory is /usr/lib/jvm/java-11-openjdk-amd64
. So accordingly I need to add JAVA_HOME to my bash profile (.bashrc
, .bash_profile
, etc. depending on your OS) like below:
JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
Here you go!
The backslash (\
) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n
is a newline character (rather than a backslash followed by the letter n).
In order to output a literal backslash, you need to escape it. That means \\
will output a single backslash (and \\\\
will output two, and so on). The reason "aa ///\"
doesn't work is because the backslash escapes the "
(which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\"
won't work, because the last backslash again escapes the quote.
Just remember, for each backslash you want to output, you need to give Javascript two.
Did you remember setting the height of the html and body tags in your CSS? This is generally how I've gotten DIVs to extend to full height:
<html>
<head>
<style type="text/css">
html,body { height: 100%; margin: 0px; padding: 0px; }
#full { background: #0f0; height: 100% }
</style>
</head>
<body>
<div id="full">
</div>
</body>
</html>
Use for...in
loop:
for (var key in obj) {
console.log(' name=' + key + ' value=' + obj[key]);
// do some more stuff with obj[key]
}
You can use [(ngModel)]
, but you'll need to update your value
to [value]
otherwise the value is evaluating as a string. It would look like this:
<label>This rule is true if:</label>
<label class="form-check-inline">
<input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode">
</label>
<label class="form-check-inline">
<input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode">
</label>
If rule.mode
is true, then that radio is selected. If it's false, then the other.
The difference really comes down to the value
. value="true"
really evaluates to the string 'true', whereas [value]="true"
evaluates to the boolean true.
In Swift you can use the following code:
extension YourViewController: UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
if let url = request.url, navigationType == UIWebView.NavigationType.linkClicked {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
return false
}
return true
}
}
Make sure you check for the URL value and the navigationType.
$_FILES["file"]["name"] - the name of the uploaded file
In order to prevent StaleObjectStateException
, in your hbm
file write below code:
<timestamp name="lstUpdTstamp" column="LST_UPD_TSTAMP" source="db"/>
I had a similar problem, just verify the port where your Mysql server is running, that will solve the problem
For example, my code was:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/bddventas","root","");
i change the string to
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bddventas","root","");
and voila!!, this workd because my server was running on that port
Hope this help
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
You declare the variable as extern
in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.
PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains ,
use as join('-')
parametr character (can be utf) which is not used in strings
array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()
var array1 = [['a', 'b'], ['b', 'c']];_x000D_
var array2 = [['b', 'c'], ['b', 'a']];_x000D_
_x000D_
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();_x000D_
_x000D_
console.log(r);
_x000D_
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
<?php
function mysqli_insert_array($table, $data, $exclude = array()) {
$con= mysqli_connect("localhost", "root","","test");
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysqli_query($con,"INSERT INTO `$table` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => false,
"mysql_insert_id" => mysqli_insert_id($con),
"mysql_affected_rows" => mysqli_affected_rows($con),
"mysql_info" => mysqli_info($con)
);
} else {
return array( "mysql_error" => mysqli_error($con) );
}
}
$a['firstname']="abc";
$a['last name']="xyz";
$a['birthdate']="1993-09-12";
$a['profilepic']="img.jpg";
$a['gender']="male";
$a['email']="[email protected]";
$a['likechoclate']="Dm";
$a['status']="1";
$result=mysqli_insert_array('registration',$a,'abc');
if( $result['mysql_error'] ) {
echo "Query Failed: " . $result['mysql_error'];
} else {
echo "Query Succeeded! <br />";
echo "<pre>";
print_r($result);
echo "</pre>";
}
?>
Try the following statement:
select distinct A.[Tag],
count(A.[Tag]) as TAG_COUNT,
(SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
from [TagTbl] AS A GROUP BY A.[Tag]
The first field will be the tag the second will be the whole count the third will be the positive ones count.
sometimes if the same pid is running after reboot tomcat will not start
my pid file was at apache-tomcat/temp/tomcat.pid
change file apache-tomcat/bin/catalina.sh about line 386
from "ps -p $PID >/dev/null 2>&1"
to "ps -fp $PID |grep catalina >/dev/null 2>&1"
excerpt from catalina.sh file
if [ ! -z "$CATALINA_PID" ]; then
if [ -f "$CATALINA_PID" ]; then
if [ -s "$CATALINA_PID" ]; then
echo "Existing PID file found during start."
if [ -r "$CATALINA_PID" ]; then
PID=`cat "$CATALINA_PID"`
ps -fp $PID |grep catalina >/dev/null 2>&1 #this line
if [ $? -eq 0 ] ; then
echo "Tomcat appears to still be running with PID $PID. Start aborted."
echo "If the following process is not a Tomcat process, remove the PID file and try again:"
ps -f -p $PID
exit 1
else
echo "Removing/clearing stale PID file."
rm -f "$CATALINA_PID" >/dev/null 2>&1
if [ $? != 0 ]; then
if [ -w "$CATALINA_PID" ]; then
cat /dev/null > "$CATALINA_PID"
else
echo "Unable to remove or clear stale PID file. Start aborted."
exit 1
fi
fi
fi
else
echo "Unable to read PID file. Start aborted."
I use Jquery for this
function setSizes() {
var containerHeight = $("#listContainer").height();
$("#myList").height(containerHeight - 18);
}
then I bind the window resize to recalc it whenever the browser window is resized (if container's size changed with window resize)
$(window).resize(function() { setSizes(); });
You can't get a path to file from WhatsApp. They don't expose it now. The only thing you can get is InputStream
:
InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));
Using is
you can show a picture from WhatsApp in your app.
It's all really just basic uses of Factorization and Square Roots.
It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:
sqrroot(n) * sqrroot(n) = n
.
Given that, if any whole number above 1
and below or up to sqrroot(n)
divides evenly into n
, then n
cannot be a prime number.
Pseudo-code example:
i = 2;
is_prime = true;
while loop (i <= sqrroot(n))
{
if (n % i == 0)
{
is_prime = false;
exit while;
}
++i;
}
While a = 'foo' if True else 'bar'
is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:
a = (b == True and "123" or "456" )
... which in python should be shortened to:
a = b is True and "123" or "456"
... or if you simply want to test the truthfulness of b's value in general...
a = b and "123" or "456"
? :
can literally be swapped out for and or
I was getting the same error, found out it was due to some of the dependencies missing in my pom.xml like that of Spring JPA, Hibernate, Mysql or maybe Jackson. So make sure that dependencies are not missing in your pom.xml and check their version compatibility.
<!-- Jpa and hibernate -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.3.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
To my knowledge these are the rules for calling subroutines and functions in VBScript:
Call
keyword enclose the arguments in parenthesisSince you probably wont be using the Call
keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.
Here are some examples:
WScript.Echo 1, "two", 3.3
- calling a subroutine
WScript.Echo(1, "two", 3.3)
- syntax error
Call WScript.Echo(1, "two", 3.3)
- keyword Call
requires parenthesis
MsgBox "Error"
- calling a function "like" a subroutine
result = MsgBox("Continue?", 4)
- calling a function where the return value is used
WScript.Echo (1 + 2)*3, ("two"), (((3.3)))
- calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)
WScript.Echo(1)
- apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1)
and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines
I'm not sure how to interpret your example, Randomize()
. Randomize
is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.
I'm quite sure that these syntactic rules applies across different versions of operating systems.
You can also use python's requests library instead.
import requests
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = requests.get(url)
dict = response.json()
Now you can manipulate the "dict" like a python dictionary.
In PostMan we have ->Pre-request Script. Paste the Below snippet.
const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());
And now we are ready to use.
{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}
If you are using JPA Entity classes then use the below snippet
@JsonFormat(pattern="MM/dd/yyyy")
@Column(name = "creation_date")
private Date creationDate;
Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;
function get(k) {
return map[k];
}
//map[myKey1] == get(myKey1);
Looks like the answer is that, as of now, you can't.
http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api
I think the intent is to enable static analysis as much as possible, and conditionally imported modules break that. Also worth mentioning -- I'm using Babel, and I'm guessing that System
is not supported by Babel because the module loader API didn't become an ES6 standard.
Is your problem similar to this:
l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"
If so, you simply need to copy the objects when you store them:
import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"
The objects in question should implement a __copy__
method to copy objects. See the documentation for copy
. You may also be interested in copy.deepcopy
, which is there as well.
EDIT: Here's the problem:
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(wM) # appends the wM object to the list
wM.reset() # clears the wM object
You need to append a copy:
import copy
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(copy.copy(wM)) # appends a copy to the list
wM.reset() # clears the wM object
But I'm still confused as to where wM
is coming from. Won't you just be copying the same wM
object over and over, except clearing it after the first time so all the rest will be empty? Or does model()
modify the wM
(which sounds like a terrible design flaw to me)? And why are you throwing away result
?
I'v done things like this using the Checksum(*) function
In essance it creates a row level checksum on all the columns data, you could then compare the checksum of each row for each table to each other, use a left join, to find rows that are different.
Hope that made sense...
Better with an example....
select *
from
( select checksum(*) as chk, userid as k from UserAccounts) as t1
left join
( select checksum(*) as chk, userid as k from UserAccounts) as t2 on t1.k = t2.k
where t1.chk <> t2.chk
From Django docs:
The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.
So Django doesn't grab any blocks from your commondata.html and it doesn't know what to do with rendered html outside blocks.
Four methods using wget, urllib and request.
#!/usr/bin/python
import requests
from StringIO import StringIO
from PIL import Image
import profile as profile
import urllib
import wget
url = 'https://tinypng.com/images/social/website.jpg'
def testRequest():
image_name = 'test1.jpg'
r = requests.get(url, stream=True)
with open(image_name, 'wb') as f:
for chunk in r.iter_content():
f.write(chunk)
def testRequest2():
image_name = 'test2.jpg'
r = requests.get(url)
i = Image.open(StringIO(r.content))
i.save(image_name)
def testUrllib():
image_name = 'test3.jpg'
testfile = urllib.URLopener()
testfile.retrieve(url, image_name)
def testwget():
image_name = 'test4.jpg'
wget.download(url, image_name)
if __name__ == '__main__':
profile.run('testRequest()')
profile.run('testRequest2()')
profile.run('testUrllib()')
profile.run('testwget()')
testRequest - 4469882 function calls (4469842 primitive calls) in 20.236 seconds
testRequest2 - 8580 function calls (8574 primitive calls) in 0.072 seconds
testUrllib - 3810 function calls (3775 primitive calls) in 0.036 seconds
testwget - 3489 function calls in 0.020 seconds
I honestly suggest that you use moment.js. Just download moment.min.js
and then use this snippet to get your date in whatever format you want:
<script>
$(document).ready(function() {
// set an element
$("#date").val( moment().format('MMM D, YYYY') );
// set a variable
var today = moment().format('D MMM, YYYY');
});
</script>
Use following chart for date formats:
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
Probably, it will not matter at all. Read this post on Coding Horror ;): http://www.codinghorror.com/blog/archives/001218.html
You are getting an HTTP 400
(Bad Request) error because there is a space
in your URL. If you fix it (before the zoom
parameter), you will get an HTTP 400
error (Unauthorized).
Maybe you need some HTTP header to identify your download as a recognised browser (use the "User-Agent" header) or additional authentication parameter.
For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");
Use whatever needed for xxxxxx
You can also try this.
$(document).ready(function () {
var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
setInterval(function () {
var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
}, 30000); //Refreshes every 30 seconds
$.ajaxSetup({ cache: false }); //Turn off caching
});
It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.
In the controller section you can update the object and pass the object to the partial view.
public class ControllerName: Controller
{
public ActionResult ActionName()
{
.
. // code for update object
.
return PartialView("PartialViewName", updatedObject);
}
}
Set rs = me.RecordsetClone
rs.Bookmark = me.Bookmark
Do
rs.movenext
Loop until rs.eof
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
You need to store all of the extra rows in the files in your dictionary, not just one of them:
dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}
Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:
w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])