You have to load the url helper to access that function. Either you add
$this->load->helper('url');
somewhere in your controller.
Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like
$autoload['helper'] = array('url');
has 'url'
in that array (as shown above).
Here is a very useful and lightweight javascript plugin to accomplish this: js-cookie
Cookies.set('cookieName', 'Value');
setTimeout(function(){
var cookieValue = Cookies.get('cookieName');
if(cookieValue){
console.log("Test Cookie is set!");
} else {
document.write('<p>Sorry, but cookies must be enabled</p>');
}
Cookies.remove('cookieName');
}, 1000);
Works in all browsers, accepts any character.
Interned Strings avoid duplicate Strings. Interning saves RAM at the expense of more CPU time to detect and replace duplicate Strings. There is only one copy of each String that has been interned, no matter how many references point to it. Since Strings are immutable, if two different methods incidentally use the same String, they can share a copy of the same String. The process of converting duplicated Strings to shared ones is called interning.String.intern() gives you the address of the canonical master String. You can compare interned Strings with simple == (which compares pointers) instead of equals which compares the characters of the String one by one. Because Strings are immutable, the intern process is free to further save space, for example, by not creating a separate String literal for "pot" when it exists as a substring of some other literal such as "hippopotamus".
To see more http://mindprod.com/jgloss/interned.html
First,
always define certificates with CURLOPT_CAPATH option,
decide how your POSTed data will be transfered.
By default:
CURLOPT_SSL_VERIFYHOST == 2
which "checks the existence of a common name and also verify that it matches the hostname provided" and
CURLOPT_VERIFYPEER == true
which "verifies the peer's certificate".
So, all you have to do is:
const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);
taken from a working class where SERVER_ROOT
is a constant defined during application bootstraping like in a custom classloader, another class etc.
Forget things like \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0);
or \curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);
.
Find cacert.pem
there as seen in this question.
There are actually 2 modes when posting data:
the data is transfered with Content-Type
header set to multipart/form-data
or,
the data is a urlencoded string with application/x-www-form-urlencoded
encoding.
In the first case you pass an array while in the second you pass a urlencoded string.
multipart/form-data
ex.:$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
application/x-www-form-urlencoded
ex.:$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));
http_build_query
:Test it at your command line as
user@group:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else
The other end of the POST request will define the appropriate mode of connection.
There are multiple popular repositories offering docker packages for Ubuntu. The package docker.io
is (most likely) from the Ubuntu repository. Another popular one is http://get.docker.io/ubuntu
which offers a package lxc-docker
(I am running the latter because it ships updates faster). Make sure only one package is installed. Not quite sure if removal of the packages cleans up properly. If sudo service docker restart
still does not work, you may have to clean up manually in /etc/.
Not sure if this is what you're referring to, but this is the list of HTML entities you can use:
List of XML and HTML character entity references
Using the content within the 'Name' column you can just wrap these in an &
and ;
E.g.
,  
, etc.
You can easily add a drop-shadow effect to an svg-element using the drop-shadow() CSS function and rgba color values. By using rgba color values you can change the opacity of your shadow.
img.light-shadow{_x000D_
filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.4));_x000D_
}_x000D_
_x000D_
img.dark-shadow{_x000D_
filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 1));_x000D_
}
_x000D_
<img class="light-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />_x000D_
<img class="dark-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />
_x000D_
You need to make a second groupby object that groups by the states, and then use the div
method:
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]})
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100
sales
state office_id
AZ 2 16.981365
4 19.250033
6 63.768601
CA 1 19.331879
3 33.858747
5 46.809373
CO 1 36.851857
3 19.874290
5 43.273852
WA 2 34.707233
4 35.511259
6 29.781508
the level='state'
kwarg in div
tells pandas to broadcast/join the dataframes base on the values in the state
level of the index.
As Marineio said, you could use the onclick
attribute of the <li>
to change location.href
, through javascript:
<li onclick="location.href='http://example';"> ... </li>
Alternatively, you could remove any margins or padding in the <li>
, and add a large padding to the left side of the <a>
to avoid text going over the bullet.
You could try Directory.Exists(path)
and Directory.GetFiles(path)
- probably less overhead (no objects - just strings etc).
Subclassing and over-riding layoutSubviews is probably your best way to go.
Referenced from: iPhone UIButton - image position
new ModelAndView("welcomePage", "WelcomeMessage", message);
is shorthand for
ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);
Looking at the code above, you can see the view name is "welcomePage". Your ViewResolver
(usually setup in .../WEB-INF/spring-servlet.xml
) will translate this into a View. The last line of the code sets an attribute in your model (addObject("WelcomeMessage", message)
). That's where the model comes into play.
In my case I parsed an S3 url into its components.
For example:
Url: s3://bucket-name/path/to/file
Was parsed into:
Bucket: bucket-name
Path: /path/to/file
Having the path part containing a leading '/' failed the request.
This may help you ;D
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
float Stukprijs;
float Aantal;
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
}
private void button1_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
errorProvider2.Clear();
if (float.TryParse(textBox1.Text, out Stukprijs))
{
if (float.TryParse(textBox2.Text, out Aantal))
{
float Totaal = Stukprijs * Aantal;
string Output = Totaal.ToString();
textBox3.Text = Output;
if (Totaal >= 100)
{
float korting = Totaal - 100;
float korting2 = korting / 100 * 15;
string Output2 = korting2.ToString();
textBox4.Text = Output2;
if (korting2 >= 10)
{
textBox4.BackColor = Color.LightGreen;
}
else
{
textBox4.BackColor = SystemColors.Control;
}
}
else
{
textBox4.Text = "0";
textBox4.BackColor = SystemColors.Control;
}
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
else
{
errorProvider1.SetError(textBox1, "Bedrag plz!");
if (float.TryParse(textBox2.Text, out Aantal))
{
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
}
private void BTNwissel_Click(object sender, EventArgs e)
{
//LL, LU, LR, LD.
Color c = LL.BackColor;
LL.BackColor = LU.BackColor;
LU.BackColor = LR.BackColor;
LR.BackColor = LD.BackColor;
LD.BackColor = c;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
}
}
}
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>
$("#chkAll").click(function() {
$(".chkGroup").attr("checked", this.checked);
});
With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:
$(".chkGroup").click(function() {
$("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});
Your select count and select max should be from your table variable instead of the actual table
DECLARE @i int
DECLARE @PractitionerId int
DECLARE @numrows int
DECLARE @Practitioner TABLE (
idx smallint Primary Key IDENTITY(1,1)
, PractitionerId int
)
INSERT @Practitioner
SELECT distinct PractitionerId FROM Practitioner
SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @Practitioner)
IF @numrows > 0
WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))
BEGIN
SET @PractitionerId = (SELECT PractitionerId FROM @Practitioner WHERE idx = @i)
--Do something with Id here
PRINT @PractitionerId
SET @i = @i + 1
END
I have recently blogged on a solution that worked for me by using a Markdown XSLT file to transform the HTML Source. The HTML source will of course need to be valid XML first
If you want to query the results from a temporary table inside the same query, you can use # temp tables, or @ table variables (I personally prefer @), for querying outside of the scope you would either want to use ## global temp tables or create a new table with the results.
DECLARE
@ProjectID int = 3,
@Year int = 2010,
@MeterTypeID int = 1,
@StartDate datetime,
@EndDate datetime
SET @StartDate = '07/01/' + CAST(@Year as VARCHAR)
SET @EndDate = '06/30/' + CAST(@Year+1 as VARCHAR)
DECLARE @MyTempTable TABLE (SiteName varchar(50), BillingMonth varchar(10), Consumption float)
INSERT INTO @MyTempTable (SiteName, BillingMonth, Consumption)
SELECT tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101) AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
There are several places where you can set environment variables.
~/.profile
: use this for variables you want to set in all programs launched from the terminal (note that, unlike on Linux, all shells opened in Terminal.app are login shells).~/.bashrc
: this is invoked for shells which are not login shells. Use this for aliases and other things which need to be redefined in subshells, not for environment variables that are inherited./etc/profile
: this is loaded before ~/.profile, but is otherwise equivalent. Use it when you want the variable to apply to terminal programs launched by all users on the machine (assuming they use bash).~/.MacOSX/environment.plist
: this is read by loginwindow on login. It applies to all applications, including GUI ones, except those launched by Spotlight in 10.5 (not 10.6). It requires you to logout and login again for changes to take effect. This file is no longer supported as of OS X 10.8.launchd
instance: this applies to all programs launched by the user, GUI and CLI. You can apply changes at any time by using the setenv
command in launchctl
. In theory, you should be able to put setenv
commands in ~/.launchd.conf
, and launchd
would read them automatically when the user logs in, but in practice support for this file was never implemented. Instead, you can use another mechanism to execute a script at login, and have that script call launchctl
to set up the launchd
environment./etc/launchd.conf
: this is read by launchd when the system starts up and when a user logs in. They affect every single process on the system, because launchd is the root process. To apply changes to the running root launchd you can pipe the commands into sudo launchctl
.The fundamental things to understand are:
launchctl
; the updated variables are then inherited by all new processes it forks from then on.Example of setting an environment variable with launchd:
echo setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE | launchctl
Now, launch your GUI app that uses the variable, and voila!
To work around the fact that ~/.launchd.conf
does not work, you can put the following script in ~/Library/LaunchAgents/local.launchd.conf.plist
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>local.launchd.conf</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>launchctl < ~/.launchd.conf</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Then you can put setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE
inside ~/.launchd.conf
, and it will be executed at each login.
Note that, when piping a command list into launchctl in this fashion, you will not be able to set environment variables with values containing spaces. If you need to do so, you can call launchctl as follows: launchctl setenv MYVARIABLE "QUOTE THE STRING"
.
Also, note that other programs that run at login may execute before the launchagent, and thus may not see the environment variables it sets.
You can also split a string at every n-th character and put them each, in each index of a List :
Here I made a list of Strings named Sequence :
List < String > Sequence
Then I'm basically splitting the String "KILOSO" by every 2 words. So 'KI' 'LO' 'SO' would be incorporate in separate index of the List called Sequence.
String S = KILOSO
Sequence = Arrays.asList(S.split("(?<=\G..)"));
So when I'm doing :
System.out.print(Sequence)
It should print :
[KI, LO, SO]
to verify I can write :
System.out.print(Sequence.get(1))
it will print :
LO
There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:
HorizontalContentAlignment="Stretch"
... to force the contents of a control to stretch horizontally. Or you can say:
HorizontalAlignment="Stretch"
... to force the control itself to stretch horizontally to fill its parent.
I find that the best solution to comparing a datetime field to a date field is the following:
DECLARE @StartDate DATE = '5/1/2013',
@EndDate DATE = '5/1/2013'
SELECT *
FROM cases
WHERE Datediff(day, created_at, @StartDate) <= 0
AND Datediff(day, created_at, @EndDate) >= 0
This is equivalent to an inclusive between statement as it includes both the start and end date as well as those that fall between.
you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java
Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?
CASE AlarmEventTransactions.DeviceID
should just be CASE
.
You are mixing the 2 forms of the CASE
expression.
Function imageMorph
will create a new img element therefore the id is removed.
Changed to
$("#wrapper > img")
You should use live() function for click event if you want you rocket lanch again.
Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/
Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.
I was having the same problem while making a POST request from Postman and later I could solve the problem by setting a custom Content-Type with a boundary value set along with it like this.
I thought people can run into similar problem and hence, I'm sharing my solution.
Well there are lot of answeres already provided and lot are making sense too.
Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.
I came across similar situation today and here is very simple query I came up with...
declare
begin
execute immediate '
create table "TBL" ("ID" number not null)';
exception when others then
if SQLCODE = -955 then null; else raise; end if;
end;
/
955 is failure code.
This is simple, if exception come while running query it will be suppressed. and you can use same for SQL
or Oracle
.
I found a new error code which is not documented above: CFNetworkErrorCode -1022
Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'
or you could always get geekier with regexps :)
have fun!
I doubt there is one... It depends on browser, on printer (physical max dpi) and its driver, on paper size as you point out (and I might want to print on B5 paper too...), on settings (landscape or portrait?), plus you often can change the scale (percentage), etc.
Let the users tweak their settings...
It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:
Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.
Underneath working solution with normal choice field. my problem was that each user have their own CUSTOM choicefield options based on few conditions.
class SupportForm(BaseForm):
affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
grid_id = get_user_from_request(self.request)
for l in get_all_choices().filter(user=user_id):
admin = 'y' if l in self.core else 'n'
choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
self.affiliated_choices.append(choice)
super(SupportForm, self).__init__(*args, **kwargs)
self.fields['affiliated'].choices = self.affiliated_choice
From my Linux installation I did:
sudo ipython2 kernelspec install-self
And now my python 2 is back on the list.
Reference:
http://ipython.readthedocs.org/en/latest/install/kernel_install.html
UPDATE:
The method above is now deprecated and will be dropped in the future. The new method should be:
sudo ipython2 kernel install
Try
gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort
I had the same problem. Try to make a bat-file to start the Qt Creator. Add something like this to the bat-file:
call "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
"C:\QTsdk\qtcreator\bin\qtcreator"
Now I can compile and get:
jom 1.0.8 - empower your cores
11:10:08: The process "C:\QTsdk\qtcreator\bin\jom.exe" exited normally.
After my PC got completely reinstalled, I got the error described here. VS 2017 was reinstalled but "ASP.NET Web Pages 2" was not reinstalled. After reinstalling "ASP.NET Web Pages 2", the problem was solved.
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
If you need to do this on the backend you can use the following URL structure:
https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]
Sample PHP code using curl:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($curl);
curl_close ($curl);
$obj = json_decode($json);
See additional documentation for more details and expected json response.
The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.
bless
associates a reference with a package.
It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).
The effect bless
-ing has is that it allows you to apply special syntax to the blessed reference.
For example, if a blessed reference is stored in $obj
(associated by bless
with package "Class"), then $obj->foo(@args)
will call a subroutine foo
and pass as first argument the reference $obj
followed by the rest of the arguments (@args
). The subroutine should be defined in package "Class". If there is no subroutine foo
in package "Class", a list of other packages (taken form the array @ISA
in the package "Class") will be searched and the first subroutine foo
found will be called.
Obviously you know how this defeats the whole purpose of a SecureString, but I'll restate it anyway.
If you want a one-liner, try this: (.NET 4 and above only)
string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
Where securePassword is a SecureString.
You need a String object of some description to hold your array of concatenated chars, since the char
type will hold only a single character. e.g.,
StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
You can enable log4j internal logging by defining the 'log4j.debug' variable.
This is what worked for me (Intellij Idea 2018.1.2):
1) Navigate to: File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle
2) Gradle JVM: change to version 1.8
3) Re-run the gradle task
Another layer of indirection:
for i in $(eval echo {1..$END}); do
:
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
In the numpy README.txt file, it says
After installation, tests can be run with:
python -c 'import numpy; numpy.test()'
This should be a sufficient test for proper installation.
In NodeJS if you know the ID
, the looping through the array is very slow compared to object[ID]
.
const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;
//create data
for(var i=0;i<1000000;i++){
var getUnique = `${uniqueString()}`;
if(i===888555) seeking = getUnique;
arr.push(getUnique);
obj[getUnique] = true;
}
//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
if(arr[x]===seeking){
console.log('Array result:');
console.timeEnd('arrTimer');
break;
}
}
//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');
And the results:
Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms
Even if the seeking ID is the first one in the array/object:
Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms
You can specify the -o $@ option to your compile command to force the output of the compile command to take on the name of the target. For example, if you have:
...and you want to place the object files in:
...then you can compile cpp/class.cpp and cpp/driver.cpp separately into obj/class.o and obj/driver.o, and then link, with the following Makefile:
CC=c++
FLAGS=-std=gnu++11
INCS=-I./headers
SRC=./cpp
OBJ=./obj
EXE=./exe
${OBJ}/class.o: ${SRC}/class.cpp
${CC} ${FLAGS} ${INCS} -c $< -o $@
${OBJ}/driver.o: ${SRC}/driver.cpp ${SRC}/class.cpp
${CC} ${FLAGS} ${INCS} -c $< -o $@
driver: ${OBJ}/driver.o ${OBJ}/class.o
${CC} ${FLAGS} ${OBJ}/driver.o ${OBJ}/class.o -o ${EXE}/driver
I wanted to do the same thing as, but I wanted to do it in the one file.
So the logic would be:
I modified the answer by Bakuriu and came up with this:
from os import getpid
from sys import argv, exit
import psutil ## pip install psutil
myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
if process.pid != mypid:
for path in process.cmdline():
if myname in path:
print "process found"
process.terminate()
exit()
## your program starts here...
Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.
I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.
Your friend's PC is missing the runtime support DLLs for your program:
Use This one and you can get the
$previousDate = '2013-7-26 17:01:10';
$startdate = new DateTime($previousDate);
$endDate = new DateTime('now');
$interval = $endDate->diff($startdate);
echo$interval->format('%y years, %m months, %d days');
Refer this http://ca2.php.net/manual/en/dateinterval.format.php
White Box Testing equals Software Unit Test. The developer or a development level tester (e.g. another developer) ensures that the code he has written is working properly according to the detailed level requirements before integrating it in the system.
Black Box Testing equals Integration Testing. The tester ensures that the system works according to the requirements on a functional level.
Both test approaches are equally important in my opinion.
A thorough unit test will catch defects in the development stage and not after the software has been integrated into the system. A system level black box test will ensure all software modules behave correctly when integrated together. A unit test in the development stage would not catch these defects since modules are usually developed independent from each other.
if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true)
from the second version will return the globally scoped jQuery variables to those of the first version.
Sometimes it could be issue with older version (or not stable) of JQuery files
Solution use $.noConflict();
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
$('#myTable').DataTable();
});
// Code that uses other library's $ can follow here.
</script>
Using event.target.reset()
only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:
import React, { Component } from 'react'
class MyForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
placeholder="Enter name"
name="name"
value={name}
onChange={this.handleInputOnChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
ContactAdd.propTypes = {}
export default MyForm
I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'
This function is used to clear all the elements in the form including radio button, check-box, select, multiple select, password, text, textarea, file.
function clear_form_elements(class_name) {
jQuery("."+class_name).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'text':
case 'textarea':
case 'file':
case 'select-one':
case 'select-multiple':
case 'date':
case 'number':
case 'tel':
case 'email':
jQuery(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
break;
}
});
}
package com.app;
public class SiftNumberAndEvenNumber {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
int arr1[] = new int[arr.length];
int shiftAmount=3;
for(int i = 0; i < arr.length; i++){
int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
arr1[newLocation] = arr[i];
}
for(int i=0;i<arr1.length;i++) {
if(i==arr1.length-1) {
System.out.print(arr1[i]);
}else {
System.out.print(arr1[i]+",");
}
}
System.out.println();
for(int i=0;i<arr1.length;i++) {
if(arr1[i]%2==0) {
System.out.print(arr1[i]+" ");
}
}
}
}
I tried making changes to Intellij IDEA as below:
1.
File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler >> project bytecode version: 1.8 >> Per-module bytecode version: 1.8
2.
File >> Project Structure >> Project Settings >> Project >> SDK : 1.8, Project Language : 8 - Lambdas
File >> Project Structure >> Project Settings >> Modules >> abc : Language level: 8 - Lambdas
but nothing worked, it reverted the versions to java 1.5 as soon as I saved it.
However, adding below lines to root(project level) pom.xml worked me to resolve above issue: (both of the options worked for me)
Option 1:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Option 2:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
It means the path you input caused an error. In your LD_PRELOAD
command, modify the path like the error tips:
/usr/lib/liblunar-calendar-preload.so
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
Linux based Tomcat6 should have /etc/tomcat6/tomcat6.conf
# System-wide configuration file for tomcat6 services
# This will be sourced by tomcat6 and any secondary service
# Values will be overridden by service-specific configuration
# files in /etc/sysconfig
#
# Use this one to change default values for all services
# Change the service specific ones to affect only one service
# (see, for instance, /etc/sysconfig/tomcat6)
#
# Where your java installation lives
#JAVA_HOME="/usr/lib/jvm/java-1.5.0"
# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat6"
...
EventHandler
receives EventArgs
as a parameter. To resolve your problem, you can build your own MyEventArgs
.
public enum MyEvents
{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEvents MyEvent { get; set; }
}
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents ev)
{
if (EventTriggered != null)
{
EventTriggered(null, new MyEventArgs { MyEvent = ev });
}
}
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.
In other words, merging "main" into "current" in the following arrangement:
main
|
--feature
|
--current
I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.
SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.
The specific keys you have to set are below:
javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.
javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).
javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes,
/
, in place of backslashes,\
.If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts
javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by
javax.net.ssl.trustStore
.javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.
javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
This post is a little bit old, but here is another easy solution for getting data related to SMS
content provider in Android:
Use this lib: https://github.com/EverythingMe/easy-content-providers
Get all SMS
:
TelephonyProvider telephonyProvider = new TelephonyProvider(context);
List<Sms> smses = telephonyProvider.getSms(Filter.ALL).getList();
Each Sms has all fields, so you can get any info you need:
address, body, receivedDate, type(INBOX, SENT, DRAFT, ..), threadId, ...
Gel all MMS
:
List<Mms> mmses = telephonyProvider.getMms(Filter.ALL).getList();
Gel all Thread
:
List<Thread> threads = telephonyProvider.getThreads().getList();
Gel all Conversation
:
List<Conversation> conversations = telephonyProvider.getConversations().getList();
It works with List
or Cursor
and there is a sample app to see how it looks and works.
In fact, there is a support for all Android content providers like: Contacts, Call logs, Calendar, ... Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers
Hope it also helped :)
If you are interested ONLY on relative paths like: /dashboard
, /about
etc, See other answers.
If you want to open an absolute path like: https://www.google.com
to a new tab, you have to know that Vue Router is NOT meant to handle those.
However, they seems to consider that as a feature-request. #1280. But until they do that,
Here is a little trick you can do to handle external links with vue-router.
router.js
) and add this code:/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
const link = document.createElement('a')
link.href = url
link.target = newTab ? '_blank' : ''
if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
link.click()
}
Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab
this.$router.absUrl('https://www.google.com)
Remember that whenever we open another page to a new tab we MUST use noopener noreferrer
.
I solved my problem in AngularJS as follows:
var configPopOver = {
animation: 500,
container: 'body',
placement: function (context, source) {
var elBounding = source.getBoundingClientRect();
var pageWidth = angular.element('body')[0].clientWidth
var pageHeith = angular.element('body')[0].clientHeith
if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
return "left";
}
if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
return "right";
}
if (elBounding.top < 110){
return "bottom";
}
return "top";
},
html: true
};
This function do the position of Bootstrap popover float to the best position, based on element position.
hsb.s = max != 0 ? 255 * delta / max : 0;
?
is a ternary operator. It works like an if
in conjunction with the :
!=
means not equals
So, the long form of this line would be
if (max != 0) { //if max is not zero
hsb.s = 255 * delta / max;
} else {
hsb.s = 0;
}
require(caTools)
set.seed(101) #This is used to create same samples everytime
split1=sample.split(data$anycol,SplitRatio=2/3)
train=subset(data,split1==TRUE)
test=subset(data,split1==FALSE)
The sample.split()
function will add one extra column 'split1' to dataframe and 2/3 of the rows will have this value as TRUE and others as FALSE.Now the rows where split1 is TRUE will be copied into train and other rows will be copied to test dataframe.
You could use regular expressions to replace the '\n' or '\n\r' characters with '<br />'.
you have this:
var h1 = document.createElement("h1");
h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE...
so this text will display in a new line";
you can replace your characters like this:
h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');
check the javascript reference for the String and Regex objects:
Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0
Follow the official instruction doesn't work
Finally use the old way to figure it out.
ADD:
# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
#proj/settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'proj.middlewares.CsrfExemptSessionAuthentication',
),
}
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
Please use the below code and let me know
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(c, "root", "MyNewPass");
System.out.println("connection done");
PreparedStatement ps=con.prepareStatement(q);
System.out.println(q);
rs=ps.executeQuery();
System.out.println("done2");
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Failed");
}
myfolder/welcome.jsp
is the relative path of your jsp
page. So, change it as per your jsp
page path.
Let's break this down:
The error says
Cannot invoke an expression whose type lacks a call signature.
The code:
The problem is in this line public toggleBody: string;
&
it's relation to these lines:
...
return this.toggleBody(true);
...
return this.toggleBody(false);
Your saying toggleBody
is a string
but then your treating it like something that has a call signature
(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc. In JS just function tho.). You need to change the declaration to be public toggleBody: (arg: boolean) => boolean;
.
Extra Details:
"invoke" means your calling or applying a function.
"an expression" in Javascript is basically something that produces a value, so this.toggleBody()
counts as an expression.
"type" is declared on this line public toggleBody: string
"lacks a call signature" this is because your trying to call something this.toggleBody()
that doesn't have signature(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc.) that can be called. You said this.toggleBody
is something that acts like a string.
In other words the error is saying
Cannot call an expression (this.toggleBody) because it's type (:string) lacks a call signature (bc it has a string signature.)
To me, it sounds like you want to create a new attribute? Do you want
<option value="2" value2="somethingElse">...
To do this, you can do
$(your selector).attr('value2', 'the value');
And then to retrieve it, you can use
$(your selector).attr('value2')
It's not going to be valid code, but I guess it does the job.
Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.
Your Arduino library folder should look like this (on Windows):
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
My Documents\Arduino\libraries\ArduinoParty\examples
....
or like this (on Mac and Linux):
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
Documents/Arduino/libraries/ArduinoParty/examples
The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.
What would you use a ConcurrentList for?
The concept of a Random Access container in a threaded world isn't as useful as it may appear. The statement
if (i < MyConcurrentList.Count)
x = MyConcurrentList[i];
as a whole would still not be thread-safe.
Instead of creating a ConcurrentList, try to build solutions with what's there. The most common classes are the ConcurrentBag and especially the BlockingCollection.
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
$('elements-to-match').click(function(){
alert("The id is "+ this.id );
});
no need to wrap it in a jquery object
Try this code ...
Integer perc = 5;
BigDecimal spread = BigDecimal.ZERO;
BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
System.out.println(perc);
Result: 0.00000
Try this
if ( typeof is_json != "function" )
function is_json( _obj )
{
var _has_keys = 0 ;
for( var _pr in _obj )
{
if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
{
_has_keys = 1 ;
break ;
}
}
return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}
It works for the example below
var _a = { "name" : "me",
"surname" : "I",
"nickname" : {
"first" : "wow",
"second" : "super",
"morelevel" : {
"3level1" : 1,
"3level2" : 2,
"3level3" : 3
}
}
} ;
var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;
console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );
This is my second answer, but I believe the fastest? I'd like someone to check for me and reply in the comments.
My first attempt hit about 99k ops/sec and this go around is saying 390k ops/sec vs the other leading jsperf test of 140k (for me).
http://jsperf.com/merge-two-arrays-keeping-only-unique-values/26
I tried to minimize as much array interaction as possible this time around and it looked like I netted some performance.
function findMerge(a1, a2) {
var len1 = a1.length;
for (var x = 0; x < a2.length; x++) {
var found = false;
for (var y = 0; y < len1; y++) {
if (a2[x] === a1[y]) {
found = true;
break;
}
}
if(!found){
a1.push(a2.splice(x--, 1)[0]);
}
}
return a1;
}
Edit: I made some changes to my function, and the performance is drastic compared to others on the jsperf site.
For those who want a dumb down answer like me
Something like how to steps as 1, 2, 3
Here it is what I did
First create the HTML markup
<div class="thumb" data-image-src="images/img.jpg"></div>
Then before your ending body tag, add this script
I included the ending body on the code below as an example
So becareful when you copy
<script>
var list = document.getElementsByClassName('thumb');
for (var i = 0; i < list.length; i++) {
var src = list[i].getAttribute('data-image-src');
list[i].style.backgroundImage="url('" + src + "')";
}
</script>
</body>
In the terms of POS (Part of Speech) Tag,
If you have control over the request, you could set the content type to binary/octet-stream. This allows to query for parameters without consuming the input stream.
However, this might be specific to some application servers. I only tested tomcat, jetty seems to behave the same way according to https://stackoverflow.com/a/11434646/957103.
Python-3.x:
"aabc".count("a")
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
A correct way of iterating over the vector and printing its values is as follows:
#include<vector>
// declare the vector of type int
vector<int> v;
// insert elements in the vector
for (unsigned int i = 0; i < 5; ++i){
v.push_back(i);
}
// print those elements
for (auto it = v.begin(); it != v.end(); ++it){
std::cout << *it << std::endl;
}
But at least in the present case it is nicer to use a range-based for loop:
for (auto x: v) std::cout << x << "\n";
(You may also add &
after auto
to make x
a reference to the elements rather than a copy of them. It is then very similar to the above iterator-based approach, but easier to read and write.)
Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
It can be done by simply declaring one function which will handle all your swipe UISwipeGestureRecognizer directions. Here is my code:
let swipeGestureRight = UISwipeGestureRecognizer(target: self, action:#selector(ViewController.respondToSwipeGesture(_:)) )
swipeGestureRight.direction = UISwipeGestureRecognizerDirection.right
self.view .addGestureRecognizer(swipeGestureRight)
let swipeGestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeGestureLeft)
let swipeGestureUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureUp.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(swipeGestureUp)
let swipeGestureDown = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeGestureDown)
Here is the function which will hande the swipedirection functionality:
func respondToSwipeGesture(_ sender: UIGestureRecognizer) {
if let swipeGesture = sender as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("right swipe")
case UISwipeGestureRecognizerDirection.left:
print("leftSwipe")
case UISwipeGestureRecognizerDirection.up:
print("upSwipe")
case UISwipeGestureRecognizerDirection.down:
print("downSwipe")
default:
break
}
}
}
Use the Config class:
Config::set('site_settings', $site_settings);
Config::get('site_settings');
http://laravel.com/docs/4.2/configuration
Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.
Change your code to
<Limit GET POST>
deny from all
allow from 139.82.0.0/16
allow from 143.54.0.0/16
allow from 186.192.0.0/11
allow from 186.224.0.0/11
</Limit>
This way your htaccess will deny every except those that you explicitly allow with allow from..
A proxy within the allow range can easily be overwritten with an additional deny from..
rule.
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast
for the conversion.
Of the other casts:
dynamic_cast
only works for pointers or references to polymorphic class types;const_cast
can't change types, only const
or volatile
qualifiers;reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.static_cast
, const_cast
and reinterpret_cast
is needed to get the job done.And
has precedence over Or
, so, even if a <=> a1 Or a2
Where a And b
is not the same as
Where a1 Or a2 And b,
because that would be Executed as
Where a1 Or (a2 And b)
and what you want, to make them the same, is the following (using parentheses to override rules of precedence):
Where (a1 Or a2) And b
Here's an example to illustrate:
Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0
Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F
For those who like to consult references (in alphabetic order):
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
For those who are using Eclipse IDE.
After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,
You will need to tell Eclipse IDE about the following
Here is how you go about it.
To Add mysql.h
1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql
To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.
2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient
3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.
Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql
The Connector 6.7.x does not integrate the native data provider anymore. For "Visual Studio 2012" or less, you have to install "MySQL for Visual Studio". If you are using "Visual Studio 2013" there is no possibility to integrate MySQL for the "Entity Framework" yet. A solution should be available on 10/2013!
In case above-accepted answer did not work, try below solution. You can use it for port 8080 or for any other ports.
sudo lsof -i tcp:3000
Replace 3000 with whichever port you want. Run below command to kill that process.
sudo kill -9 PID
PID is process ID you want to kill.
Below is the output of commands on mac Terminal.
This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.
You can fork this and use it as a great starting point for your specific expectations:
Here are two screenshots I took for you... wide and thin:
If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
After that, if you need to, you can copy to an array :
String[] tokenArray = tokens.toArray(new String[0]);
This is from Bills answer.
Just to be really clear for others.
If you are copying ONE file from one place to another AND you want the full directory structure to be created, use the following command:
xcopy "C:\Data\Images\2013\08\12\85e4a707-2672-481b-92fb-67ecff20c96b.jpg" "C:\Target Data\\Images\2013\08\12\85e4a707-2672-481b-92fb-67ecff20c96b.jpg\"
Yes, put a backslash at the end of the file name and it will NOT ask you if it's a file or directory. Because there is only ONE file in the source, it will assume it's a file.
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
One liner:
<? if (have_posts()):while(have_posts()): the_post(); the_content(); endwhile; endif; ?>
If you really need to remove items then what about Except()?
You can remove based on a new list, or remove on-the-fly by nesting the Linq.
var authorsList = new List<Author>()
{
new Author{ Firstname = "Bob", Lastname = "Smith" },
new Author{ Firstname = "Fred", Lastname = "Jones" },
new Author{ Firstname = "Brian", Lastname = "Brains" },
new Author{ Firstname = "Billy", Lastname = "TheKid" }
};
var authors = authorsList.Where(a => a.Firstname == "Bob");
authorsList = authorsList.Except(authors).ToList();
authorsList = authorsList.Except(authorsList.Where(a=>a.Firstname=="Billy")).ToList();
When the workbook first opens, execute this code:
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
Then just have a macro in the workbook called "EventMacro" that will repeat it.
Public Sub EventMacro()
'... Execute your actions here'
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
End Sub
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username, @password, @email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("@id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("@username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("@password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("@email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this
gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or
gameObj.rigidbody2D.AddForce(Vector3.up * 1000);
See which combination and what values matches your requirement and use accordingly. Hope it helps
Here is my complete code how to open.
there are 2 options:
open using default browser (behavior is like opened inside the browser window)
open through default command options (behavior is like you use "RUN.EXE" command)
open through 'explorer' (behavior is like you wrote url inside your folder window url)
[optional suggestion] 4. use iexplore process location to open the required url
internal static bool TryOpenUrl(string p_url)
{
// try use default browser [registry: HKEY_CURRENT_USER\Software\Classes\http\shell\open\command]
try
{
string keyValue = Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Classes\http\shell\open\command", "", null) as string;
if (string.IsNullOrEmpty(keyValue) == false)
{
string browserPath = keyValue.Replace("%1", p_url);
System.Diagnostics.Process.Start(browserPath);
return true;
}
}
catch { }
// try open browser as default command
try
{
System.Diagnostics.Process.Start(p_url); //browserPath, argUrl);
return true;
}
catch { }
// try open through 'explorer.exe'
try
{
string browserPath = GetWindowsPath("explorer.exe");
string argUrl = "\"" + p_url + "\"";
System.Diagnostics.Process.Start(browserPath, argUrl);
return true;
}
catch { }
// return false, all failed
return false;
}
internal static string GetWindowsPath(string p_fileName)
{
string path = null;
string sysdir;
for (int i = 0; i < 3; i++)
{
try
{
if (i == 0)
{
path = Environment.GetEnvironmentVariable("SystemRoot");
}
else if (i == 1)
{
path = Environment.GetEnvironmentVariable("windir");
}
else if (i == 2)
{
sysdir = Environment.GetFolderPath(Environment.SpecialFolder.System);
path = System.IO.Directory.GetParent(sysdir).FullName;
}
if (path != null)
{
path = System.IO.Path.Combine(path, p_fileName);
if (System.IO.File.Exists(path) == true)
{
return path;
}
}
}
catch { }
}
// not found
return null;
}
Hope i helped.
You can use use findFragmentById
in FragmentManager
.
Since you are using the Support library (you are extending FragmentActivity) you can use:
getSupportFragmentManager().findFragmentById(R.id.pageview)
If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):
getFragmentManager().findFragmentById(R.id.pageview)
Please consider that using the support library is recommended even on Honeycomb+.
JDK 1.8 have some more enrich feature which doesn't support to many eclipse .
If you didn't find java compliance level as 1.8 in java compiler ,then go ahead and install the below eclipse 32bit or 64 bit depending on your system supports.
Try running one java program supports to java 8 like lambda expression as below and if no compilation error ,means your eclipse supports to java 1.8, something like this:
interface testI{
void show();
}
/*class A implements testI{
public void show(){
System.out.println("Hello");
}
}*/
public class LambdaDemo1 {
public static void main(String[] args) {
testI test ;
/*test= new A();
test.show();*/
test = () ->System.out.println("Hello,how are you?"); //lambda
test.show();
}
}
As of Spring 3.2, this is no longer an issue. Spring now supports Autowiring of the results of generic factory methods. See the section entitled "Generic Factory Methods" in this blog post: http://spring.io/blog/2012/11/07/spring-framework-3-2-rc1-new-testing-features/.
The key point is:
In Spring 3.2, generic return types for factory methods are now properly inferred, and autowiring by type for mocks should work as expected. As a result, custom work-arounds such as a MockitoFactoryBean, EasyMockFactoryBean, or Springockito are likely no longer necessary.
Which means this should work out of the box:
<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.Dao" />
</bean>
in my case just removing background-image
from nav-bar
item solved the problem
.navbar-default .navbar-nav > .active > a:focus {
.
.
.
background-image: none;
}
# views.py
def handler404(request, exception):
context = RequestContext(request)
err_code = 404
response = render_to_response('404.html', {"code":err_code}, context)
response.status_code = 404
return response
# <project_folder>.urls.py
handler404 = 'todo.views.handler404'
This works on django 2.0
Be sure to include your custom 404.html
inside the app templates folder.
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).
It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.
Here's your one-liner, without using any regular expressions, which can get expensive at times:
>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))
returns:
'123453120'
A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b
the value you get is 2^16 - 56 or 65536 - 56.
Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8
using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8
when casting to a char
, which translates to the positive number 65480
.
From the language specification:
5.1.4. Widening and Narrowing Primitive Conversion
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
To get the right point use char c = (char) (b & 0xFF)
which first converts the byte value of b
to the positive integer 200
by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8
becomes 0x000000C8
or the positive number 200
in decimals.
Above is a direct explanation of what happens during conversion between the byte
, int
and char
primitive types.
If you want to encode/decode characters from bytes, use Charset
, CharsetEncoder
, CharsetDecoder
or one of the convenience methods such as new String(byte[] bytes, Charset charset)
or String#toBytes(Charset charset)
. You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets
.
In IE11 Windows 7 this worked for me,
background-size: 100% 100%;
Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.
By defining the the full span as display:inline-block you might have a hard time displaying images.
Therefore I prefer to define a span like so:
span {
display:block;
width:150px;
word-wrap:break-word;
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
display:inline-block;
}
img{
display:block;
}
Primitive data types (such as byte) don't have methods in java, but you can directly do:
int i=rno[0];
I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.
Sure you could use $var=0; $var++
in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++
would probably throw an error.
I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.
Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.
EvalError --- Creates an instance representing an error that occurs regarding the global function eval().
InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
In Spring Web 4.3.6 I also see
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables)
That means you don't have to create an ugly map
So if you have this url
http://my-url/action?param1={param1}¶m2={param2}
You can either do
restTemplate.getForObject(url, Response.class, param1, param2)
or
restTemplate.getForObject(url, Response.class, param [])
It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:
<li><span class="foo">some text</span></li>
<li>some other text</li>
Then refer to it the usual way:
li > span.foo {...}
Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.
.divider{
position:absolute;
left:50%;
top:10%;
bottom:10%;
border-left:1px solid white;
}
You can use json decode then you get php array,and use that value as your own way
<?php
$leads = json_decode($leads, true);
dd($leads);
For Windows users
Use the original code as it's:
from selenium import webdriver
browser = webdriver.Firefox()
driver.get("https://www.google.com")
Then download the driver from: mozilla/geckodriver
Place it in a fixed path (permanently)... As an example, I put it in:
C:\Python35
Then go to the environment variables of the system. In the grid of "System variables" look for the Path variable and add:
;C:\Python35\geckodriver
geckodriver, not geckodriver.exe.
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
Try to clean and rebuild the project. I had the absolutely same question, this solved it.
Here's how you can debug CORS requests using curl.
Sending a regular CORS request using cUrl:
curl -H "Origin: http://example.com" --verbose \
https://www.googleapis.com/discovery/v1/apis?fields=
The -H "Origin: http://example.com"
flag is the third party domain making the request. Substitute in whatever your domain is.
The --verbose
flag prints out the entire response so you can see the request and response headers.
The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.
The response should include the Access-Control-Allow-Origin
header.
Sending a preflight request using cUrl:
curl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X OPTIONS --verbose \
https://www.googleapis.com/discovery/v1/apis?fields=
This looks similar to the regular CORS request with a few additions:
The -H
flags send additional preflight request headers to the server
The -X OPTIONS
flag indicates that this is an HTTP OPTIONS request.
If the preflight request is successful, the response should include the Access-Control-Allow-Origin
, Access-Control-Allow-Methods
, and Access-Control-Allow-Headers
response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.
You can also specify additional headers, such as User-Agent
, by using the -H
flag.
At least in version 2.2.3 that I'm using, you must use autoClose
instead of autoclose
. Letter case matters.
I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.
https://github.com/cmderdev/cmder
This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.
app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
return res.send(200);
});
GTK is built entirely on C and it uses many OOP concepts. I have read through the source code of GTK and it is pretty impressive, and definitely easier to read. The basic concept is that each "class" is simply a struct, and associated static functions. The static functions all accept the "instance" struct as a parameter, do whatever then need, and return results if necessary. For Example, you may have a function "GetPosition(CircleStruct obj)". The function would simply dig through the struct, extract the position numbers, probably build a new PositionStruct object, stick the x and y in the new PositionStruct, and return it. GTK even implements inheritance this way by embedding structs inside structs. pretty clever.
This worked for me:
gem install --local [path to downloaded gem file]
update_rubygems
gem --version
Below is my code.I also had the same error but the problem was that i gave my password wrong.The below code will work perfectly..try it
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Password Recovery ";
mail.Body += " <html>";
mail.Body += "<body>";
mail.Body += "<table>";
mail.Body += "<tr>";
mail.Body += "<td>User Name : </td><td> HAi </td>";
mail.Body += "</tr>";
mail.Body += "<tr>";
mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
mail.Body += "</tr>";
mail.Body += "</table>";
mail.Body += "</body>";
mail.Body += "</html>";
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("sendfrommailaddress.com", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
You can refer it in my blog
It is worth noting that sometimes you do want non-configurable "hard-coded" numbers in your code. There are a number of famous ones including 0x5F3759DF which is used in the optimized inverse square root algorithm.
In the rare cases where I find the need to use such Magic Numbers, I set them as a const in my code, and document why they are used, how they work, and where they came from.
There's now also Leaflet, which is built with mobile devices in mind.
There is a Quick Start Guide for leaflet. Besides basic features such as markers, with plugins it also supports routing using an external service.
For a simple map, it is IMHO easier and faster to set up than OpenLayers, yet fully configurable and tweakable for more complex uses.
After adding JTextArea into JScrollPane here:
scroll = new JScrollPane(display);
You don't need to add it again into other container like you do:
middlePanel.add(display);
Just remove that last line of code and it will work fine. Like this:
middlePanel=new JPanel();
middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));
// create the middle panel components
display = new JTextArea(16, 58);
display.setEditable(false); // set textArea non-editable
scroll = new JScrollPane(display);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Add Textarea in to middle panel
middlePanel.add(scroll);
JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:
new JScrollPane( myComponent )
or set view like this:
JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );
Additional:
Here is fully working example since you still did not get it working:
public static void main ( String[] args )
{
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );
// create the middle panel components
JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
//Add Textarea in to middle panel
middlePanel.add ( scroll );
// My code
JFrame frame = new JFrame ();
frame.add ( middlePanel );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
And here is what you get:
The Vue
event handling only allows for single function calls. If you need to do multiple ones you can either do a wrapper that includes both:
<div @click="handler"></div>
////////////////////////////
handler: function() { //Syntax assuming its in the 'methods' option of Vue instance
fn1('foo');
fn2('bar');
}
EDIT
Another option is to edit the first handler to have a callback and pass the second in.
<div @click="fn1('foo', fn2)"></div>
////////////////////////////////////
fn1: function(value, callback) {
console.log(value);
callback('bar');
},
fn2: function(value) {
console.log(value);
}
That's classic undefined behaviour that's been discussed here not two days ago -- search around the site for a bit. In a nutshell, you were lucky, but anything could have happened and your code is making invalid access to memory.
Run:
pip list
You should get a list of packages (including panda) and their versions, e.g.:
beautifulsoup4 (4.5.1)
cycler (0.10.0)
jdcal (1.3)
matplotlib (1.5.3)
numpy (1.11.1)
openpyxl (2.2.0b1)
pandas (0.18.1)
pip (8.1.2)
pyparsing (2.1.9)
python-dateutil (2.2)
python-nmap (0.6.1)
pytz (2016.6.1)
requests (2.11.1)
setuptools (20.10.1)
six (1.10.0)
SQLAlchemy (1.0.15)
xlrd (1.0.0)
Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789
Or you could try:
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
//But this will cause problems if your string value IsNullOrEmplty...
This is something of a generic solution:
<div class="outer">
<div class="inner">
Some content...
</div>
</div>
<style>
.outer {
overflow: hidden;
}
.inner {
margin-right: -16px;
overflow-y: scroll;
overflow-x: hidden;
}
</style>
The scroll bar is hidden by the parent div.
This requires you to use overflow:hidden in the parent div.
Ok, yup you use the timeout
command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window.
And here is the script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing
Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"
I have replaced the printf
calls with calls to warning
in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings()
or any of the other above mentioned methods.
suppressWarnings({ your code })
I encountered the same ImportError
. Somehow the setuptools
package had been deleted in my Python environment.
To fix the issue, run the setup script for setuptools
:
curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python
If you have any version of distribute
, or any setuptools
below 0.6, you will have to uninstall it first.*
See Installation Instructions for further details.
* If you already have a working distribute
, upgrading it to the "compatibility wrapper" that switches you over to setuptools
is easier. But if things are already broken, don't try that.
Translate composed UInt32 color Value
to CSS in .NET
I know the question applies to 3 input values (red
green
blue
). But there may be the situation where you already have a composed 32bit Value
. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06}
or #{0:X03}
would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.
Solve this by:
String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)
Do you mean like:
import groovy.json.*
class Me {
String name
}
def o = new Me( name: 'tim' )
println new JsonBuilder( o ).toPrettyString()
The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:
http://api.jquery.com/category/selectors/
However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
Not All Components.
the state
in component looks like the source of the waterfall of state of the whole APP.
So the change happens from where the setState called. The tree of renders
then get called from there. If you've used pure component, the render
will be skipped.
Let me explain to you by an example:
if you have Python list
>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]
and you want to remove duplicates from it.
>>> uniqueList = []
>>> for letter in randomList:
if letter not in uniqueList:
uniqueList.append(letter)
>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']
This is how you can remove duplicates from the list.
Haven't you heard about the Comparable
interface being implemented by String
? If no, try to use
"abcda".compareTo("abcza")
And it will output a good root for a solution to your problem.
open() will be called at the end of each of the fopen() family functions. open() is a system call and fopen() are provided by libraries as a wrapper functions for user easy of use
Add ?var1=data1&var2=data2
to the end of url to submit values to the page via GET:
using System.Net;
using System.IO;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.
Per the documentation from GitHub regarding GFM syntax highlighted code blocks
We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.
Rendered on GitHub, console
makes the lines after the console blue. bash
, sh
, or shell
don't seem to "highlight" much ...and you can use posh
for PowerShell or CMD.
This answer is based on the same 'theory' that is outlined well by this answer
I'm adding this answer as:
-- None of the other options fit the 'uniformity' need 'spot-on' (or not obviously-clearly so). (Noting to get the planet like distribution looking behavior particurally wanted in the original ask, you just reject from the finite list of the k uniformly created points at random (random wrt the index count in the k items back).)
--The closest other impl forced you to decide the 'N' by 'angular axis', vs. just 'one value of N' across both angular axis values ( which at low counts of N is very tricky to know what may, or may not matter (e.g. you want '5' points -- have fun ) )
--Furthermore, it's very hard to 'grok' how to differentiate between the other options without any imagery, so here's what this option looks like (below), and the ready-to-run implementation that goes with it.
with N at 20:
and then N at 80:
here's the ready-to-run python3 code, where the emulation is that same source: " http://web.archive.org/web/20120421191837/http://www.cgafaq.info/wiki/Evenly_distributed_points_on_sphere " found by others. ( The plotting I've included, that fires when run as 'main,' is taken from: http://www.scipy.org/Cookbook/Matplotlib/mplot3D )
from math import cos, sin, pi, sqrt
def GetPointsEquiAngularlyDistancedOnSphere(numberOfPoints=45):
""" each point you get will be of form 'x, y, z'; in cartesian coordinates
eg. the 'l2 distance' from the origion [0., 0., 0.] for each point will be 1.0
------------
converted from: http://web.archive.org/web/20120421191837/http://www.cgafaq.info/wiki/Evenly_distributed_points_on_sphere )
"""
dlong = pi*(3.0-sqrt(5.0)) # ~2.39996323
dz = 2.0/numberOfPoints
long = 0.0
z = 1.0 - dz/2.0
ptsOnSphere =[]
for k in range( 0, numberOfPoints):
r = sqrt(1.0-z*z)
ptNew = (cos(long)*r, sin(long)*r, z)
ptsOnSphere.append( ptNew )
z = z - dz
long = long + dlong
return ptsOnSphere
if __name__ == '__main__':
ptsOnSphere = GetPointsEquiAngularlyDistancedOnSphere( 80)
#toggle True/False to print them
if( True ):
for pt in ptsOnSphere: print( pt)
#toggle True/False to plot them
if(True):
from numpy import *
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
fig=p.figure()
ax = p3.Axes3D(fig)
x_s=[];y_s=[]; z_s=[]
for pt in ptsOnSphere:
x_s.append( pt[0]); y_s.append( pt[1]); z_s.append( pt[2])
ax.scatter3D( array( x_s), array( y_s), array( z_s) )
ax.set_xlabel('X'); ax.set_ylabel('Y'); ax.set_zlabel('Z')
p.show()
#end
tested at low counts (N in 2, 5, 7, 13, etc) and seems to work 'nice'
updateValue(data){
// retriving index from array
let indexValue = this.items.indexOf(data);
// changing specific element in array
this.items[indexValue].isShow = !this.items[indexValue].isShow;
}
This works
It will create a Executor with a single thread, that can get a lot of tasks; and will wait for the current one to end execution to begin with the next
In case of uncaugth error or exception the uncaughtExceptionHandler will catch it
public final class SingleThreadExecutorWithExceptions { public static ExecutorService newSingleThreadExecutorWithExceptions(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { ThreadFactory factory = (Runnable runnable) -> { final Thread newThread = new Thread(runnable, "SingleThreadExecutorWithExceptions"); newThread.setUncaughtExceptionHandler( (final Thread caugthThread,final Throwable throwable) -> { uncaughtExceptionHandler.uncaughtException(caugthThread, throwable); }); return newThread; }; return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), factory){ protected void afterExecute(Runnable runnable, Throwable throwable) { super.afterExecute(runnable, throwable); if (throwable == null && runnable instanceof Future) { try { Future future = (Future) runnable; if (future.isDone()) { future.get(); } } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // ignore/reset } } if (throwable != null) { uncaughtExceptionHandler.uncaughtException(Thread.currentThread(),throwable); } } }); } private static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } protected void finalize() { super.shutdown(); } } /** * A wrapper class that exposes only the ExecutorService methods * of an ExecutorService implementation. */ private static class DelegatedExecutorService extends AbstractExecutorService { private final ExecutorService e; DelegatedExecutorService(ExecutorService executor) { e = executor; } public void execute(Runnable command) { e.execute(command); } public void shutdown() { e.shutdown(); } public List shutdownNow() { return e.shutdownNow(); } public boolean isShutdown() { return e.isShutdown(); } public boolean isTerminated() { return e.isTerminated(); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return e.awaitTermination(timeout, unit); } public Future submit(Runnable task) { return e.submit(task); } public Future submit(Callable task) { return e.submit(task); } public Future submit(Runnable task, T result) { return e.submit(task, result); } public List> invokeAll(Collection> tasks) throws InterruptedException { return e.invokeAll(tasks); } public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { return e.invokeAll(tasks, timeout, unit); } public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { return e.invokeAny(tasks); } public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return e.invokeAny(tasks, timeout, unit); } } private SingleThreadExecutorWithExceptions() {} }
In ---- model:
Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
Change the class ----- extends Model
to class ----- extends Eloquent
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
I'm going to answer this myself.
I've determined that there is a difference. "git fetch --tags" might bring in all the tags, but it doesn't bring in any new commits!
Turns out one has to do this to be totally "up to date", i.e. replicated a "git pull" without the merge:
$ git fetch --tags
$ git fetch
This is a shame, because it's twice as slow. If only "git fetch" had an option to do what it normally does and bring in all the tags.
I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:
Make sure your DNS Resolver config file is writable:
sudo chmod o+r /etc/resolv.conf
Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:
sudo nano /etc/resolv.conf
Change the IP address in the file to: 8.8.8.8
Press CTRL
+
X
to save the file.
This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.
I suggest you read The Objective-C Programming Language. The part about messaging is specifically what you want here, but the whole thing will help you get started. After that, maybe try doing a few tutorials to get a feel for it before you jump into making your own apps.
The request body is available as byte stream by HttpServletRequest#getInputStream()
:
InputStream body = request.getInputStream();
// ...
Or as character stream by HttpServletRequest#getReader()
:
Reader body = request.getReader();
// ...
Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter()
and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.
You could use:
$('#btnForm').click(function(){
$.fancybox({
'content' : $("#divForm").html()
});
};
Turns out that Entity Framework will assume that any class that inherits from a POCO class that is mapped to a table on the database requires a Discriminator column, even if the derived class will not be saved to the DB.
The solution is quite simple and you just need to add [NotMapped]
as an attribute of the derived class.
Example:
class Person
{
public string Name { get; set; }
}
[NotMapped]
class PersonViewModel : Person
{
public bool UpdateProfile { get; set; }
}
Now, even if you map the Person class to the Person table on the database, a "Discriminator" column will not be created because the derived class has [NotMapped]
.
As an additional tip, you can use [NotMapped]
to properties you don't want to map to a field on the DB.
Add
android:configChanges="keyboardHidden|orientation|screenSize"
to your manifest.
The way I know is easy.
var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String
n
is the inner position in the array
This in SWIFT Language.
It might work in Objective C
To add more examples to Chuck's answer:
With parameter:
case a
when 1
puts "Single value"
when 2, 3
puts "One of comma-separated values"
when 4..6
puts "One of 4, 5, 6"
when 7...9
puts "One of 7, 8, but not 9"
else
puts "Any other thing"
end
Without parameter:
case
when b < 3
puts "Little than 3"
when b == 3
puts "Equal to 3"
when (1..10) === b
puts "Something in closed range of [1..10]"
end
Please, be aware of "How to write a switch statement in Ruby" that kikito warns about.
Arnon Rotem-Gal-Oz already answered this question a while ago, but I thought some may like this slightly more concise version.
LOGS = LOAD 'log';
LOG_COUNT = FOREACH (GROUP LOGS ALL) GENERATE COUNT(LOGS);
Leave your email.php code the same, but replace this JavaScript code:
var name = $("#form_name").val();
var email = $("#form_email").val();
var text = $("#msg_text").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
with this:
$.ajax({
type: "POST",
url: "email.php",
data: $(form).serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
So that your form input names match up.
You have to get back out of the Iframe with the following code:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
hope that helps
use trim() method of javascript after all angularjs is also a javascript framework and it is not necessary to put $ to apply trim()
for example
var x="hello world";
x=x.trim()
Improving another answer here
input[type=checkbox] {
cursor: pointer;
margin-right: 10px;
}
input[type=checkbox]:after {
content: " ";
background-color: lightgray;
display: inline-block;
position: relative;
top: -4px;
width: 24px;
height: 24px;
margin-right: 10px;
}
input[type=checkbox]:checked:after {
content: "\00a0\2714";
}
I'd like to add a new version of flatten case (this is what i needed :)) which, according to my probes with the above jsFiddler, is slightly faster then the currently selected one. Moreover, me personally see this snippet a bit more readable, which is of course important for multi-developer projects.
function flattenObject(graph) {
let result = {},
item,
key;
function recurr(graph, path) {
if (Array.isArray(graph)) {
graph.forEach(function (itm, idx) {
key = path + '[' + idx + ']';
if (itm && typeof itm === 'object') {
recurr(itm, key);
} else {
result[key] = itm;
}
});
} else {
Reflect.ownKeys(graph).forEach(function (p) {
key = path + '.' + p;
item = graph[p];
if (item && typeof item === 'object') {
recurr(item, key);
} else {
result[key] = item;
}
});
}
}
recurr(graph, '');
return result;
}
$( "#sortable" ).sortable({
change: function(event, ui) {
var pos = ui.helper.index() < ui.placeholder.index()
? { start: ui.helper.index(), end: ui.placeholder.index() }
: { start: ui.placeholder.index(), end: ui.helper.index() }
$(this)
.children().removeClass( 'highlight' )
.not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
},
stop: function(event, ui) {
$(this).children().removeClass( 'highlight' );
}
});
An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper
, and the element of current position is ui.placeholder
, we can take the elements between those two indexes and highlight them. Also, we can use this
inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.
Yes, a UITextView is what you're looking for. You'll have to deal with some things differently (like the return key) but you can add text to it, and it will allow you to scroll up and down if there's too much text inside.
This link has info about making a screen to enter data:
Apparently, some versions of the shell can also emit this message when the final line of your script lacks a newline.
Consider this approach, you don't need a for loop:
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(ExitingSqlTableName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If you want to check for authenticated users in your template then:
{% if user.is_authenticated %}
<p>Authenticated user</p>
{% else %}
<!-- Do something which you want to do with unauthenticated user -->
{% endif %}
There is nothing wrong with what you have. Double-nested for loops should be easily digested by anyone reading your code.
That said, the following formulation is denser and more idiomatic java. I'd suggest poking around some of the static utility classes like Arrays and Collections sooner than later. Tons of boilerplate can be shaved off by their efficient use.
for (int[] row : array)
{
Arrays.fill(row, 0);
System.out.println(Arrays.toString(row));
}
You are trying to assign a value to a function, which is not possible in C. Try the comparison operator instead:
if (strcmp("hello", "hello") == 0)
Change the CorsMapping from registry.addMapping("/*")
to registry.addMapping("/**")
in addCorsMappings
method.
Check out this Spring CORS Documentation .
From the documentation -
Enabling CORS for the whole application is as simple as:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}
Controller method CORS configuration
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
}
To enable CORS for the whole controller -
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
You can even use both controller-level and method-level CORS configurations; Spring will then combine attributes from both annotations to create merged CORS configuration.
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin("http://domain2.com")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
You cannot get the exact code, but you can get a decompiled version of it.
The most popular (and best) tool is Reflector, but there are also other .Net decompilers (such as Dis#). You can also decompile the IL using ILDASM, which comes bundled with the .Net Framework SDK Tools.
Use the btoa()
function to encode:
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
To decode, you can use the atob()
function:
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
matcher.find();
System.out.println(matcher.group(1));
LATERAL
join?The feature was introduced with PostgreSQL 9.3.
Quoting the manual:
Subqueries appearing in
FROM
can be preceded by the key wordLATERAL
. This allows them to reference columns provided by precedingFROM
items. (WithoutLATERAL
, each subquery is evaluated independently and so cannot cross-reference any otherFROM
item.)Table functions appearing in
FROM
can also be preceded by the key wordLATERAL
, but for functions the key word is optional; the function's arguments can contain references to columns provided by precedingFROM
items in any case.
Basic code examples are given there.
A LATERAL
join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL
join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:
For returning more than one column, a LATERAL
join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true
:
There are things that a LATERAL
join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM
clause. Like unnest()
with multiple parameters in Postgres 9.4 or later. The manual:
This is only allowed in the
FROM
clause;
So this works, but cannot (easily) be replaced with a subquery:
CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2); -- implicit LATERAL
The comma (,
) in the FROM
clause is short notation for CROSS JOIN
.
LATERAL
is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] )
:
SELECT
listYou can also use set-returning functions like unnest()
in the SELECT
list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT
list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:
Building on above example:
SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM tbl;
Comparison:
dbfiddle for pg 9.6 here
dbfiddle for pg 10 here
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofNATURAL
,ON
join_condition, orUSING
(join_column [, ...]). See below for the meaning.
ForCROSS JOIN
, none of these clauses can appear.
So these two queries are valid (even if not particularly useful):
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;
SELECT *
FROM tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
While this one is not:
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
That's why Andomar's code example is correct (the CROSS JOIN
does not require a join condition) and Attila's is was not.
Try this:
=FORMAT(Cdate(today), "dd-MM-yyyy")
or
=FORMAT(Cdate(today), "MM-dd-yyyy")
or
=FORMAT(Cdate(today), "yyyy-MM-dd")
or
=Report Generation Date: " & FORMAT(Cdate(today), "dd-MM-yyyy")
You should format the date in the same format your customer (internal or external) wants to see the date. For example In one of my servers it is running on American date format (MM-dd-yyyy) and on my reports I must ensure the dates displayed are European (yyyy-MM-dd).
.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE
The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields: