As MRA said, you shouldn't try to dodge a 429 Too Many Requests
but instead handle it accordingly. You have several options depending on your use-case:
1) Sleep your process. The server usually includes a Retry-after
header in the response with the number of seconds you are supposed to wait before retrying. Keep in mind that sleeping a process might cause problems, e.g. in a task queue, where you should instead retry the task at a later time to free up the worker for other things.
2) Exponential backoff. If the server does not tell you how long to wait, you can retry your request using increasing pauses in between. The popular task queue Celery has this feature built right-in.
3) Token bucket. This technique is useful if you know in advance how many requests you are able to make in a given time. Each time you access the API you first fetch a token from the bucket. The bucket is refilled at a constant rate. If the bucket is empty, you know you'll have to wait before hitting the API again. Token buckets are usually implemented on the other end (the API) but you can also use them as a proxy to avoid ever getting a 429 Too Many Requests
. Celery's rate_limit feature uses a token bucket algorithm.
Here is an example of a Python/Celery app using exponential backoff and rate-limiting/token bucket:
class TooManyRequests(Exception):
"""Too many requests"""
@task(
rate_limit='10/s',
autoretry_for=(ConnectTimeout, TooManyRequests,),
retry_backoff=True)
def api(*args, **kwargs):
r = requests.get('placeholder-external-api')
if r.status_code == 429:
raise TooManyRequests()
This is what I expected to see when I came to this question:
#!/usr/bin/env python
import pandas as pd
df = pd.DataFrame([(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, 1, 2),
(3, 4, 5, 6)],
columns=list('abcd'),
index=['India', 'France', 'England', 'Germany'])
print(df)
gives
a b c d
India 1 2 3 4
France 5 6 7 8
England 9 0 1 2
Germany 3 4 5 6
I found it pretty easy like this
using System;
using System.Data;
using System.IO;
using Excel;
public DataTable ExcelToDataTableUsingExcelDataReader(string storePath)
{
FileStream stream = File.Open(storePath, FileMode.Open, FileAccess.Read);
string fileExtension = Path.GetExtension(storePath);
IExcelDataReader excelReader = null;
if (fileExtension == ".xls")
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (fileExtension == ".xlsx")
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
var test = result.Tables[0];
return result.Tables[0];
}
Note: you need to install SharpZipLib package for this
Install-Package SharpZipLib
neat and clean! ;)
def awgn(sinal):
regsnr=54
sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
sigpower=sigpower/len(sinal)
noisepower=sigpower/(math.pow(10,regsnr/10))
noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
return noise
I have tried directlabels
package for putting text labels. In the case of scatter plots it's not still perfect, but much better than manually adjusting the positions, specially in the cases that you are preparing the draft plots and not the final one - so you need to change and make plot again and again -.
I don't know if you ever found an answer to this but I DIDN'T need MAMP PRO to do this. Simply goto the correct path by following what others have said. It's something like...
MAMP-> bin-> php-> php(your php version)-> conf-> php.ini
The key here is where you're editing the file. I was making the mistake of editing the commented part of the ini file. You actually have to scroll down to LINE #472 where it says "display_errors = Off and change it to On. Hope this helps any
you can use this function to download file from base64.
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}
This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.
i hope this will help of you thanks
Try zoom
property
<img src="..." style="zoom: 0.5" />
Edit: Apparently, FireFox doesn't support zoom
property. You should use;
-moz-transform: scale(0.5);
for FireFox.
If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):
# 1) Get back to the main body page
driver.switch_to.default_content()
# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js:
# 3) Read the jquery from a file
jquery = jquery_js.read()
# 4) Load jquery lib
driver.execute_script(jquery)
# 5) Execute your command
driver.execute_script('$("#myId").click()')
Here's an example of an all-xaml solution. It binds to an "IsWorking" boolean in the viewmodel to show the control and start the animation.
<UserControl x:Class="MainApp.Views.SpinnerView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
</UserControl.Resources>
<StackPanel Orientation="Horizontal" Margin="5"
Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisConverter}}">
<Label>Wait...</Label>
<Ellipse x:Name="spinnerEllipse"
Width="20" Height="20">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="1,1" EndPoint="0,0" >
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="CornflowerBlue" Offset="1"/>
</LinearGradientBrush>
</Ellipse.Fill>
<Ellipse.RenderTransform>
<RotateTransform x:Name="SpinnerRotate" CenterX="10" CenterY="10"/>
</Ellipse.RenderTransform>
<Ellipse.Style>
<Style TargetType="Ellipse">
<Style.Triggers>
<DataTrigger Binding="{Binding IsWorking}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="SpinStoryboard">
<Storyboard TargetProperty="RenderTransform.Angle" >
<DoubleAnimation
From="0" To="360" Duration="0:0:01"
RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="SpinStoryboard"></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
</StackPanel>
</UserControl>
EDIT: The below answer no longer works see here
Google Chrome cache file format description.
Cache files list, see URLs (copy and paste to your browser address bar):
chrome://cache/
chrome://view-http-cache/
Cache folder in Linux: $~/.cache/google-chrome/Default/Cache
Let's determine in file GZIP encoding:
$ head f84358af102b1064_0 | hexdump -C | grep --before-context=100 --after-context=5 "1f 8b 08"
Extract Chrome cache file by one line on PHP (without header, CRC32 and ISIZE block):
$ php -r "echo gzinflate(substr(strchr(file_get_contents('f84358af102b1064_0'), \"\x1f\x8b\x08\"), 10,
-8));"
Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:
if (row > 0) col = test[0].length;
Here's some background on the mechanism you should use, called Package Configurations: Understanding Integration Services Package Configurations. The article describes 5 types of configurations:
Here's a walkthrough of setting up a configuration on a Connection Manager: SQL Server Integration Services SSIS Package Configuration - I do realize this is using an environment variable for the connection string (not a great idea), but the basics are identical to using an XML file. The only step(s) you have to change in that walkthrough are the configuration type, and then a path.
The accepted (and correct) answer says that "you can include this [Constants.h] file... in the pre-compiled header for the project."
As a novice, I had difficulty doing this without further explanation -- here's how: In your YourAppNameHere-Prefix.pch file (this is the default name for the precompiled header in Xcode), import your Constants.h inside the #ifdef __OBJC__
block.
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "Constants.h"
#endif
Also note that the Constants.h and Constants.m files should contain absolutely nothing else in them except what is described in the accepted answer. (No interface or implementation).
I use Eclipse and a plain vanilla PyDev. There isn't any specific Django functionality. The best I came up with was setting up a run profile to run the development web server.
If you add the web tools project (WTP), you'll get syntax highlighting in your templates, but nothing that relates to the specific template language. PyDev is a decent plugin, and if you are already familiar with Eclipse and use it for other projects it is a good way to go.
I recall NetBeans starting to get Python support, but I have no idea where that is right now. Lots of people rave about NetBeans 6, but in the Java world Eclipse still reigns as the king of the OSS IDEs.
None of the answers above are complete. Although Leo Theobald answer looks nearest answer.
The basic point is how hibernate is dealing with states of entities and how it handles them when there is a state change. Everything must be seen with respect to flushes and commits as well, which everyone seems to have ignored completely.
NEVER USE THE SAVE METHOD of HIBERNATE. FORGET THAT IT EVEN EXISTS IN HIBERNATE!
Persist
As everyone explained, Persist basically transitions an entity from "Transient" state to "Managed" State. At this point, a slush or a commit can create an insert statement. But the entity will still remains in "Managed" state. That doesn't change with flush.
At this point, if you "Persist" again there will be no change. And there wont be any more saves if we try to persist a persisted entity.
The fun begins when we try to evict the entity.
An evict is a special function of Hibernate which will transition the entity from "Managed" to "Detached". We cannot call a persist on a detached entity. If we do that, then Hibernate raises an exception and entire transaction gets rolled back on commit.
Merge vs Update
These are 2 interesting functions doing different stuff when dealt in different ways. Both of them are trying to transition the entity from "Detached" state to "Managed" state. But doing it differently.
Understand a fact that Detached means kind of an "offline" state. and managed means "Online" state.
Observe the code below:
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
ses1.merge(entity);
ses1.delete(entity);
tx1.commit();
When you do this? What do you think will happen? If you said this will raise exception, then you are correct. This will raise exception because, merge has worked on entity object, which is detached state. But it doesn't alter the state of object.
Behind the scene, merge will raise a select query and basically returns a copy of entity which is in attached state. Observe the code below:
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
HibEntity copied = (HibEntity)ses1.merge(entity);
ses1.delete(copied);
tx1.commit();
The above sample works because merge has brought a new entity into the context which is in persisted state.
When applied with Update the same works fine because update doesn't actually bring a copy of entity like merge.
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
ses1.update(entity);
ses1.delete(entity);
tx1.commit();
At the same time in debug trace we can see that Update hasn't raised SQL query of select like merge.
delete
In the above example I used delete without talking about delete. Delete will basically transition the entity from managed state to "removed" state. And when flushed or commited will issue a delete command to store.
However it is possible to bring the entity back to "managed" state from "removed" state using the persist method.
Hope the above explanation clarified any doubts.
You don't mention whether you are using Windows or UNIX.
On UNIX systems, KDevelop is good but I use KDbg because it is easy to use and will also work with apps not developed in KDevelop.
Eclipse is good on both platforms.
On Windows, there is a great package called Wascana Desktop Developer which is Eclipse CDT and MinGW all packaged up and preconfigured nicely for the minimum of pain. Its the best thing I've found for developing GNU code on Windows.
I have used all these debuggers and none of them are as good as MS Dev Studio. Eclipse/Wascana is probably the closest but it does have limitations like you cannot step into DLLs and it doesn't do as good a job at examining variables.
I think you can use loc
if you need update two columns to same value:
df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
stream feat another_feat
a 1 some_value some_value
b 2 aaaa aaaa
c 2 aaaa aaaa
d 3 some_value some_value
If you need update separate, one option is use:
df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
stream feat another_feat
a 1 some_value some_value
b 2 10 some_value
c 2 10 some_value
d 3 some_value some_value
Another common option is use numpy.where
:
df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
stream feat another_feat
a 1 20 some_value
b 2 10 some_value
c 2 10 some_value
d 3 20 some_value
EDIT: If you need divide all columns without stream
where condition is True
, use:
print df1
stream feat another_feat
a 1 4 5
b 2 4 5
c 2 2 9
d 3 1 7
#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']
df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
stream feat another_feat
a 1 4.0 5.0
b 2 2.0 2.5
c 2 1.0 4.5
d 3 1.0 7.0
If working with multiple conditions is possible use multiple numpy.where
or numpy.select
:
df0 = pd.DataFrame({'Col':[5,0,-6]})
df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing',
np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))
df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
['Increasing', 'Decreasing'],
default='No Change')
print (df0)
Col New Col1 New Col2
0 5 Increasing Increasing
1 0 No Change No Change
2 -6 Decreasing Decreasing
I'm using OS X (Yosemite) and this error happened to me when I upgraded from Mavericks to Yosemite. It was solved by using this command
sudo /usr/local/mysql/support-files/mysql.server start
Use Array.CreateInstance
to create an array dynamically.
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
InputProperty[] ip = Array.CreateInstance(typeof(InputProperty), nvPairs.Count()) as InputProperty[];
int i;
for (i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
update.Items = ip;
return update;
}
My exact problem was (Fatal error in launcher: Unable to create process using '"') on windows 10. So I navigated to the "C:\Python33\Lib\site-packages" and deleted django folder and pip folders then reinstalled django using pip and my problem was solved.
I can do it using below two methods, using function
def lensort(x):
list1 = []
for i in x:
list1.append([len(i),i])
return sorted(list1)
lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])
In one Liner using Lambda, as below, a already answered above.
lista = ['a', 'bb', 'ccc', 'dddd']
lista.sort(key = lambda x:len(x))
print(lista)
I can't comment yet, so I'll post a new answer
Accepted answer is ok-ish, but it wasn't stopping submit on numpad enter. At least in current version of Chrome. I had to alter the keycode condition to this, then it works.
if(event.keyCode == 13 || event.keyCode == 169) {...}
The line #include "stdafx.h"
must be the first line at the top of each source file, before any other header files are included.
If what you've shown is the entire .cxx
file, then you did forget to include stdafx.h
in that file.
This can also be done as follows for a list of dataframes df_list
:
df = df_list[0]
for df_ in df_list[1:]:
df = df.merge(df_, on='join_col_name')
or if the dataframes are in a generator object (e.g. to reduce memory consumption):
df = next(df_list)
for df_ in df_list:
df = df.merge(df_, on='join_col_name')
Ok, this might be a little after the fact, but .promise() should also achieve what you're after.
An example from a project i'm working on:
$( '.panel' )
.fadeOut( 'slow')
.promise()
.done( function() {
$( '#' + target_panel ).fadeIn( 'slow', function() {});
});
:)
SELECT Min(sal)
FROM (SELECT DISTINCT sal
FROM emp
WHERE sal IS NOT NULL
ORDER BY sal DESC)
WHERE rownum <= n;
The accepted answer from Paul is great. I've made a small extension to this which is very useful if you have an multidimensional array like this (which is quite common):
Array
(
[0] => Array
(
[a] => "a"
[b] => "b"
)
[1] => Array
(
[a] => "a2"
[b] => "b2"
)
[2] => Array
(
[a] => "a3"
[b] => "b3"
)
[3] => Array
(
[a] => "a4"
[b] => "b4"
)
[4] => Array
(
[a] => "a5"
[b] => "b5"
)
)
So I just took Paul's function from above:
/**
* Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
* Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
*/
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields as $field ) {
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}
And added this:
function a2c($array, $glue = "\n")
{
$ret = [];
foreach ($array as $item) {
$ret[] = arrayToCsv($item);
}
return implode($glue, $ret);
}
So you can just call:
$csv = a2c($array);
If you want a special line ending you can use the optional parameter "glue" for this.
A really simple implementation is:
out = "".join(c for c in asking if c not in ('!','.',':'))
and keep adding any other types of punctuation.
A more efficient way would be
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)
Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python
If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt
try
{
File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
//File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, fileName);
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n\n");
writer.flush();
writer.close();
Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
try
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
chars += line.length();
words += new StringTokenizer(line, " ,").countTokens();
}
You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:
public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
Load += new EventHandler(ProgramViwer_Load);
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
formPanel.Controls.Add(wel);
}
}
All Java objects have a toString()
method, which is invoked when you try to print the object.
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object
class (the superclass of all Java objects). The Object.toString()
method returns a fairly ugly looking string, composed of the name of the class, an @
symbol and the hashcode of the object in hexadecimal. The code for this looks like:
// Code of Object.toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
A result such as com.foo.MyType@2f92e0f4
can therefore be explained as:
com.foo.MyType
- the name of the class, i.e. the class is MyType
in the package com.foo
.@
- joins the string together2f92e0f4
the hashcode of the object.The name of array classes look a little different, which is explained well in the Javadocs for Class.getName()
. For instance, [Ljava.lang.String
means:
[
- an single-dimensional array (as opposed to [[
or [[[
etc.)L
- the array contains a class or interfacejava.lang.String
- the type of objects in the arrayTo print something different when you call System.out.println(myObject)
, you must override the toString()
method in your own class. Here's a simple example:
public class Person {
private String name;
// constructors and other methods omitted
@Override
public String toString() {
return name;
}
}
Now if we print a Person
, we see their name rather than com.foo.Person@12345678
.
Bear in mind that toString()
is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString()
for our Person
class might be:
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + name + "]";
}
Which would print, e.g., Person[name=Henry]
. That's a really useful piece of data for debugging/testing.
If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}
.
Many IDEs offer support for auto-generating a toString()
method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.
Several popular Java libraries offer this feature as well. Some examples include:
@ToString
annotation from Project Lombok
So you've created a nice toString()
for your class. What happens if that class is placed into an array or a collection?
If you have an array of objects, you can call Arrays.toString()
to produce a simple representation of the contents of the array. For instance, consider this array of Person
objects:
Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));
// Prints: [Fred, Mike]
Note: this is a call to a static method called toString()
in the Arrays class, which is different to what we've been discussing above.
If you have a multi-dimensional array, you can use Arrays.deepToString()
to achieve the same sort of output.
Most collections will produce a pretty output based on calling .toString()
on every element.
List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));
System.out.println(people);
// Prints [Alice, Bob]
So you just need to ensure your list elements define a nice toString()
as discussed above.
You can create table variable instead of tamp table in procedure A and execute procedure B and insert into temp table by below query.
DECLARE @T TABLE
(
TABLE DEFINITION
)
.
.
.
INSERT INTO @T
EXEC B @MYDATE
and you continue operation.
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
By dragging and dropping the dll onto 'regasm' you can register it. You can open two 'Window Explorer' windows. One will contain the dll you wish to register. The 2nd window will be the location of the 'regasm' application. Scroll down in both windows so that you have a view of both the dll and 'regasm'. It helps to reduce the size of the two windows so they are side-by-side. Be sure to drag the dll over the 'regasm' that is labeled 'application'. There are several 'regasm' files but you only want the application.
In .Net 2.0 I`m pretty sure about this solution:
public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
List<T> uniques = new List<T>();
foreach (T item in source)
{
if (!uniques.Contains(item)) uniques.Add(item);
}
return uniques;
}
Echo inside an HTML element with class
and style the element:
echo "<span class='name'>" . $ip['cityName'] . "</span>";
It seems that lots of answers already complete, I'd like to add one more example code for showing how the lea and move instruction work differently when they have the same expression format.
To make a long story short, lea instruction and mov instructions both can be used with the parentheses enclosing the src operand of the instructions. When they are enclosed with the (), the expression in the () is calculated in the same way; however, two instructions will interpret the calculated value in the src operand in a different way.
Whether the expression is used with the lea or mov, the src value is calculated as below.
D ( Rb, Ri, S ) => (Reg[Rb]+S*Reg[Ri]+ D)
However, when it is used with the mov instruction, it tries to access the value pointed to by the address generated by the above expression and store it to the destination.
In contrast of it, when the lea instruction is executed with the above expression, it loads the generated value as it is to the destination.
The below code executes the lea instruction and mov instruction with the same parameter. However, to catch the difference, I added a user-level signal handler to catch the segmentation fault caused by accessing a wrong address as a result of mov instruction.
Example code
#define _GNU_SOURCE 1 /* To pick up REG_RIP */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <signal.h>
uint32_t
register_handler (uint32_t event, void (*handler)(int, siginfo_t*, void*))
{
uint32_t ret = 0;
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_sigaction = handler;
act.sa_flags = SA_SIGINFO;
ret = sigaction(event, &act, NULL);
return ret;
}
void
segfault_handler (int signum, siginfo_t *info, void *priv)
{
ucontext_t *context = (ucontext_t *)(priv);
uint64_t rip = (uint64_t)(context->uc_mcontext.gregs[REG_RIP]);
uint64_t faulty_addr = (uint64_t)(info->si_addr);
printf("inst at 0x%lx tries to access memory at %ld, but failed\n",
rip,faulty_addr);
exit(1);
}
int
main(void)
{
int result_of_lea = 0;
register_handler(SIGSEGV, segfault_handler);
//initialize registers %eax = 1, %ebx = 2
// the compiler will emit something like
// mov $1, %eax
// mov $2, %ebx
// because of the input operands
asm("lea 4(%%rbx, %%rax, 8), %%edx \t\n"
:"=d" (result_of_lea) // output in EDX
: "a"(1), "b"(2) // inputs in EAX and EBX
: // no clobbers
);
//lea 4(rbx, rax, 8),%edx == lea (rbx + 8*rax + 4),%edx == lea(14),%edx
printf("Result of lea instruction: %d\n", result_of_lea);
asm volatile ("mov 4(%%rbx, %%rax, 8), %%edx"
:
: "a"(1), "b"(2)
: "edx" // if it didn't segfault, it would write EDX
);
}
Execution result
Result of lea instruction: 14
inst at 0x4007b5 tries to access memory at 14, but failed
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
You're trying to assign the return value of clients.get(clients.size())
to the string hey
, but the object returned is a ClientThread
, not a string. As Andre mentioned, you need to use the proper index as well.
As far as your second error is concerned, there is no static method remove()
on the type ClientThread
. Really, you likely wanted the remove method of your List
instance, clients
.
You can remove the last item from the list, if there is one, as follows. Since remove also returns the object that was removed, you can capture the return and use it to print out the name:
int size = clients.size();
if (size > 0) {
ClientThread client = clients.remove(size - 1);
System.out.println(client + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
}
I had to rm -rf ./vendor
then run bundle install
again.
try something using a for loop
for i in `egrep -lR "YOURSEARCH" .` ; do echo $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done
not pretty, but should do.
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
OPTIONS
method returns info about API (methods/content type)
HEAD
method returns info about resource (version/length/type)
Server response
OPTIONS
HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0
HEAD
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
OPTIONS
Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?HEAD
Checking whether a resource has changed. This is useful when maintaining a cached version of a resourceHEAD
Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrievalHEAD, OPTIONS
Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application
Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.
For List :
List<Integer> intList
= stringList.stream().map(Integer::valueOf).collect(Collectors.toList());
For Array :
int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();
For C# .Net to find and replace any guid looking string from the given text,
Use this RegEx:
[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?
Example C# code:
var result = Regex.Replace(
source,
@"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?",
@"${ __UUID}",
RegexOptions.IgnoreCase
);
Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.
"aa761232bd4211cfaacd00aa0057b243"
"AA761232-BD42-11CF-AACD-00AA0057B243"
"{AA761232-BD42-11CF-AACD-00AA0057B243}"
"(AA761232-BD42-11CF-AACD-00AA0057B243)"
if it is coming from server as object you can do
this.service.subscribe(data:any) keep any type on data it will solve the issue
What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.
When you add a "static" keyword to a method, it means that underlying implementation gives the same result for any instance of the class. Needless to say, result varies with change in the value of parameters
Starting Bootstrap 3 (edit: still the same in Bootstrap 4) there are 2 instances in which you can fire up events, being:
$('#myModal').on('hide.bs.modal', function () {
console.log('Fired at start of hide event!');
});
$('#myModal').on('hidden.bs.modal', function () {
console.log('Fired when hide event has finished!');
});
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
I would just chain the DataFrame.reset_index() and DataFrame.values functions to get the Numpy representation of the dataframe, including the index:
In [8]: df
Out[8]:
A B C
0 -0.982726 0.150726 0.691625
1 0.617297 -0.471879 0.505547
2 0.417123 -1.356803 -1.013499
3 -0.166363 -0.957758 1.178659
4 -0.164103 0.074516 -0.674325
5 -0.340169 -0.293698 1.231791
6 -1.062825 0.556273 1.508058
7 0.959610 0.247539 0.091333
[8 rows x 3 columns]
In [9]: df.reset_index().values
Out[9]:
array([[ 0. , -0.98272574, 0.150726 , 0.69162512],
[ 1. , 0.61729734, -0.47187926, 0.50554728],
[ 2. , 0.4171228 , -1.35680324, -1.01349922],
[ 3. , -0.16636303, -0.95775849, 1.17865945],
[ 4. , -0.16410334, 0.0745164 , -0.67432474],
[ 5. , -0.34016865, -0.29369841, 1.23179064],
[ 6. , -1.06282542, 0.55627285, 1.50805754],
[ 7. , 0.95961001, 0.24753911, 0.09133339]])
To get the dtypes we'd need to transform this ndarray into a structured array using view:
In [10]: df.reset_index().values.ravel().view(dtype=[('index', int), ('A', float), ('B', float), ('C', float)])
Out[10]:
array([( 0, -0.98272574, 0.150726 , 0.69162512),
( 1, 0.61729734, -0.47187926, 0.50554728),
( 2, 0.4171228 , -1.35680324, -1.01349922),
( 3, -0.16636303, -0.95775849, 1.17865945),
( 4, -0.16410334, 0.0745164 , -0.67432474),
( 5, -0.34016865, -0.29369841, 1.23179064),
( 6, -1.06282542, 0.55627285, 1.50805754),
( 7, 0.95961001, 0.24753911, 0.09133339),
dtype=[('index', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Just to go a little bit further in the matter, you can also set a bitmap directly, like this:
ImageView imageView = new ImageView(this);
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);
Of course, this technique is only useful if you need to change the image.
Here is some workaround to make numpys look more like Lists
np_arr = np.array([])
np_arr = np.append(np_arr , 2)
np_arr = np.append(np_arr , 24)
print(np_arr)
OUTPUT: array([ 2., 24.])
2017:
If it in on same domain just :
iframe.contentWindow.location.reload();
will work.
Annotate your field (or getter) with @Temporal(TemporalType.TIMESTAMP)
, like this:
public class MyEntity {
...
@Temporal(TemporalType.TIMESTAMP)
private java.util.Date myDate;
...
}
That should do the trick.
Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu">
on any page to reproduce the HTML.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Masterpage</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function nav() {
var menuHTML= '<ul><li><a href="#">link 1</a></li></ul><ul><li><a href="#">link 2</a></li></ul>';
$('#menu').append(menuHTML);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="nav()">
<div id="menu"></div>
</body>
</html>
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
It is not possible using just cut
. Here is a way using grep
:
grep -o '[^,]*$'
Replace the comma for other delimiters.
I had something similar with your problem today.
I didn't wanted to have it handled by the server trhough cron (and most of the libs were just cron helpers in the end).
So i've created a scheduling module and attached it to the init .
It's not the best approach, but it helps me to have all the code in a single place and with its execution related to the main app.
Datalist includes autocomplete and suggestions natively, it can also allow a user to enter a value that is not defined in the suggestions.
Select only gives you pre-defined options the user has to select from
I had a similar problem: In my test-cases executions I always got this error. I found out, that my "Distributed Transaction Service" was not started (run: services.msc -> start "Distributed Transaction Service" (best to set it to start automatic)). After I did that, it worked like a charm...
$('input[name="testing"]').val(theValue);
No need to create overload methods, just use one single method with params as shown below
// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);
You would have to use the JavascriptExecutor class:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");
If your are not in a session you can just nextval('you_sequence_name') and it's just fine.
You can run ruby commands in one line with the -e
flag:
ruby -e "puts 'hi'"
Check the man page for more information.
Simple answer is that: Go to your console app's properties(project's properties).In the "Application" tab, just change the "Output type" to "Windows Application". That's all.
Source files are often concatenated by tools (C, C++: header files, Javascript: bundlers). If you omit the newline character, you could introduce nasty bugs (where the last line of one source is concatenated with the first line of the next source file). Hopefully all the source code concat tools out there insert a newline between concatenated files anyway but that doesn't always seem to be the case.
The crux of the issue is - in most languages, newlines have semantic meaning and end-of-file is not a language defined alternative for the newline character. So you ought to terminate every statement/expression with a newline character -- including the last one.
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
file()
is not supported in Python 3
Use open()
instead; see Built-in Functions - open().
You can add a specific url to each point, e.g.:
var points = [
['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];
Add the url to the marker values in the for-loop:
var marker = new google.maps.Marker({
...
zIndex: place[3],
url: place[4]
});
Then you can add just before to the end of your for-loop:
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
Also see this example.
http://desktop-qr277sp/Reports01/report/Reports/reportName?Log%In%Name=serverUsername¶mName=value
Pass parameter to the report with server authentication
|
is a metacharacter in regex. You'd need to escape it:
String[] value_split = rat_values.split("\\|");
For en-US ( American English ) strings this should suffice:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )
Be aware that if you support UTF-8 and characters like chinese/russian and all, this will replace them as well, so you really have to specify what you want.
To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder
i solved with a max-width
in my main css-file.
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
It's a simple solution with little "code"
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/
You can use 'USING' instead of 'ON' as in the query
SELECT * FROM table1 LEFT JOIN table2 USING (id);
Simply saying, Java context means Java native
methods all together.
In next Java code two lines of code needs context: // (1)
and // (2)
import java.io.*;
public class Runner{
public static void main(String[] args) throws IOException { // (1)
File file = new File("D:/text.txt");
String text = "";
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null){ // (2)
text += line;
}
System.out.println(text);
}
}
(1) needs context because is invoked by Java native method private native void java.lang.Thread.start0();
(2) reader.readLine()
needs context because invokes Java native method public static native void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
PS.
That is what BalusC is sayed about pattern Facade more strictly.
Functions are first class objects that can be:
To build on the example given by Kenny:
function a(x) {
var w = function b(y) {
return x + y;
}
return w;
};
var returnedFunction = a(3);
alert(returnedFunction(2));
Would alert you with 5.
After <persistence-unit name="agisdb">
, define the persistence provider name:
<provider>org.hibernate.ejb.HibernatePersistence</provider>
You can create a function which would allow you to do the same as timeout but also for other functions:
function run_cmd {
cmd="$1"; timeout="$2";
grep -qP '^\d+$' <<< $timeout || timeout=10
(
eval "$cmd" &
child=$!
trap -- "" SIGTERM
(
sleep $timeout
kill $child 2> /dev/null
) &
wait $child
)
}
And could run as below:
run_cmd "echoFooBar" 10
Note: The solution came from one of my questions: Elegant solution to implement timeout for bash commands and functions
When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
In Swift:
override func viewDidLoad() {
super.viewDidLoad()
// We set the table view header.
let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
self.tableView.tableHeaderView = cellTableViewHeader
// We set the table view footer, just know that it will also remove extra cells from tableview.
let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
self.tableView.tableFooterView = cellTableViewFooter
}
Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause()
is called when another activity gains focus, and onStop()
is called when the activity is no longer visible.
From what I have learned yet, you can call finish()
only from the activity which is active and/or has the focus. If you're calling finish()
from the onPause()
method that means you're calling it when the activity is no longer active. thus an exception is thrown.
When you're calling finish()
from onStop()
then the activity is being sent to background, thus will no longer be visible, then this exception.
When you press the back
button, onStop()
is called.
Most probably, Android will automatically do for you what you are currently wanting to do.
A pure javascript solution (without jQuery
):
const SEARCH_DELAY = 100; // in ms
// it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
function waitForElementToBeAdded(cssSelector) {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (element = document.querySelector(cssSelector)) {
clearInterval(interval);
resolve(element);
}
}, SEARCH_DELAY);
});
}
console.log(await waitForElementToBeAdded('#main'));
We can set java.util.Date time part to 00:00:00 By using LocalDate class of Java 8/Joda-datetime api:
Date datewithTime = new Date() ; // ex: Sat Apr 21 01:30:44 IST 2018
LocalDate localDate = LocalDate.fromDateFields(datewithTime);
Date datewithoutTime = localDate.toDate(); // Sat Apr 21 00:00:00 IST 2018
USE Master GO
ALTER Server Role [bulkadmin] ADD MEMBER [username] GO Command failed even tried several command parameters
master..sp_addsrvrolemember @loginame = N'username', @rolename = N'bulkadmin' GO Command was successful..
I know there are a lot of answers to this already but I would like to put in my two cents. When creating a virtual environment in anaconda launcher you still need to install the packages you need. This is deceiving because I assumed since I was using anaconda that packages such as pandas, numpy etc would be include. This is not the case. It gives you a fresh environment with none of those packages installed, at least mine did. All my packages installed into the environment with no problem and work correctly.
Due to the exposed fact that Class literals doesn't have generic type information, I think you should assume that it will be impossible to get rid of all the warnings. In a way, using Class<Something>
is the same as using a collection without specifying the generic type. The best I could come out with was:
private <C extends A<C>> List<C> getList(Class<C> cls) {
List<C> res = new ArrayList<C>();
// "snip"... some stuff happening in here, using cls
return res;
}
public <C extends A<C>> List<A<C>> getList() {
return getList(A.class);
}
It may be because I'm using Spring 3.1 (instead of Spring 3.0.5 as your question specified), but Steve Eastwood's answer didn't work for me. This solution works for Spring 3.1:
In your spring xml context:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jacksonObjectMapper" class="de.Company.backend.web.CompanyObjectMapper" />
Your merge stopped in the middle of the action. You should add your files, and then 'git commit':
git add file_1.php file_2.php file_3.php
git commit
Cheers
from threading import Timer
def TaskManager():
#do stuff
t = Timer( 1, TaskManager )
t.start()
TaskManager()
Here is small sample, it will help beter understanding how it runs. function taskManager() at the end create delayed function call to it self.
Try to change "dalay" variable and you will able to see difference
from threading import Timer, _sleep
# ------------------------------------------
DATA = []
dalay = 0.25 # sec
counter = 0
allow_run = True
FIFO = True
def taskManager():
global counter, DATA, delay, allow_run
counter += 1
if len(DATA) > 0:
if FIFO:
print("["+str(counter)+"] new data: ["+str(DATA.pop(0))+"]")
else:
print("["+str(counter)+"] new data: ["+str(DATA.pop())+"]")
else:
print("["+str(counter)+"] no data")
if allow_run:
#delayed method/function call to it self
t = Timer( dalay, taskManager )
t.start()
else:
print(" END task-manager: disabled")
# ------------------------------------------
def main():
DATA.append("data from main(): 0")
_sleep(2)
DATA.append("data from main(): 1")
_sleep(2)
# ------------------------------------------
print(" START task-manager:")
taskManager()
_sleep(2)
DATA.append("first data")
_sleep(2)
DATA.append("second data")
print(" START main():")
main()
print(" END main():")
_sleep(2)
DATA.append("last data")
allow_run = False
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.
.mydiv {
...
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
...
}
Adapted from: MDN
Try this one
.parent_div{
display: flex;
}
I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest
Get-ChildItem $tfsLocalPath -Recurse | #Find all children
Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} | #Calculate the length of their path
Sort-Object PathLength -Descending | #sort by path length descending
%{ Get-Item -LiteralPath $_.FullName } |
Remove-Item -Force
Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808
Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.
const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter
/** remove warning that you don't care about */
function cleanWarning(error) {
return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}
function callPython(scriptName, args) {
return new Promise(function(success, reject) {
const script = pythonDir + scriptName;
const pyArgs = [script, JSON.stringify(args) ]
const pyprog = spawn(python, pyArgs );
let result = "";
let resultError = "";
pyprog.stdout.on('data', function(data) {
result += data.toString();
});
pyprog.stderr.on('data', (data) => {
resultError += cleanWarning(data.toString());
});
pyprog.stdout.on("end", function(){
if(resultError == "") {
success(JSON.parse(result));
}else{
console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
const error = new Error(resultError);
console.error(error);
reject(resultError);
}
})
});
}
module.exports.callPython = callPython;
Call:
const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});
python:
try:
argu = json.loads(sys.argv[1])
except:
raise Exception("error while loading argument")
using user 113716 solution, which by the way is great to avoid all those if-else I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity.
In the process writing of non numbers in unit and quantity textboxes, their values are bing replace by zero so final posting of user data has no non-numbers .
<script src="/common/tools/jquery-1.10.2.js"></script>
<script src="/common/tools/jquery-ui.js"></script>
<!----------------- link above 2 lines to your jquery files ------>
<script type="text/javascript" >
function calculate_subtotal(){
$('#quantity').val((+$('#quantity').val() || 0));
$('#unit').val((+$('#unit').val() || 0));
var calculated = $('#quantity').val() * $('#unit').val() ;
$('#subtotal').val(calculated);
}
</script>
<input type = "text" onChange ="calculate_subtotal();" id = "quantity"/>
<input type = "text" onChange ="calculate_subtotal();" id = "unit"/>
<input type = "text" id = "subtotal"/>
Working one liner if you want a single result from the collection:
$ipAddy = [System.Net.Dns]::GetHostAddresses("yahoo.com")[0].IPAddressToString;
hth
Or if you need it in a loop
foreach ($array as $key => $value)
{
echo $key . ':' . $value . "\n";
}
//Result:
//one:value
//two:value2
You can use
git rm -r --cached -- "path/to/directory"
to stage a deleted directory.
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??
This uses twitter bootstrap 3.x with one css class to get labels to sit on top of the inputs. Here's a fiddle link, make sure to expand results panel wide enough to see effect.
HTML:
<div class="row myform">
<div class="col-md-12">
<form name="myform" role="form" novalidate>
<div class="form-group">
<label class="control-label" for="fullName">Address Line</label>
<input required type="text" name="addr" id="addr" class="form-control" placeholder="Address"/>
</div>
<div class="form-inline">
<div class="form-group">
<label>State</label>
<input required type="text" name="state" id="state" class="form-control" placeholder="State"/>
</div>
<div class="form-group">
<label>ZIP</label>
<input required type="text" name="zip" id="zip" class="form-control" placeholder="Zip"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<input required type="text" name="country" id="country" class="form-control" placeholder="country"/>
</div>
</form>
</div>
</div>
CSS:
.myform input.form-control {
display: block; /* allows labels to sit on input when inline */
margin-bottom: 15px; /* gives padding to bottom of inline inputs */
}
You could create a random number using FLOOR(RAND() * n) as randnum
(n is an integer), however if you do not need the same random number to be repeated then you will have to somewhat store in a temp table. So you can check it against with where randnum not in (select * from temptable)
...
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
hive> show partitions table_name;
Yep! Use the link:
https://m.google.com/app/plus/x/?v=compose&content=YOUR_TEXT
It's SHARE url (not used for plus one) button.
If this will not work (not for me) try this url:
https://plusone.google.com/_/+1/confirm?hl=ru&url=_URL_&title=_TITLE_
Or see this solution:
Adding a Google Plus (one or share) link to an email newsletter
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
Try
class MissileLauncher
{
public:
MissileLauncher(void);
private:
unsigned char abc[3];
};
or
using byte = unsigned char;
class MissileLauncher
{
public:
MissileLauncher(void);
private:
byte abc[3];
};
**Note: In older compilers (non-C++11) replace the using
line with typedef unsigned char byte;
I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:
<configuration>
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/init1.aspx?call=2"/>
<add initializationPage="/init1.aspx?call=2" />
</applicationInitialization>
</system.webServer>
Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
After Jenkins is installed just run sudo cat /var/lib/jenkins/secrets/initialAdminPassword
.
In the Jenkins login page:
User: admin
Password: the output from the above command
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
On CentOS EL 6 and perhaps on earlier versions there is one way to get into this same mess.
Install CentOS EL6 with a minimal installation. For example I used kickstart to install the following:
%packages
@core
acpid
bison
cmake
dhcp-common
flex
gcc
gcc-c++
git
libaio-devel
make
man
ncurses-devel
perl
ntp
ntpdate
pciutils
tar
tcpdump
wget
%end
You will find that one of the dependencies of the above list is mysql-libs
. I found that my system has a default my.cnf
in /etc
and this contains:
[mysqld]
dataddir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
When you build from the Generic Linux (Architecture Independent), Compressed TAR Archive
your default data directory is /usr/local/mysql/data
which conflicts with the /etc/my.cnf
already present which defines datadir=/var/lib/mysql
. Also the pid-file
defined in the same file does not have permissions for the mysql user/group to write to it in /var/run/mysqld
.
A quick remedy is to mv /etc/my.cnf /etc/my.cnf.old
which should get your generic source procedure working.
Of course the experience is different of you use the source RPMs.
I think that concat
method and +
should be mentioned here as well:
assert_eq!(
("My".to_owned() + " " + "string"),
["My", " ", "string"].concat()
);
and there is also concat!
macro but only for literals:
let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");
This while else statement should only execute the else code when the condition is false, this means it will always execute it. But, there is a catch, when you use the break keyword within the while loop, the else statement should not execute.
The code that satisfies does condition is only:
boolean entered = false;
while (condition) {
entered = true; // Set it to true stright away
// While loop code
// If you want to break out of this loop
if (condition) {
entered = false;
break;
}
} if (!entered) {
// else code
}
This did it for me. in a custom/reusable class. helps alot with the space in b/w the actual text and left view icon/image
func currencyLeftVeiw(image litery: UIImage) {
self.leftView = UIView(frame: CGRect(x: 10, y: 0, width: 40, height: 40))
self.leftViewMode = .always
let leftViewItSelf = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
leftViewItSelf.image = litery
leftView?.addSubview(leftViewItSelf)
}
The Google AJAX Libraries API, which includes jQuery UI (currently v1.10.3), also includes popular themes as per the jQuery UI blog:
Google Ajax Libraries API (CDN)
Uncompressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js
Compressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js
Themes Uncompressed: black-tie, blitzer, cupertino, dark-hive, dot-luv, eggplant, excite-bike, flick, hot-sneaks, humanity, le-frog, mint-choc, overcast,pepper-grinder, redmond, smoothness, south-street, start, sunny, swanky-purse, trontastic, ui-darkness, ui-lightness, and vader.
Themes Compressed: black-tie, blitzer, cupertino, dark-hive, dot-luv, eggplant, excite-bike, flick, hot-sneaks, humanity, le-frog, mint-choc, overcast,pepper-grinder, redmond, smoothness, south-street, start, sunny, swanky-purse, trontastic, ui-darkness, ui-lightness, and vader.
You can use Sorted Set in redis to get a TTL container with timestamp as score.
For example, whenever you insert a event string into the set you can set its score to the event time.
Thus you can get data of any time window by calling
zrangebyscore "your set name" min-time max-time
Moreover, we can do expire by using zremrangebyscore "your set name" min-time max-time
to remove old events.
The only drawback here is you have to do housekeeping from an outsider process to maintain the size of the set.
Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).
From the website:
Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.
FROM openjdk:8-jdk-alpine
RUN apk update && apk add wget openssl lsof procps curl
RUN apk update
RUN mkdir -p /apps/agent
RUN mkdir -p /apps/lib
ADD ./app/agent /apps/agent
ADD ./app/lib /apps/lib
ADD ./app/* /apps/app/
RUN ls -lrt /apps/app/
CMD sh /apps/app/launch.sh
by using DockerFile, I'm copying agent and lib directories to /apps/agent,/apps/lib directories and bunch of files to target.
I try to avoid a few things when using Git.
Using knowledge of the internals, e.g. refs/tags. I try to use solely the documented Git commands and avoid using things which require knowledge of the internal contents of the .git directory. (That is to say, I treat Git as a Git user and not a Git developer.)
The use of force when not required.
Overdoing things. (Pushing a branch and/or lots of tags, to get one tag where I want it.)
So here is my non-violent solution for changing a tag, both locally and remotely, without knowledge of the Git internals.
I use it when a software fix ultimately has a problem and needs to be updated/re-released.
git tag -d fix123 # delete the old local tag
git push github :fix123 # delete the old remote tag (use for each affected remote)
git tag fix123 790a621265 # create a new local tag
git push github fix123 # push new tag to remote (use for each affected remote)
github
is a sample remote name, fix123
is a sample tag name, and 790a621265
a sample commit.
[ -n file.txt ]
doesn't check its size, it checks that the string file.txt
is non-zero length, so it will always succeed.
If you want to say "size is non-zero", you need [ -s file.txt ]
.
To get a file's size, you can use wc -c
to get the size (file length) in bytes:
file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
fi
In this case, it sounds like that's what you want.
But FYI, if you want to know how much disk space the file is using, you could use du -k
to get the size (disk space used) in kilobytes:
file=file.txt
minimumsize=90
actualsize=$(du -k "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize kilobytes
else
echo size is under $minimumsize kilobytes
fi
If you need more control over the output format, you can also look at stat
. On Linux, you'd start with something like stat -c '%s' file.txt
, and on BSD/Mac OS X, something like stat -f '%z' file.txt
.
How about less /var/log/syslog
?
from inside an activity that calls a layout and a textview, this click listener works:
setContentView(R.layout.your_layout);
TextView tvGmail = (TextView) findViewById(R.id.tvGmail);
String TAG = "yourLogCatTag";
tvGmail.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
Log.d(TAG,"GMAIL account selected");
} catch (Exception except) {
Log.e(TAG,"Ooops GMAIL account selection problem "+except.getMessage());
}
}
});
the text view is declared like this (default wizard):
<TextView
android:id="@+id/tvGmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/menu_id_google"
android:textSize="30sp" />
and in the strings.xml file
<string name="menu_id_google">Google ID (Gmail)</string>
Its true the official documentation (Apache log4net™ Manual - Introduction) states there are the following levels...
... but oddly when I view assembly log4net.dll, v1.2.15.0 sealed class log4net.Core.Level I see the following levels defined...
public static readonly Level Alert;
public static readonly Level All;
public static readonly Level Critical;
public static readonly Level Debug;
public static readonly Level Emergency;
public static readonly Level Error;
public static readonly Level Fatal;
public static readonly Level Fine;
public static readonly Level Finer;
public static readonly Level Finest;
public static readonly Level Info;
public static readonly Level Log4Net_Debug;
public static readonly Level Notice;
public static readonly Level Off;
public static readonly Level Severe;
public static readonly Level Trace;
public static readonly Level Verbose;
public static readonly Level Warn;
I have been using TRACE in conjunction with PostSharp OnBoundaryEntry and OnBoundaryExit for a long time. I wonder why these other levels are not in the documentation. Furthermore, what is the true priority of all these levels?
You would do that by providing a fully qualified name, e.g.:
SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id
Which would give you the id of tbl_names
Use CSS background-clip:
background-clip: content-box;
The background will be painted within the content box.
Extending on what Martin said, recording the install output and a little bash scripting does the trick quite nicely. Here's what I do...
for i in $(less install.record);
sudo rm $i;
done;
And presto. Uninstalled.
You should use append("svg:svg")
, not append("svg")
so that D3 makes the element with the correct 'namespace' if you're using xhtml.
Add this to the UIWebView delegate:
(edited to check for navigation type. you could also pass through file://
requests which would be relative links)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
return YES;
}
Swift Version:
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(request.URL!)
return false
}
return true
}
Swift 3 version:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.linkClicked {
UIApplication.shared.openURL(request.url!)
return false
}
return true
}
Swift 4 version:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
guard let url = request.url, navigationType == .linkClicked else { return true }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
return false
}
Update
As openURL
has been deprecated in iOS 10:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
UIApplication *application = [UIApplication sharedApplication];
[application openURL:[request URL] options:@{} completionHandler:nil];
return NO;
}
return YES;
}
To build on Anton's answer a little --
angular.module("app").directive("onlyDigits", function ()
{
return {
restrict: 'EA',
require: '?ngModel',
scope:{
allowDecimal: '@',
allowNegative: '@',
minNum: '@',
maxNum: '@'
},
link: function (scope, element, attrs, ngModel)
{
if (!ngModel) return;
ngModel.$parsers.unshift(function (inputValue)
{
var decimalFound = false;
var digits = inputValue.split('').filter(function (s,i)
{
var b = (!isNaN(s) && s != ' ');
if (!b && attrs.allowDecimal && attrs.allowDecimal == "true")
{
if (s == "." && decimalFound == false)
{
decimalFound = true;
b = true;
}
}
if (!b && attrs.allowNegative && attrs.allowNegative == "true")
{
b = (s == '-' && i == 0);
}
return b;
}).join('');
if (attrs.maxNum && !isNaN(attrs.maxNum) && parseFloat(digits) > parseFloat(attrs.maxNum))
{
digits = attrs.maxNum;
}
if (attrs.minNum && !isNaN(attrs.minNum) && parseFloat(digits) < parseFloat(attrs.minNum))
{
digits = attrs.minNum;
}
ngModel.$viewValue = digits;
ngModel.$render();
return digits;
});
}
};
});
Here's a useful little function, which makes using/creating iOS folders a little easier.
You pass it the name of a subfolder, it'll return the full path back to you, and make sure the directory exists.
(Personally, I stick this static function in my AppDelete class, but perhaps this isn't the smartest place to put it.)
Here's how you would call it, to get the "full path" of a MySavedImages subdirectory:
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
And here's the full function:
+(NSString*)getFullPath:(NSString*)folderName
{
// Check whether a subdirectory exists in our sandboxed Documents directory.
// Returns the full path of the directory.
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (paths.count < 1)
return nil;
NSString *rootFolder = [paths firstObject];
NSString* fullFolderPath = [rootFolder stringByAppendingPathComponent:folderName];
BOOL isDirectory;
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:fullFolderPath isDirectory:&isDirectory] || !isDirectory) {
NSError *error = nil;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:fullFolderPath
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error) {
NSLog(@"Error creating directory path: %@", [error localizedDescription]);
return nil;
}
}
return fullFolderPath;
}
Using this little function, it's easy to create a directory in your app's Documents directory (if it doesn't already exist), and to write a file into it.
Here's how I would create the directory, and write the contents of one of my image files into it:
// Let's create a "MySavedImages" subdirectory (if it doesn't already exist)
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
// As an example, let's load the data in one of my images files
NSString* imageFilename = @"icnCross.png";
UIImage* image = [UIImage imageNamed:imageFilename];
NSData *imageData = UIImagePNGRepresentation(image);
// Obtain the full path+filename where we can write this .png to, in our new MySavedImages directory
NSString* imageFilePathname = [fullPath stringByAppendingPathComponent:imageFilename];
// Write the data
[imageData writeToFile:imageFilePathname atomically:YES];
Hope this helps !
In Java I'd use Guava's Optional type. Being an actual type you get compiler guarantees about its use. It's easy to bypass it and obtain a NullPointerException
, but at least the signature of the method clearly communicates what it expects as an argument or what it might return.
I do meet this problem. use ojdbc14.jar and jdk 1.6
InputStream in = new FileInputStream(file);
cstmt.setBinaryStream(1, in,file.length()); // got AbstractMethodError
InputStream in = new FileInputStream(file);
cstmt.setBinaryStream(1, in,(int)file.length()); // no problem.
In case you are trying to log all errors make sure you keep Task.WhenAll line in your code, lot of comments suggest that you can remove it and wait for individual tasks. Task.WhenAll is really important for error handling. Without this line you potentially leaving your code open for unobserved exceptions.
var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();
await Task.WhenAll(catTask, houseTask, carTask);
var cat = await catTask;
var house = await houseTask;
var car = await carTask;
Imagine FeedCat throws exception in the following code:
var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();
var cat = await catTask;
var house = await houseTask;
var car = await carTask;
In that case you will never await on houseTask nor carTask. There are 3 possible scenarios here:
SellHouse is already completed successfully when FeedCat failed. In this case you are fine.
SellHouse is not complete and fails with exception at some point. Exception is not observed and will be rethrown on finalizer thread.
SellHouse is not complete and contains awaits inside it. In case your code runs in ASP.NET SellHouse will fail as soon as some of the awaits will completed inside it. This happens because you basically made fire & forget call and synchronization context was lost as soon as FeedCat failed.
Here is error that you will get for case (3):
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
at System.Web.HttpApplication.System.Web.Util.ISyncContext.Enter()
at System.Web.Util.SynchronizationHelper.SafeWrapCallback(Action action)
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
at System.Web.HttpApplication.System.Web.Util.ISyncContext.Enter()
at System.Web.Util.SynchronizationHelper.SafeWrapCallback(Action action)
at System.Threading.Tasks.Task.Execute()<---
For case (2) you will get similar error but with original exception stack trace.
For .NET 4.0 and later you can catch unobserved exceptions using TaskScheduler.UnobservedTaskException. For .NET 4.5 and later unobserved exceptions are swallowed by default for .NET 4.0 unobserved exception will crash your process.
More details here: Task Exception Handling in .NET 4.5
Here maybe helpful answer for your problem using Rx Java & Rx Android.
You can add join type as well:
Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);
To remove all objects in oracle :
1) Dynamic
DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE'
AND OWNER='SCHEMA_NAME';
CURSOR IY IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND OWNER='SCHEMA_NAME';
CURSOR IZ IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND OWNER='SCHEMA_NAME';
BEGIN
FOR X IN IX LOOP
EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' '||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
END LOOP;
FOR Y IN IY LOOP
EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' '||Y.OBJECT_NAME);
END LOOP;
FOR Z IN IZ LOOP
EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' '||Z.OBJECT_NAME||' FORCE ');
END LOOP;
END;
/
2)Static
SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
union ALL
select 'drop '||object_type||' '|| object_name || ';' from user_objects
where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
union ALL
SELECT 'drop '
||object_type
||' '
|| object_name
|| ' force;'
FROM user_objects
WHERE object_type IN ('TYPE');
Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.
TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.
See Do I need to heartbeat to keep a TCP connection open? for more discussion.
You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).
We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)
I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.
It doesn't seem like you're asking for an implementation, so I'll try to explain the process.
Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).
When the queue is empty every element should have been printed out.
Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search
What you are passing to GETNAME
is the value of myInput
, not the definition of myInput
itself. The only way to do that is with a lambda expression, for example:
var nameofVar = GETNAME(() => myInput);
and indeed there are examples of that available. However! This reeks of doing something very wrong. I would propose you rethink why you need this. It is almost certainly not a good way of doing it, and forces various overheads (the capture class instance, and the expression tree). Also, it impacts the compiler: without this the compiler might actually have chosen to remove that variable completely (just using the stack without a formal local).
It works more or less like this (example using an image/jpg file):
async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData)
{
var requestContent = new MultipartFormDataContent();
// here you can specify boundary if you need---^
var imageContent = new ByteArrayContent(ImageData);
imageContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("image/jpeg");
requestContent.Add(imageContent, "image", "image.jpg");
return await client.PostAsync(url, requestContent);
}
(You can requestContent.Add()
whatever you want, take a look at the HttpContent descendant to see available types to pass in)
When completed, you'll find the response content inside HttpResponseMessage.Content
that you can consume with HttpContent.ReadAs*Async
.
It seems that I'm late on this issue and/or it has already been answered, but, what could be done is: (in my case, I had only one tag locally so.. I deleted the old tag and retagged it with:
git tag -d v1.0
git tag -a v1.0 -m "My commit message"
Then:
git push --tags -f
That will update all tags on remote.
Could be dangerous! Use at own risk.
Alternatively you can execute program with specified library dir:
/lib/ld-linux.so.2 --library-path PATH EXECUTABLE
Create an instance of Class B:
B b=new B();
b.method();
or define an static method in Class B:
class B
{
static void staticMethod();
}
and call it like this:
B.staticMethod();
You can set the style attribute of any element... the trick is that in IE you have to do it differently. (bug 245)
//Standards base browsers
elem.setAttribute('style', styleString);
//Non Standards based IE browser
elem.style.setAttribute('cssText', styleString);
Note that in IE8, in Standards Mode, the first way does work.
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
inside OnCreate method :-
{
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener((View.OnClickListener)this);
b = (Button)findViewById(R.id.button2);
b.setOnClickListener((View.OnClickListener)this);
}
@Override
public void OnClick(View v){
switch(v.getId()){
case R.id.button1:
//whatever
break;
case R.id.button2:
//whatever
break;
}
Simple solution
{{ orderTotal | number : '1.2-2'}}
//output like this
// public orderTotal = 220.45892221
// {{ orderTotal | number : '1.2-2'}}
// final Output
// 220.45
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
Simple bar graph:
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes
data.dat:
0 label 100
1 label2 450
2 "bar label" 75
If you want to style your bars differently, you can do something like:
set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"
set style fill solid
set boxwidth 0.5
plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
"data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2
If you want to do multiple bars for each entry:
data.dat:
0 5
0.5 6
1.5 3
2 7
3 8
3.5 1
gnuplot:
set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)
set boxwidth 0.5
set style fill solid
plot 'data.dat' every 2 using 1:2 with boxes ls 1,\
'data.dat' every 2::1 using 1:2 with boxes ls 2
If you want to be tricky and use some neat gnuplot tricks:
Gnuplot has psuedo-columns that can be used as the index to color:
plot 'data.dat' using 1:2:0 with boxes lc variable
Further you can use a function to pick the colors you want:
mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable
Note: you will have to add a couple other basic commands to get the same effect as the sample images.
First check your Internet conection..
or try with
Tools -> Android -> Sync
or Try
File -> Settings -> Gradle -> Check Offline Work
The magic variables %
n contains the arguments used to invoke the file: %0
is the path to the bat-file itself, %1
is the first argument after, %2
is the second and so on.
Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d
is drive, ~p
is the path (without drive), ~n
is the file name. They can be combined so ~dp
is drive+path.
%~dp0
is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.
You can also get other kinds of meta info about the file: ~t
is the timestamp, ~z
is the size.
Look here for a reference for all command line commands. The tilde-magic codes are described under for.
You can use \n for new line
alert("Welcome\nto Jumanji");
alert("Welcome\nto Jumanji");
_x000D_
Now has a new nuget package, try use it: https://www.nuget.org/packages/Oracle.ManagedDataAccess.EntityFramework/
I have a similar issue, and this is what I'm doing:
insert into Preguntas (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` ) select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18
Been Preguntas:
CREATE TABLE IF NOT EXISTS `Preguntas` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`EncuestaID` int(11) DEFAULT NULL,
`Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
`Seccion` int(11) DEFAULT NULL,
`RespuestaID` bigint(11) DEFAULT NULL,
`Texto` text COLLATE utf8_unicode_ci ,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;
So, the ID
is automatically incremented and also I'm using a fixed value ('23') for EncuestaID
.
Probably an issue with strings having whitespace. Here's a cleaned up version that works for me:
Function Test-RegistryValue($regkey, $name) {
$exists = Get-ItemProperty -Path "$regkey" -Name "$name" -ErrorAction SilentlyContinue
If (($exists -ne $null) -and ($exists.Length -ne 0)) {
Return $true
}
Return $false
}
Another option for working out the encoding is to use libmagic (which is the code behind the file command). There are a profusion of python bindings available.
The python bindings that live in the file source tree are available as the python-magic (or python3-magic) debian package. It can determine the encoding of a file by doing:
import magic
blob = open('unknown-file', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob) # "utf-8" "us-ascii" etc
There is an identically named, but incompatible, python-magic pip package on pypi that also uses libmagic
. It can also get the encoding, by doing:
import magic
blob = open('unknown-file', 'rb').read()
m = magic.Magic(mime_encoding=True)
encoding = m.from_buffer(blob)
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.
Look into the File class.
You can create a streamwriter with
StreamWriter sw = File.Create(....)
You can open an existing file with
File.Open(...)
You can append text easily with
File.AppendAllText(...);
Use URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var data = new URLSearchParams();
data.append('userName', '[email protected]');
data.append('password', 'Password');
data.append('grant_type', 'password');
I fixed this for an instance of it happening to me by deleting the hidden .svn folder and then performing a checkout on the folder to the same URL.
This did not overwrite any of my modified files & just versioned all of the existing files instead of grabbing fresh copies from the server.
In python 3.2 and later, there is a useful contextmanager for this in the stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory
My program with two arguments, args[0] and args[1]:
public static void main(String[] args) throws Exception {
System.out.println(args);
String host = args[0];
System.out.println(host);
int port = Integer.parseInt(args[1]);
my build.gradle
run {
if ( project.hasProperty("appArgsWhatEverIWant") ) {
args Eval.me(appArgsWhatEverIWant)
}
}
my terminal prompt:
gradle run -PappArgsWhatEverIWant="['localhost','8080']"
This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....
application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.
Solution
Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.
I also ran into this issue. It was because I forgot to await for a promise.
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
What solved this problem for me was changing WSGIPassAuthorization
to 'On'
in wsgi.conf
.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
This is a example for get the url image, escape the p tag from some item.
Try this:
$('#img').attr('src').split('<p>')[1].split('</p>')[0]
One option from dplyr 1.0.0
could be:
DF %>%
rowwise() %>%
mutate(row_max = names(.)[which.max(c_across(everything()))])
V1 V2 V3 row_max
<dbl> <dbl> <dbl> <chr>
1 2 7 9 V3
2 8 3 6 V1
3 1 5 4 V2
Sample data:
DF <- structure(list(V1 = c(2, 8, 1), V2 = c(7, 3, 5), V3 = c(9, 6,
4)), class = "data.frame", row.names = c(NA, -3L))
I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:
componentDidMount(){
fetch('./data/json-data.json')
.then ( resp1 => resp1.json() )
.then ( users1 => this.setState( {cards : users1} ) )
}
so I created public/data/json-data.json
and everything was fine then :)
That's because jQuery can do much more than querySelectorAll
.
First of all, jQuery (and Sizzle, in particular), works for older browsers like IE7-8 that doesn't support CSS2.1-3 selectors.
Plus, Sizzle (which is the selector engine behind jQuery) offers you a lot of more advanced selector instruments, like the :selected
pseudo-class, an advanced :not()
selector, a more complex syntax like in $("> .children")
and so on.
And it does it cross-browsers, flawlessly, offering all that jQuery can offer (plugins and APIs).
Yes, if you think you can rely on simple class and id selectors, jQuery is too much for you, and you'd be paying an exaggerated pay-off. But if you don't, and want to take advantage of all jQuery goodness, then use it.
There's also a shorthand ternary operator and it looks like this:
(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.
Example:
$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';
will return
Apples are great!
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
From the PHP Manual
this worked for me with minimal code
$(my_list).remove('li');
Please check your web.xml again. You might be making some silly mistake. As my application is working fine with the same init-param configuration...
Please copy paste the web.xml, if the problem still persists.
I had similar issues when migrating to androidx.
If by adding the below two lines to gradle.properties did not solve the issue
android.useAndroidX=true
android.enableJetifier=true
Then try
If you still run into issues with migration then manually try to replace the libraries which are causing the issue.
For example
If you have an issue with android.support.annotation.NonNull
change it to androidx.annotation.NonNull
as indicated in the below class mappings table.
As mentioned previously, compilers like to build lookup tables that optimize switch
statements to near O(1) timing whenever possible. Combine this with the fact that the C++ Language doesn't have a string type - std::string
is part of the Standard Library which is not part of the Language per se.
I will offer an alternative that you might want to consider, I've used it in the past to good effect. Instead of switching over the string itself, switch over the result of a hash function that uses the string as input. Your code will be almost as clear as switching over the string if you are using a predetermined set of strings:
enum string_code {
eFred,
eBarney,
eWilma,
eBetty,
...
};
string_code hashit (std::string const& inString) {
if (inString == "Fred") return eFred;
if (inString == "Barney") return eBarney;
...
}
void foo() {
switch (hashit(stringValue)) {
case eFred:
...
case eBarney:
...
}
}
There are a bunch of obvious optimizations that pretty much follow what the C compiler would do with a switch statement... funny how that happens.
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button) findViewById(R.id.uploadButton);
messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"
+ uploadFileName + "'");
/************* Php script path ****************/
upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection connection = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
+ uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
// + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ URLEncoder.encode(fileName, "UTF-8") + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
PHP FILE
<?php
$target_path = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Try this:
xcopy %1 %2 /y /e
The %1
and %2
are the source and destination arguments you pass to the batch file. i.e. C:\MyBatchFile.bat C:\CopyMe D:\ToHere
Note: you should use the accepted answer if possible. It's better than mine.
It's quite easy with the GD library.
It's built in usually, you probably have it (use phpinfo()
to check)
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagejpeg($image, "folder/file.jpg");
The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");
This only works if allow_url_fopen
is true
(it is by default)
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
This excerpt is from the following awesome post.
ERROR – something terribly wrong had happened, that must be investigated immediately. No system can tolerate items logged on this level. Example: NPE, database unavailable, mission critical use case cannot be continued.
WARN – the process might be continued, but take extra caution. Actually I always wanted to have two levels here: one for obvious problems where work-around exists (for example: “Current data unavailable, using cached values”) and second (name it: ATTENTION) for potential problems and suggestions. Example: “Application running in development mode” or “Administration console is not secured with a password”. The application can tolerate warning messages, but they should always be justified and examined.
INFO – Important business process has finished. In ideal world, administrator or advanced user should be able to understand INFO messages and quickly find out what the application is doing. For example if an application is all about booking airplane tickets, there should be only one INFO statement per each ticket saying “[Who] booked ticket from [Where] to [Where]“. Other definition of INFO message: each action that changes the state of the application significantly (database update, external system request).
DEBUG – Developers stuff. I will discuss later what sort of information deserves to be logged.
TRACE – Very detailed information, intended only for development. You might keep trace messages for a short period of time after deployment on production environment, but treat these log statements as temporary, that should or might be turned-off eventually. The distinction between DEBUG and TRACE is the most difficult, but if you put logging statement and remove it after the feature has been developed and tested, it should probably be on TRACE level.
PS: Read TRACE as VERBOSE
Adding an answer that exclusively uses the pandas library to read in a .csv file and save as a .xlsx file. This example makes use of pandas.read_csv
(Link to docs) and pandas.dataframe.to_excel
(Link to docs).
The fully reproducible example uses numpy to generate random numbers only, and this can be removed if you would like to use your own .csv file.
import pandas as pd
import numpy as np
# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)
# Reading in test.csv and saving as test.xlsx
df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()
Add this code
runOnUiThread(new Runnable() { public void run() {
adapter = new CustomAdapter(anotherdata);
adapter.notifyDataSetChanged();
}
});
Range.Rows
and Range.Columns
return essentially the same Range except for the fact that the new Range has a flag which indicates that it represents Rows or Columns. This is necessary for some Excel properties such as Range.Count and Range.Hidden and for some methods such as Range.AutoFit()
:
Range.Rows.Count
returns the number of rows in Range.Range.Columns.Count
returns the number of columns in Range.Range.Rows.AutoFit()
autofits the rows in Range.Range.Columns.AutoFit()
autofits the columns in Range.You might find that Range.EntireRow
and Range.EntireColumn
are useful, although they still are not exactly what you are looking for. They return all possible columns for EntireRow
and all possible rows for EntireColumn
for the represented range.
I know this because SpreadsheetGear for .NET comes with .NET APIs which are very similar to Excel's APIs. The SpreadsheetGear API comes with several strongly typed overloads to the IRange indexer including the one you probably wish Excel had:
IRange this[int row1, int column1, int row2, int column2];
Disclaimer: I own SpreadsheetGear LLC
Yes, you can solve it using the ElementName=Something
as suggested by Juve.
BUT!
If a child element (on which you use this kind of binding) is a user control which uses the same element name as you specify in the parent control, then the binding goes to the wrong object!!
I know this post is not a solution but I thought everyone who uses the ElementName in the binding should know this, since it's a possible runtime bug.
<UserControl x:Class="MyNiceControl"
x:Name="TheSameName">
the content ...
</UserControl>
<UserControl x:Class="AnotherUserControl">
<ListView x:Name="TheSameName">
<ListView.ItemTemplate>
<DataTemplate>
<MyNiceControl Width="{Binding DataContext.Width, ElementName=TheSameName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
An aggregate function requires a GROUP BY in standard SQL
This is "Get minimum date per title" in plain language
SELECT title, MIN(date) FROM table GROUP BY title
Most RDBMS and the standard require that column is either in the GROUP BY or in a functions (MIN, COUNT etc): MySQL is the notable exception with some extensions that give unpredictable behaviour
If the size of the circles corresponds to the square of the parameter in s=parameter
, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24]
such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.
If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]
. Try list interpretation: s=[numpy.sqrt(i) for i in s]
I use this it works for me
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
Requests and httplib2 are great options:
# Using requests.
import requests
request = requests.get(value)
if request.status_code == 200:
return True
return False
# Using httplib2.
import httplib2
try:
http = httplib2.Http()
response = http.request(value, 'HEAD')
if int(response[0]['status']) == 200:
return True
except:
pass
return False
If using Ansible, you can use the fetch_url function:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
module = AnsibleModule(
dict(),
supports_check_mode=True)
try:
response, info = fetch_url(module, url)
if info['status'] == 200:
return True
except Exception:
pass
return False
I'm not sure if this works for you, but when I do small solo PHP projects with Eclipse, the first thing I set up is an Ant script for deploying the project to a remote testing environment. I code away locally, and whenever I want to test it, I just hit the shortcut which updates the remote site.
Eclipse has good Ant support out of the box, and the scripts aren't hard to make.
Sharing data between controllers is what Factories/Services are very good for. In short, it works something like this.
var app = angular.module('myApp', []);
app.factory('items', function() {
var items = [];
var itemsService = {};
itemsService.add = function(item) {
items.push(item);
};
itemsService.list = function() {
return items;
};
return itemsService;
});
function Ctrl1($scope,items) {
$scope.list = items.list;
}
function Ctrl2($scope, items) {
$scope.add = items.add;
}
You can see a working example in this fiddle: http://jsfiddle.net/mbielski/m8saa/
This is the way I upload the file and save it into database and public folder and also the method I delete file from database and public folder.
this may help you and student to get complete source code to get the task done.
uploading file
at the first if you save file into database by giving pathpublic_path()
once it not need to used in delete method again
public function store_file(Request $request)
{
if($request->hasFile('file'))
{
$fileExtention = $request->file('file')->getClientOriginalExtension();
$name = time().rand(999,9999).$request->filename.'.'.$fileExtention;
$filePath = $request->file('file')->move(public_path().'/videos',$name);
$video = new Video_Model;
$video->file_path = $filePath;
$video->filename = $request->filename;
$video->save();
}
return redirect()->back();
}
deleting file
from database and public folder as you saved
public function delete_file(Request $request)
{
$file = Video_Model::find($request->id);
$file_path = $file->file_path;
if(file_exists($file_path))
{
unlink($file_path);
Video_Model::destroy($request->id);
}
return redirect()->back();
}
You should add mode history to your router like the below
export default new Router({
mode: 'history',
routes: [
{
...
}
]
})
Yes, C++ supports bool and it is a data type. For reference - Bool data type
//Returns a random number in the range (0.0f, 1.0f).
// 0111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
// seee eeee eeee vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv
// sign = 's'
// exponent = 'e'
// value = 'v'
double DoubleRand() {
typedef unsigned long long uint64;
uint64 ret = 0;
for (int i = 0; i < 13; i++) {
ret |= ((uint64) (rand() % 16) << i * 4);
}
if (ret == 0) {
return rand() % 2 ? 1.0f : 0.0f;
}
uint64 retb = ret;
unsigned int exp = 0x3ff;
retb = ret | ((uint64) exp << 52);
double *tmp = (double*) &retb;
double retval = *tmp;
while (retval > 1.0f || retval < 0.0f) {
retval = *(tmp = (double*) &(retb = ret | ((uint64) (exp--) << 52)));
}
if (rand() % 2) {
retval -= 0.5f;
}
return retval;
}
This should do the trick, I used this Wikipedia article to help create this. I believe it to be as good as drand48();
You could use javascript. The other answers to date seem to also target Safari.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
alert("You'll only see this in Chrome");
$('#someID').css('background-position', '10px 20px');
}
I had the same problem but when I looked closely I found that, it was causing because I was trying to put the foreign key values into the tables before that key was assigned its primary key value. e.g. I had two tables "customers" and "films", "cust_id" and "film_id" were primary key respectively. "customer" had one-to-many relation with "films" so I had "cust_id" as foreign key in "films" tables. But I was trying to put values to "films" table first, so I got that problem.
I prefer the second way.
When you use the first way, if you decide to use a parallel stream to improve performance, you'll have no control over the order in which the elements will be added to the output list by forEach
.
When you use toList
, the Streams API will preserve the order even if you use a parallel stream.
const int * ptr;
means that the pointed data is constant and immutable but the pointer is not.
int * const ptr;
means that the pointer is constant and immutable but the pointed data is not.
I was getting this error attempting to run "php artisan migrate" on Windows with a virtual box / vagrant / homestead installation.
The documentation said I had to run this command on the virtual machine.
This worked!!!
make sure to do it inside your current project folder.