Check the $_SERVER['HTTP_USER_AGENT']
for some of the strings listed here:
http://www.useragentstring.com/pages/useragentstring.php
Or more specifically for crawlers:
http://www.useragentstring.com/pages/useragentstring.php?typ=Crawler
If you want to -say- log the number of visits of most common search engine crawlers, you could use
$interestingCrawlers = array( 'google', 'yahoo' );
$pattern = '/(' . implode('|', $interestingCrawlers) .')/';
$matches = array();
$numMatches = preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']), $matches, 'i');
if($numMatches > 0) // Found a match
{
// $matches[1] contains an array of all text matches to either 'google' or 'yahoo'
}
I had the issue where after updating the SDK it would only update to version 20 and kept telling me that ANDROID 4.1 (API16) was available and only part of ANDROID 4.2 (API17) was available and there was no update to version 21.
After restarting several times and digging I found (was not obvious to me) going to the SDK Manager and going to FILE -> RELOAD solved the problem. Immediately the other uninstalled parts of API17 were there and I was able to update the SDK. Once updated to 4.2 then I could re-update to version 21 and voila.
Good luck! David
It works for trivial cases, and you can extend it with "automatic generation of the prepared statement" however it is always having its limits.
The in() approach can be good enough for some cases, but not rocket proof :)
The rocket-proof solution is to pass the arbitrary number of parameters in a separate call (by passing a clob of params, for example), and then have a view (or any other way) to represent them in SQL and use in your where criteria.
A brute-force variant is here http://tkyte.blogspot.hu/2006/06/varying-in-lists.html
However if you can use PL/SQL, this mess can become pretty neat.
function getCustomers(in_customerIdList clob) return sys_refcursor is
begin
aux_in_list.parse(in_customerIdList);
open res for
select *
from customer c,
in_list v
where c.customer_id=v.token;
return res;
end;
Then you can pass arbitrary number of comma separated customer ids in the parameter, and:
The trick here is:
The view looks like:
create or replace view in_list
as
select
trim( substr (txt,
instr (txt, ',', 1, level ) + 1,
instr (txt, ',', 1, level+1)
- instr (txt, ',', 1, level) -1 ) ) as token
from (select ','||aux_in_list.getpayload||',' txt from dual)
connect by level <= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1
where aux_in_list.getpayload refers to the original input string.
A possible approach would be to pass pl/sql arrays (supported by Oracle only), however you can't use those in pure SQL, therefore a conversion step is always needed. The conversion can not be done in SQL, so after all, passing a clob with all parameters in string and converting it witin a view is the most efficient solution.
If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!
Because when you call $( "#form_id" ).submit();
it triggers the external submit handler which prevents the default action, instead use
$( "#form_id" )[0].submit();
or
$form.submit();//declare `$form as a local variable by using var $form = this;
When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element
For ViewPager2,
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
})
where OnPageChangeCallback
is a static class with three methods:
onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position),
onPageScrollStateChanged(@ScrollState int state)
That depends on what you actually want to achieve.
You want to keep on making normal Java-based Android application, but use Visual Studio for development? Then it's bad news, as Visual Studio has no built-in java support. Thus, if you use it out-of-the-box, you will lose all Java-specific Eclipse functionality (IntelliSense for Java, Java debugger, wizards, etc) as well as numerous Android plugins (that are Eclipse-specific and won't work with VS).
On the other hand, you can use Mono for Android to develop apps in C# in VS, but they won't look as smooth as the native apps (some functionality might be missing, look-and-feel slightly different, etc.). In that case such app could sell less than a "normal" Java app that looks and feels like all other Java apps.
If you are talking about native Android code (in C/C++), such as games, the news are not as bad. As Visual Studio has no problem with C++, there are numerous ways to make it work:
If you only want to compile your code, you can use the free vs-android toolset. It's essentially a set of build rules telling Visual Studio how to launch Android compiler.
If you want to compile and debug your native code with Visual Studio, you will need something more advanced, such as VisualGDB for Android. It can build/debug your Native code independently, or together with debugging Java code from Eclipse.
Try the :lt selector: http://docs.jquery.com/Selectors/lt#index
$('a:lt(20)');
instanceof
is just syntactic sugar for isPrototypeOf
:
function Ctor() {}
var o = new Ctor();
o instanceof Ctor; // true
Ctor.prototype.isPrototypeOf(o); // true
o instanceof Ctor === Ctor.prototype.isPrototypeOf(o); // equivalent
instanceof
just depends on the prototype of a constructor of an object.
A constructor is just a normal function. Strictly speaking it is a function object, since everything is an object in Javascript. And this function object has a prototype, because every function has a prototype.
A prototype is just a normal object, which is located within the prototype chain of another object. That means being in the prototype chain of another object makes an object to a prototype:
function f() {} // ordinary function
var o = {}, // ordinary object
p;
f.prototype = o; // oops, o is a prototype now
p = new f(); // oops, f is a constructor now
o.isPrototypeOf(p); // true
p instanceof f; // true
The instanceof
operator should be avoided because it fakes classes, which do not exist in Javascript. Despite the class
keyword not in ES2015 either, since class
is again just syntactic sugar for...but that's another story.
Like so many others, but with explanation in the css.
/* select all <a> elements with class "button" */
a.button {
/* use inline-block because it respects padding */
display: inline-block;
/* padding creates clickable area around text (top/bottom, left/right) */
padding: 1em 3em;
/* round corners */
border-radius: 5px;
/* remove underline */
text-decoration: none;
/* set colors */
color: white;
background-color: #4E9CAF;
}
_x000D_
<a class="button" href="#">Add a problem</a>
_x000D_
This is how I've added a bot to my channel and set up notifications:
telegram.me/whateverIWantAndAvailable
the channel id will be @whateverIWantAndAvailable
Now set up your bot to send notifications by pusshing the messages here:
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test
the message which bot will notify is: Test
I strongly suggest an urlencode of the message like
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works
in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");
I hope it helps
Ad this line inside the OnCreate event on MainActivity (Xamarin)
Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.
I try to give a general rule by using the OPs example
do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"
we have to avoid a branch where $a
gets more than 10, so $a < 10
as a general condition can be applied to every other, following condition.
In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.
So the OPs example with the rule applied may be restructured as:
if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
echo "1"
elif [ "$a" -lt 10 ]
then
echo "2"
fi
Just a variation of the above, enclosing everything in the $a < 10
condition:
if [ "$a" -lt 10 ]
then
if [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
fi
(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)
The absolute path to the directory where
./manage.py collectstatic
will collect static files for deployment. Example:STATIC_ROOT="/var/www/example.com/static/"
now the command ./manage.py collectstatic
will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/
. now you only need to serve this directory on apache or nginx..etc.
The
URL
of which the static files inSTATIC_ROOT
directory are served(by Apache or nginx..etc). Example:/static/
orhttp://static.example.com/
If you set STATIC_URL = 'http://static.example.com/'
, then you must serve the STATIC_ROOT
folder (ie "/var/www/example.com/static/"
) by apache or nginx at url 'http://static.example.com/'
(so that you can refer the static file '/var/www/example.com/static/jquery.js'
with 'http://static.example.com/jquery.js'
)
Now in your django-templates, you can refer it by:
{% load static %}
<script src="{% static "jquery.js" %}"></script>
which will render:
<script src="http://static.example.com/jquery.js"></script>
No. While you can set a base font size on body
using the font-size
property, anything after that that specifies a smaller size will override the base rule for that element. In order to do what you are looking to do you will need to use Javascript.
You could iterate through the elements on the page and change the smaller fonts using something like this:
$("*").each( function () {
var $this = $(this);
if (parseInt($this.css("fontSize")) < 12) {
$this.css({ "font-size": "12px" });
}
});
Here is a Fiddle where you can see it done: http://jsfiddle.net/mifi79/LfdL8/2/
From the documentation:
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a),x)
is equivalent toa.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
To delete multiple services in Powershell 5.0, since remove service does not exist in this version
Run the below command
Get-Service -Displayname "*ServiceName*" | ForEach-object{ cmd /c sc delete $_.Name}
Even without pop
the list we can do with set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4
For C++ :
I just faced the same issue and I think it is worth mentioning a problem comes up when one use both __stdcall
(or WINAPI
) and extern "C"
:
As you know extern "C"
removes the decoration so that instead of :
__declspec(dllexport) int Test(void) --> dumpbin : ?Test@@YaHXZ
you obtain a symbol name undecorated:
extern "C" __declspec(dllexport) int Test(void) --> dumpbin : Test
However the _stdcall
( = macro WINAPI, that changes the calling convention) also decorates names so that if we use both we obtain :
extern "C" __declspec(dllexport) int WINAPI Test(void) --> dumpbin : _Test@0
and the benefit of extern "C"
is lost because the symbol is decorated (with _ @bytes)
Note that this only occurs for x86 architecture because the
__stdcall
convention is ignored on x64 (msdn : on x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.).
This is particularly tricky if you are targeting both x86 and x64 platforms.
Two solutions
Use a definition file. But this forces you to maintain the state of the def file.
the simplest way : define the macro (see msdn) :
#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
and then include the following pragma in the function body:
#pragma EXPORT
Full Example :
int WINAPI Test(void)
{
#pragma EXPORT
return 1;
}
This will export the function undecorated for both x86 and x64 targets while preserving the __stdcall
convention for x86. The __declspec(dllexport)
is not required in this case.
With SQL Server try:
SELECT TOP 1 *
FROM dbo.youTable
WHERE user_id = 'userid'
ORDER BY date_added desc
You can extend blade like so:
Blade::directive('switch', function ($expression) {
return "<?php switch($expression): ?>";
});
Blade::directive('case', function ($expression) {
return "<?php case $expression: ?>";
});
Blade::directive('break', function () {
return "<?php break; ?>";
});
Blade::directive('default', function () {
return "<?php default: ?>";
});
Blade::directive('endswitch', function () {
return "<?php endswitch; ?>";
});
You can then use the following:
@switch($test)
@case(1)
Words
@break
@case(2)
Other Words
@break
@default
Default words
@endswitch
However do note the warnings in : http://php.net/manual/en/control-structures.alternative-syntax.php
If there is any whitespace between the switch(): and the first case then the whole code block will fail. That is a PHP limitation rather than a blade limitation. You may be able to bypass it by forcing the normal syntax e.g.:
Blade::directive('switch', function ($expression) {
return "<?php switch($expression) { ?>";
});
Blade::directive('endswitch', function ($) {
return "<?php } ?>";
});
But this feels a bit wrong.
Please use this module
RouterModule.forRoot(
[
{ path: "", component: LoginComponent}
]
)
now just replace your <login></login>
with <router-outlet></router-outlet>
thats it
I was searching for the iOS PCH file having the same problem, if you got here like me too, the solution that I've found is by clearing derived data; Close Simulator(s), go to xCode prefs -> locations -> go to the derived data file path, close xCode, delete the files in the derived data folder, re launch and cheers :)
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Just a one more link with nicely maintained collection Html Entities
I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.
That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.
So there are a few pseudo-solutions
First, store all the data in a single table. Then you'll have no issues in EF.
Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.
Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).
UPDATE
To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.
Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.
As already mentioned in other answers, use BufferedInputStreams.
After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.
Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.
(Hmm... with multiple cores, threads might help.)
Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved
For Windows users looking for solution of same problem. I just repleced
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
in my /conf/extra/http?-xampp.conf
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range
use Activesheet.range("range").select
by small modification of Joshep's code...You can use this code which seems like right corner folded down as per your requirement.
div {
height: 300px;
background: red;
position: relative;
}
div:before {
content: '';
position: absolute;
top: 0; right: 0;
border-top: 80px solid white;
border-left: 80px solid blue;
width: 0;
}
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Here are TypeScript equivalents of some common .NET delegates:
interface Action<T>
{
(item: T): void;
}
interface Func<T,TResult>
{
(item: T): TResult;
}
Adding "relaxedQueryChars" attribute to the server.xml worked for me :
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="443" URIEncoding="UTF-8" relaxedQueryChars="[]|{}^\`"<>"/>
You can set the location of your log4j.properties from inside your java app by using:
org.apache.log4j.PropertyConfigurator.configure(file/location/log4j.properties)
More information is available here: https://logging.apache.org/log4j/1.2/manual.html
What you have from the server is a string like below:
var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';
Then you can use JSON.parse
function to change it to an object. Then you access the category like below:
var dataObj = JSON.parse(data);
console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie
If you simply want to watch a state property and then act within the component accordingly to the changes of that property then see the example below.
In store.js
:
export const state = () => ({
isClosed: false
})
export const mutations = {
closeWindow(state, payload) {
state.isClosed = payload
}
}
In this scenario, I am creating a boolean
state property that I am going to change in different places in the application like so:
this.$store.commit('closeWindow', true)
Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mounted
hook:
mounted() {
this.$store.watch(
state => state.isClosed,
(value) => {
if (value) { this.localProperty = 'edit' }
}
)
}
Firstly, I am setting a watcher on the state property and then in the callback function I use the value
of that property to change the localProperty
.
I hope it helps!
I will use CXF also you can think of AXIS 2 .
The best way to do it may be using JAX RS Refer this example
Example:
wsimport -p stockquote http://stockquote.xyz/quote?wsdl
This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.
I
For run all lines of GridView don't use for
loop, use foreach
loop like:
foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//if checked do something
}
}
}
For Excel 2013:
http://blogmines.com/blog/how-to-import-text-file-in-excel-2013/
Use the below link to download IE Driver latest version
In Capybara you can use only find with xpath
find(:xpath, "//*[@id='organizationSelect']/option[2]").click
and method click
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
In simple terms, you just need to edit the .gitmodules file, then resync and update:
Edit the file, either via a git command or directly:
git config --file=.gitmodules -e
or just:
vim .gitmodules
then resync and update:
git submodule sync
git submodule update --init --recursive --remote
There's a better way of storing JSON in the HTML:
HTML
<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>
JavaScript
JSON.parse(document.getElementById('some-data').textContent);
You'll need an additional utility such as cmdow.exe to accomplish this. Look specifically at the /mov
switch. You can either launch your program from cmdow
or run it separately and then invoke cmdow
to move/resize it as desired.
There's an entire book on this topic, which is titled Large-Scale C++ Software Design (written by John Lakos).
The book pre-dates templates, so to the contents of that book add "using templates, too, can make the compiler slower".
I also get this error quite often.
I solve this by modifying the code (doing a very small change), saving it, then building the solution again.
If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance
-based approach mentioned in another answer, and instead use keyword arguments.
If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:
class C(object):
def __init__(self, fd):
# Assume fd is a file-like object.
self.fd = fd
@classmethod
def fromfilename(cls, name):
return cls(open(name, 'rb'))
# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')
Notice all those classmethods still go through the same __init__
, but using classmethods can be much more convenient than having to remember what combinations of keyword arguments to __init__
work.
isinstance
is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file)
, because there are many file-like objects that do not subclass file
(like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.
Make a useful function like this:
IplImage* img_resize(IplImage* src_img, int new_width,int new_height)
{
IplImage* des_img;
des_img=cvCreateImage(cvSize(new_width,new_height),src_img->depth,src_img->nChannels);
cvResize(src_img,des_img,CV_INTER_LINEAR);
return des_img;
}
I am able to download it using apple's download website today. https://developer.apple.com/download/
I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
If you don't care about the order of the array, then you may want to get the difference between arr1
and arr2
by id
using differenceBy() and then simply use concat() to append all the updated objects.
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();
var arr1 = [{_x000D_
id: '124',_x000D_
name: 'qqq'_x000D_
}, {_x000D_
id: '589',_x000D_
name: 'www'_x000D_
}, {_x000D_
id: '45',_x000D_
name: 'eee'_x000D_
}, {_x000D_
id: '567',_x000D_
name: 'rrr'_x000D_
}]_x000D_
_x000D_
var arr2 = [{_x000D_
id: '124',_x000D_
name: 'ttt'_x000D_
}, {_x000D_
id: '45',_x000D_
name: 'yyy'_x000D_
}];_x000D_
_x000D_
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
_x000D_
In iOS10 all I needed to do is override the prefersStatusBarHidden
var in my RootViewController
(Swift):
override var prefersStatusBarHidden: Bool {
return true
}
As indicated in the online manual, the most common cause for that error is that lines are indented with spaces when make
expects tab characters.
target:
\tcmd
where \t
is TAB (U+0009
)
target:
....cmd
where each .
represents a SPACE (U+0020
).
another solution is catching onClick event and for aggregate data to js function you can
.hmtl.erb
<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
.js
// handle my-class click
$('a.my-class').on('click', function () {
var link = $(this);
var array = link.data('array');
});
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
.wrap {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border: 1px solid #aaa;_x000D_
margin: 10px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<span>Align me to the bottom</span>_x000D_
</div>
_x000D_
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
flex
)If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
div {_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
border: 1px solid #f00;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
Here's what u can also try....
run your application....while it is still running launch your command prompt
while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.
Suggestions to fix it:
If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)
Modify the settings so they read:
MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)
This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.
Only use suggestion 2 if 1 fails.
Thank you.
Hey if you want to apply Material theme for only android 5.0 then you can add this theme in it
<style name="AppHomeTheme" parent="@android:style/Theme.Material.Light">
<!-- customize the color palette -->
<item name="android:colorPrimary">@color/blue_dark_bg</item>
<item name="android:colorPrimaryDark">@color/blue_status_bar</item>
<item name="android:colorAccent">@color/blue_color_accent</item>
<item name="android:textColor">@android:color/white</item>
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:actionMenuTextColor">@android:color/black</item>
</style>
Here below line is responsibly for text color of Actionbar of Material design.
<item name="android:textColorPrimary">@android:color/white</item>
If somebody, who is looking for a solution in Swift, landed here, it would be:
myButton.isEnabled = false // disables
myButton.setTitle("myTitle", for: .normal) // sets text
Documentation: isEnabled, setTitle.
Older code:
myButton.enabled = false // disables
myButton.setTitle("myTitle", forState: UIControlState.Normal) // sets text
I had the same issue, didn't want to mess with multiple typedefs in different files, so I resolved it with inheritance:
was:
class BurstBoss {
public:
typedef std::pair<Ogre::ParticleSystem*, bool> ParticleSystem; // removed this with...
did:
class ParticleSystem : public std::pair<Ogre::ParticleSystem*, bool>
{
public:
ParticleSystem(Ogre::ParticleSystem* system, bool enabled) : std::pair<Ogre::ParticleSystem*, bool>(system, enabled) {
};
};
Worked like a charm. Of course, I had to change any references from
BurstBoss::ParticleSystem
to simply
ParticleSystem
I would write the code like this:
def search_book(request):
form = SearchForm(request.POST or None)
if request.method == "POST" and form.is_valid():
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
return HttpResponseRedirect('/thanks/')
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
Pretty much like the documentation.
As it's said, you need an Activity as context for the dialog, use "YourActivity.this" for a static context or check here for how to use a dynamic one in a safe mode
In this example we will create iPhone class and make exact copy from it by cloning
class iPhone {
public $name;
public $email;
public function __construct($n, $e) {
$this->name = $n;
$this->email = $e;
}
}
$main = new iPhone('Dark', '[email protected]');
$copy = clone $main;
// if you want to print both objects, just write this
echo "<pre>"; print_r($main); echo "</pre>";
echo "<pre>"; print_r($copy); echo "</pre>";
For the ones who like shorter and faster(not calling deg2rad()).
function circle_distance($lat1, $lon1, $lat2, $lon2) {
$rad = M_PI / 180;
return acos(sin($lat2*$rad) * sin($lat1*$rad) + cos($lat2*$rad) * cos($lat1*$rad) * cos($lon2*$rad - $lon1*$rad)) * 6371;// Kilometers
}
Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.
If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.
Try to surround strings
(hoot
, story
, article
) with quotes '
:
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
[int(i) for i in str(number)]
or, if do not want to use a list comprehension or you want to use a base different from 10
from __future__ import division # for compatibility of // between Python 2 and 3
def digits(number, base=10):
assert number >= 0
if number == 0:
return [0]
l = []
while number > 0:
l.append(number % base)
number = number // base
return l
You can use TimerTask for Cronjobs.
Main.java
public class Main{
public static void main(String[] args){
Timer t = new Timer();
MyTask mTask = new MyTask();
// This task is scheduled to run every 10 seconds
t.scheduleAtFixedRate(mTask, 0, 10000);
}
}
MyTask.java
class MyTask extends TimerTask{
public MyTask(){
//Some stuffs
}
@Override
public void run() {
System.out.println("Hi see you after 10 seconds");
}
}
Alternative You can also use ScheduledExecutorService.
From the Tools menu, click NuGet Package Manger, then click Package Manager Console (PMC). Enter the following commands in the PMC.
Enable-Migrations Add-Migration Init Update-Database Run the application. The solution to the problem is from here
Shorter version of previous using map()
function (works for python 2.7):
"".join(map(chr, myList))
First
<table border="1">
<tr>
<td style='border:none;'>one</td>
<td style='border:none;'>two</td>
</tr>
<tr>
<td style='border:none;'>one</td>
<td style='border:none;'>two</td>
</tr>
</table>
Second example
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td style='border-left:none;border-top:none'>one</td>
<td style='border:none;'>two</td>
</tr>
<tr>
<td style='border-left:none;border-bottom:none;border-top:none'>one</td>
<td style='border:none;'>two</td>
</tr>
</table>
Each time a save method is called on a model, cake internally calls Model::getLastInsertId() and stores the result into model class attribute id, so after calling save() it is not necessary to call Model::getLastInsertId() or inserId(), as tha value can be directly accessed like this
$id = $this->id;// within a model
$id = $this->{$this->modelName}->id;// in a controller
<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
^^^^^^^^^^^^^^^^^^^^^^^^
In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.
In CreateReportCardForm, these are your only three inputs:
@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];
Add one for currentReportCardCount and you should be good to go.
This is not the OP's problem, but I got the same Object is possibly 'null'
message when I had declared a parameter as the null type by accident:
something: null;
instead of assigning it the value of null:
something: string = null;
i just place one image in " d drive-->Data-->IMG". The image name is x.jpg
:
And on c# code type
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));
(please put double slash in between path)
this.Background = myBrush;
finally i got the background..
Using the mysqli PHP driver, you can't get the insert_id after you commit.
The real solution is this:
function add_post($post_data){
$this->db->trans_begin();
$this->db->insert('posts',$post_data);
$item_id = $this->db->insert_id();
if( $this->db->trans_status() === FALSE )
{
$this->db->trans_rollback();
return( 0 );
}
else
{
$this->db->trans_commit();
return( $item_id );
}
}
Source for code structure: https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually
Does the screenshot contain only the icon? If so, the L2 distance of the two images might suffice. If the L2 distance doesn't work, the next step is to try something simple and well established, like: Lucas-Kanade. Which I'm sure is available in OpenCV.
Getting the anchor point of a div/table (left) = $("#whatever").offset().left;
- ok!
Getting the anchor point of a div/table (right)
you can use the code below.
$("#whatever").width();
If the list is sorted, you can use a binary search. If not, then there is no better way.
If you're doing this a lot, it would almost certainly be worth your while to sort the list the first time. Since you can't modify the classes, you would have to use a Comparator
to do the sorting and searching.
If your local jdk version is 11 or 9, 10, and your project's java source/target version is 1.8, and you are using org.projectlombok:lombok
package, then you can try to update its version to 1.16.22 or 1.18.12, like this:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
It just solved my issue.
Note that list
and array
are different classes. You can do:
del mylist[:]
This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).
Try:
a = [1,2]
b = a
a = []
and
a = [1,2]
b = a
del a[:]
Print a
and b
each time to see the difference.
I would use an asynchronous access using a completion block.
This example saves the Google logo to the document directory of the device. (iOS 5+, OSX 10.7+)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
The most concise solution I have found uses Sympy: https://www.geeksforgeeks.org/python-sympy-line-intersection-method/
# import sympy and Point, Line
from sympy import Point, Line
p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
l1 = Line(p1, p2)
# using intersection() method
showIntersection = l1.intersection(p3)
print(showIntersection)
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.
Try specifying the locale you wish to use, for example Locale.US
:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27, 2007");
Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.
You could use a std::stringstream. You can stream anything into it:
std::stringstream stream;
stream << 5.7;
stream << foo.bar;
std::string s = stream.str();
That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)
The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.
bool alreadyAdded = false;
This variable can be global.
if(!alreadyAdded)
{
myClass.MyEvent += MyHandler;
alreadyAdded = true;
}
you can | for set union and & for set intersection.
for example:
set1={1,2,3}
set2={3,4,5}
print(set1&set2)
output=3
set1={1,2,3}
set2={3,4,5}
print(set1|set2)
output=1,2,3,4,5
curly braces in the answer.
I asked the same question when I started out - hoping for a somewhat prescriptive guide on learning Rails... couldn't find one so decided I would write one for others who might find themselves in a similar boat one day :) You can find it here:
Best Way to Learn Ruby & Rails
(It's now actually returned with the !learn factoid helper in the official Ruby on Rails IRC chat room.)
^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$
1-718-444-1122
718-444-1122
(718)-444-1122
17184441122
7184441122
718.444.1122
1718.444.1122
1-123-456-7890
1 123-456-7890
1 (123) 456-7890
1 123 456 7890
1.123.456.7890
+91 (123) 456-7890
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
18001234567
1 800 123 4567
1-800-123-4567
+18001234567
+1 800 123 4567
+1 (800) 123 4567
1(800)1234567
+1800 1234567
1.8001234567
1.800.123.4567
+1 (800) 123-4567
18001234567
1 800 123 4567
+1 800 123-4567
+86 800 123 4567
1-800-123-4567
1 (800) 123-4567
(800)123-4567
(800) 123-4567
(800)1234567
800-123-4567
800.123.4567
1231231231
123-1231231
123123-1231
123-123 1231
123 123-1231
123-123-1231
(123)123-1231
(123)123 1231
(123) 123-1231
(123) 123 1231
+99 1234567890
+991234567890
(555) 444-6789
555-444-6789
555.444.6789
555 444 6789
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
(003) 555-1212
(103) 555-1212
(911) 555-1212
18005551234
1 800 555 1234
+86 800-555-1234
1 (800) 555-1234
See regex101.com
I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.
C# example
/// <summary>
/// Calculates the distance between two locations using the Great Circle Distance algorithm
/// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
private static double DistanceBetween(GeoLocation first, GeoLocation second)
{
double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));
double centralAngleBetweenLocationsInRadians = Math.Acos(
Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
Math.Cos(longitudeDifferenceInRadians));
const double earthRadiusInMeters = 6357 * 1000;
return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
}
private static double ToRadians(double degrees)
{
return degrees * Math.PI / 180;
}
As written before, the efficiency basically depends on what one is optimizing for.
When optiming for lines of code, or just working in environment without fully-equipped standard library one quick and dirty option could be:
// makes a number from two ascii hexa characters
int ahex2int(char a, char b){
a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
b = (b <= '9') ? b - '0' : (b & 0x7) + 9;
return (a << 4) + b;
}
... more in similar thread here: https://stackoverflow.com/a/58253380/5951263
Maybe this is what you want?
echo foo > test.txt
echo. >> test.txt
echo bar >> test.txt
results in the following within test.txt:
foo
bar
I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:
create table destination_old as select * from destination;
drop table destination;
create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;
It's safe because you have a copy of destination
before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.
Using the pattern above you end up with two country
fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old
and perhaps using coalesce
to retrieve the values from destination_old
if the country
field in source
is null. So for example:
create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;
I was having a problem on Ubuntu 18.04 on Mysql. When I needed to create a new user, the policy was always high.
The way I figured out how to disable, for future colleagues who come to investigate, was set to low.
Login to the mysql server as root
mysql -h localhost -u root -p
Set the new type of validation
SET GLOBAL validate_password_policy=0; //For Low
Restart mysql
sudo service mysql restart
In the case of your fictional getattr
function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None
.
Here's a solution that avoids performing the Charset lookup for every conversion:
import java.nio.charset.Charset;
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
String decodeUTF8(byte[] bytes) {
return new String(bytes, UTF8_CHARSET);
}
byte[] encodeUTF8(String string) {
return string.getBytes(UTF8_CHARSET);
}
Answered here quite elegantly using attached behaviors, my preferred method for almost anything.
^(0|[1-9][0-9]*)$
Disclaimer: This approach is a naive illustration of Ruby's capabilities, and not a production-grade solution for replacing strings in files. It's prone to various failure scenarios, such as data loss in case of a crash, interrupt, or disk being full. This code is not fit for anything beyond a quick one-off script where all the data is backed up. For that reason, do NOT copy this code into your programs.
Here's a quick short way to do it.
file_names = ['foo.txt', 'bar.txt']
file_names.each do |file_name|
text = File.read(file_name)
new_contents = text.gsub(/search_regexp/, "replacement string")
# To merely print the contents of the file, use:
puts new_contents
# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts new_contents }
end
Here's an implementation of URL Safe encryption and Decryption using AES(PyCrypto) and base64.
import base64
from Crypto import Random
from Crypto.Cipher import AES
AKEY = b'mysixteenbytekey' # AES key must be either 16, 24, or 32 bytes long
iv = Random.new().read(AES.block_size)
def encode(message):
obj = AES.new(AKEY, AES.MODE_CFB, iv)
return base64.urlsafe_b64encode(obj.encrypt(message))
def decode(cipher):
obj2 = AES.new(AKEY, AES.MODE_CFB, iv)
return obj2.decrypt(base64.urlsafe_b64decode(cipher))
If you face some issue like this https://bugs.python.org/issue4329 (TypeError: character mapping must return integer, None or unicode
) use str(cipher)
while decoding as follows:
return obj2.decrypt(base64.urlsafe_b64decode(str(cipher)))
Test:
In [13]: encode(b"Hello World")
Out[13]: b'67jjg-8_RyaJ-28='
In [14]: %timeit encode("Hello World")
100000 loops, best of 3: 13.9 µs per loop
In [15]: decode(b'67jjg-8_RyaJ-28=')
Out[15]: b'Hello World'
In [16]: %timeit decode(b'67jjg-8_RyaJ-28=')
100000 loops, best of 3: 15.2 µs per loop
One more way to understand would be to think in terms of communication between processes and threads. Processes communicate with the help of coarse grained communication mechanisms like sockets, signal handlers, shared memory, semaphores and files. Threads, on the other hand, have access to shared memory space that belongs to a process, which allows them to apply finer grain communication mechanisms.
Source: Java concurrency in practice
If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.
However if instead of checking whether an element has a style of style="display:none"
you want to know if that element is visible. Then use .is(":visible")
For example:
$('#idDetails').is(":visible");
This will be true
if it is visible & false
if it is not.
In PowerShell you can use the command Set-Service:
Set-Service -Name Winmgmt -StartupType Manual
I haven't found a PowerShell command to view the startup type though. One would assume that the command Get-Service would provide that, but it doesn't seem to.
It contains the allocated size, 10. The remaining indexes will contain the default value which is 0.
And for Windows 8.1/10 OS Users just open cmd (command prompt)
write this : C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts
then
just write this : pip3 install
{name of package}
Hint: the location of folder Python36-32
may get different for new python 3.x versions
This works for me:
.network-connections-icon {
background-image: url(url);
background-size: 100%;
width: 56px;
height: 56px;
margin: 0 auto;
}
@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate()
(whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).
Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."
This example is use reduce(), but slow it:
def makepnl(pnl, n):
for p in pnl:
if n % p == 0:
return pnl
pnl.append(n)
return pnl
def isprime(n):
return True if n == reduce(makepnl, range(3, n + 1, 2), [2])[-1] else False
for i in range(20):
print i, isprime(i)
It use Sieve Of Atkin, faster than above:
def atkin(limit):
if limit > 2:
yield 2
if limit > 3:
yield 3
import math
is_prime = [False] * (limit + 1)
for x in range(1,int(math.sqrt(limit))+1):
for y in range(1,int(math.sqrt(limit))+1):
n = 4*x**2 + y**2
if n<=limit and (n%12==1 or n%12==5):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3*x**2+y**2
if n<= limit and n%12==7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3*x**2 - y**2
if x>y and n<=limit and n%12==11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5,int(math.sqrt(limit))):
if is_prime[n]:
for k in range(n**2,limit+1,n**2):
is_prime[k] = False
for n in range(5,limit):
if is_prime[n]: yield n
def isprime(n):
r = list(atkin(n+1))
if not r: return False
return True if n == r[-1] else False
for i in range(20):
print i, isprime(i)
Hopefully this would get you started
See it live on http://ideone.com/l23He (using stdin)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ";");
tok && *tok;
tok = strtok(NULL, ";\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("input", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
printf("Field 3 would be %s\n", getfield(tmp, 3));
// NOTE strtok clobbers tmp
free(tmp);
}
}
Output:
Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak
Since this is the top-rated Stack Overflow Google search result for C++ split string
or similar, I'll post a complete, copy/paste runnable example that shows both methods.
splitString
uses stringstream
(probably the better and easier option in most cases)
splitString2
uses find
and substr
(a more manual approach)
// SplitString.cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
// function prototypes
std::vector<std::string> splitString(const std::string& str, char delim);
std::vector<std::string> splitString2(const std::string& str, char delim);
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx);
int main(void)
{
// Test cases - all will pass
std::string str = "ab,cd,ef";
//std::string str = "abcdef";
//std::string str = "";
//std::string str = ",cd,ef";
//std::string str = "ab,cd,"; // behavior of splitString and splitString2 is different for this final case only, if this case matters to you choose which one you need as applicable
std::vector<std::string> tokens = splitString(str, ',');
std::cout << "tokens: " << "\n";
if (tokens.empty())
{
std::cout << "(tokens is empty)" << "\n";
}
else
{
for (auto& token : tokens)
{
if (token == "") std::cout << "(empty string)" << "\n";
else std::cout << token << "\n";
}
}
return 0;
}
std::vector<std::string> splitString(const std::string& str, char delim)
{
std::vector<std::string> tokens;
if (str == "") return tokens;
std::string currentToken;
std::stringstream ss(str);
while (std::getline(ss, currentToken, delim))
{
tokens.push_back(currentToken);
}
return tokens;
}
std::vector<std::string> splitString2(const std::string& str, char delim)
{
std::vector<std::string> tokens;
if (str == "") return tokens;
int leftIdx = 0;
int delimIdx = str.find(delim);
int rightIdx;
while (delimIdx != std::string::npos)
{
rightIdx = delimIdx - 1;
std::string token = getSubstring(str, leftIdx, rightIdx);
tokens.push_back(token);
// prep for next time around
leftIdx = delimIdx + 1;
delimIdx = str.find(delim, delimIdx + 1);
}
rightIdx = str.size() - 1;
std::string token = getSubstring(str, leftIdx, rightIdx);
tokens.push_back(token);
return tokens;
}
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx)
{
return str.substr(leftIdx, rightIdx - leftIdx + 1);
}
The problem is that the path to GraphViz was not found by the pydot module as shown in the traceback:
'GraphViz\'s executables not found'
I solved this problem on my windows 7 machine by adding the GraphViz bin directory to my computer's PATH. Then restarting my python IDE to use the updated path.
Open a visual command console (Visual Studio Command Prompt)
dumpbin /ARCHIVEMEMBERS openssl.x86.lib
or
lib /LIST openssl.x86.lib
or just open it with 7-zip :) its an AR archive
For larger data sets where sorting may not be desirable, you can also use the following perl script:
./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'
This basically just remembers every line output so that it doesn't output it again.
It has the advantage over the "sort | uniq
" solution in that there's no sorting required up front.
CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)
You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them.
And in swift we can do
UIApplication.sharedApplication().sendAction("resignFirstResponder", to: nil, from: nil, forEvent: nil)
I caught this error a few days ago.
IN my case it was because I was using a Transaction on a Singleton.
.Net does not work well with Singleton as stated above.
My solution was this:
public class DbHelper : DbHelperCore
{
public DbHelper()
{
Connection = null;
Transaction = null;
}
public static DbHelper instance
{
get
{
if (HttpContext.Current is null)
return new DbHelper();
else if (HttpContext.Current.Items["dbh"] == null)
HttpContext.Current.Items["dbh"] = new DbHelper();
return (DbHelper)HttpContext.Current.Items["dbh"];
}
}
public override void BeginTransaction()
{
Connection = new SqlConnection(Entity.Connection.getCon);
if (Connection.State == System.Data.ConnectionState.Closed)
Connection.Open();
Transaction = Connection.BeginTransaction();
}
}
I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class
I had a similar issue and i just fixed it for now
You need to select that column:
In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df
Out[41]:
Team First Season Total Games
0 Dallas Cowboys 1960 894
1 Chicago Bears 1920 1357
2 Green Bay Packers 1921 1339
3 Miami Dolphins 1966 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 1950 1003
So the syntax here is:
df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
You can check the docs and also the 10 minutes to pandas which shows the semantics
EDIT
If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int
this will convert True
and False
to 1
and 0
respectively:
In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df
Out[43]:
Team First Season Total Games
0 Dallas Cowboys 0 894
1 Chicago Bears 0 1357
2 Green Bay Packers 0 1339
3 Miami Dolphins 0 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 0 1003
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Instead of passing functions or querying it on the controller, I think what you need is relationships on models since these are related tables on your database.
If based on your structure, input_details and products are related you should put relationship definition on your models like this:
public class InputDetail(){
protected $table = "input_details";
....//other code
public function product(){
return $this->hasOne('App\Product');
}
}
then in your view you'll just have to say:
<p>{{ $input_details->product->name }}</p>
More simpler that way. It is also the best practice that controllers should only do business logic for the current resource. For more info on how to do this just go to the docs: https://laravel.com/docs/5.0/eloquent#relationships
You can also use Projections:
ProjectionList projection = Projections.projectionList();
projection.add(Projections.rowCount());
criteria.setProjection(projection);
Long totalRows = (Long) criteria.list().get(0);
Note that if you're using IntelliJ, you'll want to install the Lombok plugin (available from IDE settings) and also enable annotation processing.
Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.
Step 1) Add a COM reference in your project to Microsoft HTML Object Library
Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml
Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>
Step 4) Add a WebBrowser control to your project
Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me
Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:
Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
Dim head As HtmlElement
Dim script As HtmlElement
Dim domElement As IHTMLScriptElement
head = wb.Document.GetElementsByTagName("head")(0)
script = wb.Document.CreateElement("script")
domElement = script.DomElement
domElement.type = "text/javascript"
domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
head.AppendChild(script)
End Sub
Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:
Public Sub Callback_GetVar(ByVal vVar As String)
Debug.Print(vVar)
End Sub
Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
End Sub
Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.
start
did not work for me.
I used:
firefox http://www.stackoverflow.com
or
chrome http://www.stackoverflow.com
Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.
Here is what worked for me.
To set the server anonymous to inherit from the app pool identity do the following..
I was able to get this done following more complex instructions suggested by Valentino Vranken and rao , but here is a more simple approach , for a more simple report . This will put each table on a separate sheet and name them in Excel . It doesn't seem to have an effect on other exports like PDF and Word .
First in the Tablix Properties
of of your tables under General
, check either Add a page break before or after
, this separates the report into sheets .
Then in each table , click the table , then in the Grouping
view , on the Row Groups
side , select the parent group or the default row group and then in the Properties
view under Group -> PageBreak
set BreakLocation
to None
and PageName
to the sheet's name .
let videoUrl = //URL: Your Video URL
//Create player first using your URL
let yourplayer = AVPlayer(url: videoUrl)
//Create player controller and set it’s player
let playerController = AVPlayerViewController()
playerController.player = yourplayer
//Final step To present controller with player in your view controller
present(playerController, animated: true, completion: {
playerController.player!.play()
})
For me, I couldn't get this to return a hash.
results = ActiveRecord::Base.connection.execute(sql)
But using the exec_query method worked.
results = ActiveRecord::Base.connection.exec_query(sql)
If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:
NSLOOKUP fabrikam.com
Test-NetConnection <IP returned from NSLOOKUP> -port 389
Delete duplicate rows using DELETE JOIN statement MySQL provides you with the DELETE JOIN statement that you can use to remove duplicate rows quickly.
The following statement deletes duplicate rows and keeps the highest id:
DELETE t1 FROM contacts t1
INNER JOIN
contacts t2 WHERE
t1.id < t2.id AND t1.email = t2.email;
You can not restore database (or attach) created in the upper version into lower version. The only way is to create a script for all objects and use the script to generate database.
select "Schema and Data" - if you want to Take both the things in to the Backup script file
select Schema Only - if only schema is needed.
Yes, now you have done with the Create Script with Schema and Data of the Database.
Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}
. If you left the routing as the default {controller}/{action}/{id}
in your global.asax.cs
file, then you will need to pass in id
.
routes.MapRoute(
"Inventory",
"Inventory/{action}/{firstItem}",
new { controller = "Inventory", action = "ListAll", firstItem = "" }
);
... or something close to that.
Go to Anaconda Naviagator, find spyder,click settings in the top right corner of the spyder app.click update tab
You can also create a new jsp file sayng that form is submited and in your main action file just write its file name
Eg. Your form is submited is in a file succes.jsp Then your action file will have
Request.sendRedirect("success.jsp")
If you want to recursively apply this change to all files in a directoy, you can use the Find > Find in Files... modal:
Edit I didn't highlight it in the image, but you have to click the .* button on the left to have Sublime interpret the Find field as a regex /Edit
Edit 2 I neglected to add a start of string anchor to the regex. I'm correcting that below, and will update the image when I get a chance /Edit
The regex in the Find field ^[^\S\t\n\r]{4}
will match white space characters in groups of 4 (excluding tabs and newline characters). The replace field \t
indicates you would like to replace them with tabs.
If you click the button to the right of the Where field, you'll see options that will help you target your search, replace. Add Folder
option will let you select the folder you'd like to recursively search from. The Add Include Filter
option will let you restrict the search to files of a certain extension.
Hi You have separate T Format and then convert as you like
// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(date!)
Unfortunately, there is no guaranteed way to do it at time of selection.
Some browsers support the accept
attribute for input
tags. This is a good start, but cannot be relied upon completely.
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
You can use a cfinput
and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.
ColdFusion's cffile
can check the mime-type using the contentType
property of the result (cffile.contentType
), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.
Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)
<table id="tableHeader" class="table" style="table-layout:fixed">
<thead>
<tr>
<th>Col1</th>
...
</tr>
</thead>
</table>
<div style="overflow-y:auto;">
<table id="tableData" class="table table-condensed" style="table-layout:fixed">
<tbody>
<tr>
<td>data</td>
...
</tr>
</tbody>
</table>
</div>
The content table div needs overflow-y:auto
, for vertical scroll bars. Had to use table-layout:fixed
, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.
Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.
// ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
$(function () {
//copy width of header cells to match width of cells with data
//so they line up properly
var tdHeader = document.getElementById("tableHeader").rows[0].cells;
var tdData = document.getElementById("tableData").rows[0].cells;
for (var i = 0; i < tdData.length; i++)
tdHeader[i].style.width = tdData[i].offsetWidth + 'px';
});
according to @jreback here https://github.com/conda/conda/issues/1166
conda config --set ssl_verify false
will turn off this feature, e.g. here
You get SyntaxError
error exception because Python has no &&
operator. It has and
and &
where the latter one is the correct choice to create boolean expressions on Column
(|
for a logical disjunction and ~
for logical negation).
Condition you created is also invalid because it doesn't consider operator precedence. &
in Python has a higher precedence than ==
so expression has to be parenthesized.
(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>
On a side note when
function is equivalent to case
expression not WHEN
clause. Still the same rules apply. Conjunction:
df.where((col("foo") > 0) & (col("bar") < 0))
Disjunction:
df.where((col("foo") > 0) | (col("bar") < 0))
You can of course define conditions separately to avoid brackets:
cond1 = col("Age") == ""
cond2 = col("Survived") == "0"
cond1 & cond2
EDIT: as_matrix
is deprecated since version 0.23.0
You can use the built in values
or to_numpy
(recommended option) method on the dataframe:
In [8]:
df.to_numpy()
Out[8]:
array([[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.8, 6.1, 5.4, ..., 15.9, 14.4, 8.6],
...,
[ 0.2, 1.3, 2.3, ..., 16.1, 16.1, 10.8],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4]])
If you explicitly want lists and not a numpy array add .tolist()
:
df.to_numpy().tolist()
It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. Select2 does not have a custom event (like select2:update) that can be triggered other than change. You can rely on jQuery's event namespacing to limit the scope to Select2 though by triggering the *change.select2 event.
$('#state').trigger('change.select2'); // Notify only Select2 of changes
There is a linear relationship between the radius and the number of points "near" that radius, so he needs to use a radius distribution that is also makes the number of data points near a radius r
proportional to r
.
You can set the ReadOnly property to true.
Quoth the link:
When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.
if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:
import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';
const temp = (
<div>
<img src={logo} />
<img src={image} />
</div>
);
ReactDOM.render(temp,document.getElementByID("app"));
Happy Coding :")
resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/
I have run into a similar problem on Mac.
Looking at the log under Help -> Show logs in Finder I found the following entry.
You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)
and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.
Actually I think OZ_ may be somewhat correct.
If you have the route '/users/:userId'
and navigate to '/users/'
(note the trailing /), $routeParams
in your controller should be an object containing userId: ""
in 1.1.5. So no the paramater userId
isn't completely ignored, but I think it's the best you're going to get.
This is maybe not the case of original OP question, but: if you exceeds the default max size, this maybe a symptom of some other issue you have. in my case, I had the warrning, but finally it turned into a FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory. the reason was that i dynamically imported the current module, so this ended up with an endless loop...
With React Navigation v5, just use the navigate method. From the docs:
To achieve this, you can use the navigate method, which acts like goBack if the screen already exists. You can pass the params with navigate to pass the data back
Full example:
import React from 'react';
import { StyleSheet, Button, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function ScreenA ({ navigation, route }) {
const { params } = route;
return (
<View style={styles.container}>
<Text>Params: {JSON.stringify(params)}</Text>
<Button title='Go to B' onPress={() => navigation.navigate('B')} />
</View>
);
}
function ScreenB ({ navigation }) {
return (
<View style={styles.container}>
<Button title='Go to A'
onPress={() => {
navigation.navigate('A', { data: 'Something' })
}}
/>
</View>
);
}
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator mode="modal">
<Stack.Screen name="A" component={ScreenA} />
<Stack.Screen name="B" component={ScreenB} />
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.
And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.
I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.
I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.
# Enable TCP/IP
Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable
# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433
# Modify TCP/IP properties to enable an IP address
$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }
# Restart SQL Server
Restart-Service 'MSSQL$SQLEXPRESS'
Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.
I realize this question has an answer, but it's no longer accurate. Use the link above ^
(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)
Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.
Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)
In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
For example if there are 4 project and a root project, add the other child projects to build path of root project. If there is not selection of build path, add below codes to .project file.
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>rootProject</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>
You can also use the combination of find and awk commands to print the directory tree. For details, please refer to "How to print a multilevel tree directory structure using the linux find and awk combined commands"
find . -type d | awk -F'/' '{
depth=3;
offset=2;
str="| ";
path="";
if(NF >= 2 && NF < depth + offset) {
while(offset < NF) {
path = path "| ";
offset ++;
}
print path "|-- "$NF;
}}'
Download Git on Msys. Then:
git clone git://project.url.here
FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.
main.c has a main wrapper like this:
#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
// the true main() routine.
}
spi.c, serial.c and usb.c have main wrappers for their respective test code like this:
#ifdef TEST_USB
int main(int argc, char *argv[]) {
// the main() routine for testing the usb code.
}
config.h Which is included by all the c files has an entry like this:
// Uncomment below to test the serial
//#define TEST_SERIAL
// Uncomment below to test the spi code
//#define TEST_SPI
// Uncomment below to test the usb code
#define TEST_USB
The error is simply asking you to insert a Middleware in between which would help to handle async operations.
You could do that by :
npm i redux-thunk
Inside index.js
import thunk from "redux-thunk"
...createStore(rootReducers, applyMiddleware(thunk));
Now, async operations will work inside your functions.
You can run this example directly.
aspx page:
<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
<ItemTemplate>
<asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
<ItemTemplate>
<asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grd.DataSource = GetTableWithInitialData(); // get first initial data
grd.DataBind();
}
}
public DataTable GetTableWithInitialData() // this might be your sp for select
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
table.Rows.Add(1, "David", "1");
table.Rows.Add(2, "Sam", "2");
table.Rows.Add(3, "Christoff", "1.5");
return table;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
DataTable dt = GetTableWithNoData(); // get select column header only records not required
DataRow dr;
foreach (GridViewRow gvr in grd.Rows)
{
dr = dt.NewRow();
TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;
dr[0] = txtPayScale.Text;
dr[1] = txtIncrementAmount.Text;
dr[2] = txtPeriod.Text;
dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
}
dr = dt.NewRow(); // add last empty row
dt.Rows.Add(dr);
grd.DataSource = dt; // bind new datatable to grid
grd.DataBind();
}
public DataTable GetTableWithNoData() // returns only structure if the select columns
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
return table;
}
NumPy 1.7.0 (when numpy.pad
was added) is pretty old now (it was released in 2013) so even though the question asked for a way without using that function I thought it could be useful to know how that could be achieved using numpy.pad
.
It's actually pretty simple:
>>> import numpy as np
>>> a = np.array([[ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.]])
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
In this case I used that 0
is the default value for mode='constant'
. But it could also be specified by passing it in explicitly:
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant', constant_values=0)
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
Just in case the second argument ([(0, 1), (0, 1)]
) seems confusing: Each list item (in this case tuple) corresponds to a dimension and item therein represents the padding before (first element) and after (second element). So:
[(0, 1), (0, 1)]
^^^^^^------ padding for second dimension
^^^^^^-------------- padding for first dimension
^------------------ no padding at the beginning of the first axis
^--------------- pad with one "value" at the end of the first axis.
In this case the padding for the first and second axis are identical, so one could also just pass in the 2-tuple:
>>> np.pad(a, (0, 1), mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
In case the padding before and after is identical one could even omit the tuple (not applicable in this case though):
>>> np.pad(a, 1, mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0., 0.]])
Or if the padding before and after is identical but different for the axis, you could also omit the second argument in the inner tuples:
>>> np.pad(a, [(1, ), (2, )], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
However I tend to prefer to always use the explicit one, because it's just to easy to make mistakes (when NumPys expectations differ from your intentions):
>>> np.pad(a, [1, 2], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])
Here NumPy thinks you wanted to pad all axis with 1 element before and 2 elements after each axis! Even if you intended it to pad with 1 element in axis 1 and 2 elements for axis 2.
I used lists of tuples for the padding, note that this is just "my convention", you could also use lists of lists or tuples of tuples, or even tuples of arrays. NumPy just checks the length of the argument (or if it doesn't have a length) and the length of each item (or if it has a length)!
Since java 8 there is easy way to do it with Lambda:
yourMap.keySet().forEach(key -> {
Object obj = yourMap.get(key);
System.out.println( obj);
}
You literally just pass them in std::thread(func1,a,b,c,d);
that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate
is called. You could std::join
or std::detach
it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach
.
This is how it should be done.
std::thread t(func1,a,b,c,d);
t.join();
You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.
The correct way to do it for Material design is :
Style :
<style name="MyCheckBox" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">@color/foo</item>
<item name="colorControlActivated">@color/bar</item>
</style>
Layout :
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Check Box"
android:theme="@style/MyCheckBox"/>
It will preserve Material animations on Lollipop+.
Mixin for Less
.appearance (@value: none) {
-webkit-appearance: @value;
-moz-appearance: @value;
-ms-appearance: @value;
-o-appearance: @value;
appearance: @value;
}
UPDATE db.tablename SET columnID = (SELECT UUID()) where columnID is not null
To expand upon this point:
It is possible that the args variable itself will be null, but not via normal execution. Normal execution will use java.exe
as the entry point from the command line. However, I have seen some programs that use compiled C++
code with JNI to use the jvm.dll
, bypassing the java.exe entirely. In this case, it is possible to pass NULL
to the main method, in which case args will be null.
I recommend always checking if ((args == null) || (args.length == 0))
, or if ((args != null) && (args.length > 0))
depending on your need.
If you are using Laravel framework then it's more easy to encrypt and decrypt with internal functions.
$string = 'Some text to be encrypted';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);
var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);
Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.
ChronoUnit.between
Use instances of ChronoUnit
to calculate amount of time in different units (days,months, seconds).
For Example:
ChronoUnit.DAYS.between(startDate,endDate)
In JavaScript that would be a global. However, your function would look more like this:
function a(){
x++;
};
Since x
is in the global context, you don't need to pass it into the function.
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
If you use the DateTime.ParseExact()
-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment!
In Denmark, which of ParseExact("Januar", ...)
and ParseExact("January", ...)
should work and which should fail?
That will be the difference between CultureInfo.CurrentCulture
and CultureInfo.InvariantCulture
.
Check this:
UIAlertController *alertctrl =[UIAlertController alertControllerWithTitle:@"choose Image" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *camera =[UIAlertAction actionWithTitle:@"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self Action]; //call Action need to perform
}];
[alertctrl addAction:camera];
-(void)Action
{
}
This is how to create a jQuery live remove listener:
$(document).on('DOMNodeRemoved', function(e)
{
var $element = $(e.target).find('.element');
if ($element.length)
{
// do anything with $element
}
});
Or:
$(document).on('DOMNodeRemoved', function(e)
{
$(e.target).find('.element').each(function()
{
// do anything with $(this)
}
});
Not 96x96, use 64x64 instead. I usually use:
256 works as well on XP, however, old resource compilers sometimes complained about "out of memory" errors.
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
This seems to work (for now):
https://mail.google.com/mail/?view=cm&fs=1&[email protected]&su=SUBJECT&body=BODY&[email protected]
array = new String[array.length];
Swift 3.1 You can do this by implementing the delegate method of UINavigationController. It'll hide the Title with back button only, we'll still get the back arrow image and default functionality.
func navigationController(_ navigationController: UINavigationController,
willShow viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .plain, target: nil,
action: nil)
viewController.navigationItem.backBarButtonItem = item
}
On Edge
if(!NodeList.prototype.forEach) {
NodeList.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
Considering lolesque's comment to best answer you can add either an attribute or a class to show/hide elements with display properties that differs from what it normally has, if your site needs backwards compatibility I would suggest making a class and adding/removing it to show/display the element
.news-show {
display:inline-block;
}
.news-hide {
display:none;
}
Replace inline-block with your preferred display method of your choice and use jquerys addclass https://api.jquery.com/addclass/ and removeclass https://api.jquery.com/removeclass/ instead of show/hide, if backwards compatibility is no problem you can use attributes like this.
.news[data-news-visible=show] {
display:inline-block;
}
.news[data-news-visible=hide] {
display:none;
}
And use jquerys attr() http://api.jquery.com/attr/ to show and hide the element.
Whichever method you prefer it makes you able to easily implement css3 animations when showing/hiding elements this way
I think that if you have a to
, you must use a from
.
I would think of something like :
@keyframe in {
from: transform: rotate(0deg);
to: transform: rotate(360deg);
}
@keyframe out {
from: transform: rotate(360deg);
to: transform: rotate(0deg);
}
Of course must have checked it already, but I found strange that you only use the transform
property since CSS3 is not fully implemented everywhere. Maybe it would work better with the following considerations :
@-webkit-keyframes
, no particuliar version needed@-webkit-keyframes
since version 5+@keyframes
since version 16 (v5-15 used @-moz-keyframes
)@-webkit-keyframes
version 15-22 (only v12 used @-o-keyframes
)@keyframes
since version 10+EDIT :
I came up with that fiddle :
Using minimal code. Is it approaching what you were expecting ?
You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):
CREATE OR REPLACE FUNCTION get_allitems
RETURN SYS_REFCURSOR
AS
my_cursor SYS_REFCURSOR;
BEGIN
OPEN my_cursor FOR SELECT * FROM allitems;
RETURN my_cursor;
END get_allitems;
This will return the cursor.
Make sure not to put your SELECT
-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.
If you really need to use dynamic SQL you can put your query in single quotes:
OPEN my_cursor FOR 'SELECT * FROM allitems';
This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.
Make sure to use bind-variables where possible to avoid hard parses:
OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;
I was receiving this error because I happened to be opening a website project over a mapped network drive z:\folder
instead of connecting via a UNC path \\server\path\folder
. Once I opened the project from the UNC path it built just fine.
The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.
http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm
Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.
I put the data starting on row 5:
Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.
That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.
You can do
dt[, !c("V1","V2","V3","V5")]
to get
V4 V6 V7 V8 V9 V10
1: 0.88612076 0.94727825 0.50502208 0.6702523 0.24186706 0.96263313
2: 0.11121752 0.13969145 0.19092645 0.9589867 0.27968190 0.07796870
3: 0.50179822 0.10641301 0.08540322 0.3297847 0.03643195 0.18082180
4: 0.09787517 0.07312777 0.88077548 0.3218041 0.75826099 0.55847774
5: 0.73475574 0.96644484 0.58261312 0.9921499 0.78962675 0.04976212
6: 0.88861117 0.85690337 0.27723130 0.3662264 0.50881663 0.67402625
7: 0.33933983 0.83392047 0.30701697 0.6138122 0.85107176 0.58609504
8: 0.89907094 0.61389815 0.19957386 0.3968331 0.78876682 0.90546328
9: 0.54136123 0.08274569 0.25190790 0.1920462 0.15142604 0.12134807
10: 0.36511064 0.88117171 0.05730210 0.9441072 0.40125023 0.62828674
FOR FADE add this first line with your animation's object.
.animate().alpha(1).setDuration(2000);
Currently there is still no native solution in Javascript for this behavior. Tagged templates are something related, but don't solve it.
Here there is a refactor of alex's solution with an object for replacements.
The solution uses arrow functions and a similar syntax for the placeholders as the native Javascript interpolation in template literals ({}
instead of %%
). Also there is no need to include delimiters (%
) in the names of the replacements.
There are two flavors (three with the update): descriptive, reduced, elegant reduced with groups.
Descriptive solution:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(
/{\w+}/g,
placeholderWithDelimiters => {
const placeholderWithoutDelimiters = placeholderWithDelimiters.substring(
1,
placeholderWithDelimiters.length - 1,
);
const stringReplacement = replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters;
return stringReplacement;
},
);
console.log(string);
_x000D_
Reduced solution:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(/{\w+}/g, placeholder =>
replacements[placeholder.substring(1, placeholder.length - 1)] || placeholder
);
console.log(string);
_x000D_
Elegant reduced solution with groups, as suggested by @Kade in the comments:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(
/{(\w+)}/g,
(placeholderWithDelimiters, placeholderWithoutDelimiters) =>
replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters
);
console.log(string);
_x000D_
Support empty string as a replacement, as suggested by @Jesper in the comments:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '',
};
const string = stringWithPlaceholders.replace(
/{(\w+)}/g,
(placeholderWithDelimiters, placeholderWithoutDelimiters) =>
replacements.hasOwnProperty(placeholderWithoutDelimiters) ?
replacements[placeholderWithoutDelimiters] : placeholderWithDelimiters
);
console.log(string);
_x000D_
Thanks a lot for these (surprisingly) quick and helpful answers; they put me on the right way for my solution.
The codebase were I want to use this, uses java.util.logging as its logger mechanism, and I don't feel at home enough in those codes to completely change that to log4j or to logger interfaces/facades. But based on these suggestions, I 'hacked-up' a j.u.l.handler extension and that works as a treat.
A short summary follows. Extend java.util.logging.Handler
:
class LogHandler extends Handler
{
Level lastLevel = Level.FINEST;
public Level checkLevel() {
return lastLevel;
}
public void publish(LogRecord record) {
lastLevel = record.getLevel();
}
public void close(){}
public void flush(){}
}
Obviously, you can store as much as you like/want/need from the LogRecord
, or push them all into a stack until you get an overflow.
In the preparation for the junit-test, you create a java.util.logging.Logger
and add such a new LogHandler
to it:
@Test tester() {
Logger logger = Logger.getLogger("my junit-test logger");
LogHandler handler = new LogHandler();
handler.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
logger.addHandler(handler);
logger.setLevel(Level.ALL);
The call to setUseParentHandlers()
is to silence the normal handlers, so that (for this junit-test run) no unnecessary logging happens. Do whatever your code-under-test needs to use this logger, run the test and assertEquality:
libraryUnderTest.setLogger(logger);
methodUnderTest(true); // see original question.
assertEquals("Log level as expected?", Level.INFO, handler.checkLevel() );
}
(Of course, you would move large part of this work into a @Before
method and make assorted other improvements, but that would clutter this presentation.)