If you have a function, then you probably need this:foo(&array[0], array.size());
. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
The reject
actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject()
the exception value is undefined
, hence the "undefined" part in the error that you get.
You do not show the code that uses the promise, but I reckon it is something like this:
var promise = doSth();
promise.then(function() { doSthHere(); });
Try adding an empty failure call, like this:
promise.then(function() { doSthHere(); }, function() {});
This will prevent the error to appear.
However, I would consider calling reject
only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.
In most cases, traceroute command works fine. nslookup and host commands may fail.
You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as https://xxx.xxx.xx.xx/~mohidul
I had the same problem and solved it using a boolean flag that gets set when the form is closing (the System.Timers.Timer does not have an IsDisposed property). Everywhere on the form I was starting the timer, I had it check this flag. If it was set, then don't start the timer. Here's the reason:
The Reason:
I was stopping and disposing of the timer in the form closing event. I was starting the timer in the Timer_Elapsed() event. If I were to close the form in the middle of the Timer_Elapsed() event, the timer would immediately get disposed by the Form_Closing() event. This would happen before the Timer_Elapsed() event would finish and more importantly, before it got to this line of code:
_timer.Start()
As soon as that line was executed an ObjectDisposedException() would get thrown with the error you mentioned.
The Solution:
Private Sub myForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
' set the form closing flag so the timer doesn't fire even after the form is closed.
_formIsClosing = True
_timer.Stop()
_timer.Dispose()
End Sub
Here's the timer elapsed event:
Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed
' Don't want the timer stepping on itself (ie. the time interval elapses before the first call is done processing)
_timer.Stop()
' do work here
' Only start the timer if the form is open. Without this check, the timer will run even if the form is closed.
If Not _formIsClosing Then
_timer.Interval = _refreshInterval
_timer.Start() ' ObjectDisposedException() is thrown here unless you check the _formIsClosing flag.
End If
End Sub
The interesting thing to know, even though it would throw the ObjectDisposedException when attempting to start the timer, the timer would still get started causing it to run even when the form was closed (the thread would only stop when the application was closed).
*.dll files are archive files open with winzip/7zip etc. That isnt to say that all .dll files are archives you can save anything with the .dll extension however most windows .dll files are generated to be archives examples of this are windows>twain_32.dll which is an archive file however twain.dll is not if you look at twain.dll you will see an MZŽ as the first three notepad characters which denotes a Compiled C file/program or part of a program. Whereas MZ seems to be an archive.
Also most .exe files are archives mostly containing an icon image etc for the file and the windows installer packages as well they contain all the information the program needs to run images,movies etc and also directories including installation information and plain text file.
I have a game here game.exe and it contains java class files an image a pointer directing the .exe to run a .bat file. Obviously your .bat file will run a javac call from the archive and run the game there is also a few .dll archives containing java class files also.
[autorun]
ICON=AUTORUN\MINCRAFTLOGO.ICO
standard icon redirect here .ico is an image file within a .dll file within a .exe file. So the image seen on the .exe file is the minecraft logo. This is in a file called autorun.inf. Second example
[discstarter]
startpage=Autostart\Disk1.html
uselanguagestartpage=1
windowcaption=Solid Edge
licensee=Siemens PLM Software
productguid=05B227DF-DB00-4934-B3C8-40B7D8FAA54A
singleinstance=1
hidesplashscreen=1
noscrollbars=0
showstatusbar=1
splashscreentime=0
windowwidth=750
windowheight=775
buttondir=Autostart
toolbarcolor=16777215
toolbar=goback,goforward,gohome,print,exit
[autorun]
open=autostart.exe
icon=Autostart\ENGINE.ICO
This is the solid edge autorun.inf file contained in solidedge.exe Autostart\ is the Autostart.dll directory. open=autostart.exe specifies the autostart.exe file to run from within the original solidedge.exe archive. Here is a sample program using the .dll (dynamic link library) files http://www.flipcode.com/archives/Creating_And_Using_DLLs.shtml.
It also shows how they are created. As you can see the contents of the dll file is called by an exe file as I previously explained also there is a tutorial here http://msdn.microsoft.com/en-us/library/ms235636.aspx and as i said before 7zip or winzip will open a dynamic link library as an archive as long as you have the .dll file. If the contents of the dynamic link library have been compiled obviously you need a program which can read the file.
However since .dll files are by definition just archive library files the dll itself should be readable and not a compiled C,C# file etc etc Basically .dll files are archives well should be when a .dll file is created in visual studio the dll is created and any information you store in the dll file is encrypted. Mostly this encryption is handled by visual studio itself and generally isn't edited by hand. When you read a .dll file contents as a .exe the contents are automatically decrypted. Now when we talk about compiling a program we are changing the contents into bytecode the machine easily interprets.
This filesize would be smaller than the original file of the same contents. However the filesize is larger suggesting that the file has actually been encrypted. Probably to stop people reading their code. As a result the reading of .dll contents is termed decryption and not decompilation. Decompilation would convert the already compiled txt files to unreadable byte code. The use of standard .dll files is by definition not opensource because it involves the deliberate obfuscation of byte code.
I have a code which detects a click, a long click and movement. It is fairly a combination of the answer given above and the changes i made from peeping into every documentation page.
//Declare this flag globally
boolean goneFlag = false;
//Put this into the class
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
goneFlag = true;
//Code for long click
}
};
//onTouch code
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(mLongPressed, 1000);
//This is where my code for movement is initialized to get original location.
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(mLongPressed);
if(Math.abs(event.getRawX() - initialTouchX) <= 2 && !goneFlag) {
//Code for single click
return false;
}
break;
case MotionEvent.ACTION_MOVE:
handler.removeCallbacks(mLongPressed);
//Code for movement here. This may include using a window manager to update the view
break;
}
return true;
}
I confirm it's working as I have used it in my own application.
How to insert some Text to current cursor position of a TextBox through JQuery and JavaScript
Process
Here I have 2 TextBoxes and a Button. I have to Click on a certain position on a textbox and then click on the button to paste the text from the other textbox to the the position of the previous textbox.
Main issue here is that getting the current cursor position where we will paste the text.
//Textbox on which to be pasted
<input type="text" id="txtOnWhichToBePasted" />
//Textbox from where to be pasted
<input type="text" id="txtFromWhichToBePasted" />
//Button on which click the text to be pasted
<input type="button" id="btnInsert" value="Insert"/>
<script type="text/javascript">
$(document).ready(function () {
$('#btnInsert').bind('click', function () {
var TextToBePasted = $('#txtFromWhichToBePasted').value;
var ControlOnWhichToBePasted = $('#txtOnWhichToBePasted');
//Paste the Text
PasteTag(ControlOnWhichToBePasted, TextToBePasted);
});
});
//Function Pasting The Text
function PasteTag(ControlOnWhichToBePasted,TextToBePasted) {
//Get the position where to be paste
var CaretPos = 0;
// IE Support
if (document.selection) {
ControlOnWhichToBePasted.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ControlOnWhichToBePasted.selectionStart || ControlOnWhichToBePasted.selectionStart == '0')
CaretPos = ControlOnWhichToBePasted.selectionStart;
//paste the text
var WholeString = ControlOnWhichToBePasted.value;
var txt1 = WholeString.substring(0, CaretPos);
var txt2 = WholeString.substring(CaretPos, WholeString.length);
WholeString = txt1 + TextToBePasted + txt2;
var CaretPos = txt1.length + TextToBePasted.length;
ControlOnWhichToBePasted.value = WholeString;
//update The cursor position
setCaretPosition(ControlOnWhichToBePasted, CaretPos);
}
function setCaretPosition(ControlOnWhichToBePasted, pos) {
if (ControlOnWhichToBePasted.setSelectionRange) {
ControlOnWhichToBePasted.focus();
ControlOnWhichToBePasted.setSelectionRange(pos, pos);
}
else if (ControlOnWhichToBePasted.createTextRange) {
var range = ControlOnWhichToBePasted.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
@Service
public class MyServiceImpl implements MyService {
@Inject
private MyDao myDao;
@Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
@Repository
@Transactional
public class MyDaoImpl implements MyDao {
@PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database
folder
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl
. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl
or a.b.c.dao.impl
package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks
You can acheive this with CSS but you are not techinically changing the arrow itself.
In this example I am actually hiding the default arrow and displaying my own arrow instead.
.styleSelect select {_x000D_
background: transparent;_x000D_
width: 168px;_x000D_
padding: 5px;_x000D_
font-size: 16px;_x000D_
line-height: 1;_x000D_
border: 0;_x000D_
border-radius: 0;_x000D_
height: 34px;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.styleSelect {_x000D_
width: 140px;_x000D_
height: 34px;_x000D_
overflow: hidden;_x000D_
background: url("images/downArrow.png") no-repeat right #fff;_x000D_
border: 2px solid #000;_x000D_
}
_x000D_
<div class="styleSelect">_x000D_
<select class="units">_x000D_
<option value="Metres">Metres</option>_x000D_
<option value="Feet">Feet</option>_x000D_
<option value="Fathoms">Fathoms</option>_x000D_
</select>_x000D_
</div>
_x000D_
If your base class is called Base
, and your function is called FooBar()
you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
I have put this in my partial view:
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.
So use this alert instead:
alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
"True" and "False" do not work, to disable, set to value disabled.
$('.someElement').attr('disabled', 'disabled');
To enable, remove.
$('.someElement').removeAttr('disabled');
Also, don't worry about multiple items being selected, jQuery will operate on all of them that match. If you need just one you can use many things :first, :last, nth, etc.
You are using name and not id as other mention -- remember, if you use id valid xhtml requires the ids be unique.
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes:
You can create the PDF document using PdfSharp. It is an open source .NET library.
When trying to print the document it get worse. I have looked allover for a open source way of doing it. There are some ways do do it using AcroRd32.exe but it all depends on the version, and it cannot be done without acrobat reader staying open.
I finally ended up using VintaSoftImaging.NET SDK. It costs some money but is much cheaper than the alternative and it solves the problem really easy.
var doc = new Vintasoft.Imaging.Print.ImagePrintDocument { DocumentName = @"C:\Test.pdf" };
doc.Print();
That just prints to the default printer without showing. There are several alternatives and options.
Why not just use type casting?
(char*) "test"
//For me it's the best way to look for the value of a spezific column
int seekValue = 5;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var columnValue = Convert.ToInt32(row.Cells["ColumnName"].Value);
if (columnValue == seekValue)
{
dataGridView1.CurrentCell = row.Cells[0];
}
}
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
For a number, it is tricky because if a numeric cell is empty
VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.
The following check worked for me to see if there was an actual 0 entered into the cell:
If CStr(rng.value) = "0" then
'your code here'
End If
The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:
final String extensionRemoved = filename.split("\\.")[0];
I hope this helps
one can resize an UIImage this way
image = [UIImage imageWithCGImage:[image CGImage] scale:2.0 orientation:UIImageOrientationUp];
Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):
function find_key_value($array, $key, $val)
{
foreach ($array as $item)
{
if (is_array($item) && find_key_value($item, $key, $val)) return true;
if (isset($item[$key]) && $item[$key] == $val) return true;
}
return false;
}
No one has explicitly mentioned that weightSum
is a particular XML attribute for LinearLayout
.
I believe this would be helpful to anyone who was confused at first as I was, looking for weightSum
in the ConstraintLayout
documentation.
I am using a bit of PHP to achieve the result. It's a bit rusty though. But it should work.
<?php
function pref(){
return (isset($_SERVER['HTTP_REFERER'])) ? true : '';
}
?>
<html>
<body>
<input type="hidden" id="_pref" value="<?=pref()?>">
<button type="button" id="myButton">GoBack</button>
<!-- Include jquery library -->
<script>
if (!$('#_pref').val()) {
$('#myButton').hide() // or $('#myButton').remove()
}
</script>
</body>
</html>
select *
from (select
staff_id, site_id, pay_level, date,
rank() over (partition by staff_id order by date desc) r
from owner.table
where end_enrollment_date is null
)
where r = 1
From the docs, the filter syntax that you need is as follows:
Office Files|*.doc;*.xls;*.ppt
i.e. separate the multiple extensions with a semicolon -- thus, Image Files|*.jpg;*.jpeg;*.png;...
.
Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.
Here's a nice little helper function you can use. Based on "hello world's" example above.)
One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.
// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running
// within loops.
//
// The anonymous function returns a closure, that will be executed when
// the event triggers. And since the arguments were captured, any vars
// that were sent in will be unique to the function.
function addListenerWithArgs(elem, evt, func, vars){
var f = function(ff, vv){
return (function (){
ff(vv);
});
}(func, vars);
elem.addEventListener(evt, f);
return f;
}
// Usage:
function doSomething(withThis){
console.log("withThis", withThis);
}
// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");
// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);
This can happen if your provisioning profile has expired. Another reason could be that you device date exceeds the expiry date of your provisioning profile. Please make sure that your device date is correct.
Added windows support
def which(program):
path_ext = [""];
ext_list = None
if sys.platform == "win32":
ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")]
def is_exe(fpath):
exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# search for executable under windows
if not exe:
if ext_list:
for ext in ext_list:
exe_path = "%s%s" % (fpath,ext)
if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK):
path_ext[0] = ext
return True
return False
return exe
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return "%s%s" % (program, path_ext[0])
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return "%s%s" % (exe_file, path_ext[0])
return None
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
I took Jezzipin's answer and made it so that if you are scrolled when you refresh the page, the correct size applies. Also removed some stuff that isn't necessarily needed.
function sizer() {
if($(document).scrollTop() > 0) {
$('#header_nav').stop().animate({
height:'40px'
},600);
} else {
$('#header_nav').stop().animate({
height:'100px'
},600);
}
}
$(window).scroll(function(){
sizer();
});
sizer();
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
Some of it is possible, specifically accessing subtotals:
"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)
Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/
This native way will help to convert any inputted format to the desired format.
$formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
$dateInput = '01-02-2018'; //date in above format
$formatOut = 'Y-m-d'; // Your format
$dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);
Simply type in command prompt :
set path=%PATH%;D:\xampp\mysql\bin;
Here my path started from D so I used D: , you can use C: or E:
This is going to work :
In [1]: import torch
In [2]: torch.cuda.current_device()
Out[2]: 0
In [3]: torch.cuda.device(0)
Out[3]: <torch.cuda.device at 0x7efce0b03be0>
In [4]: torch.cuda.device_count()
Out[4]: 1
In [5]: torch.cuda.get_device_name(0)
Out[5]: 'GeForce GTX 950M'
In [6]: torch.cuda.is_available()
Out[6]: True
This tells me the GPU GeForce GTX 950M
is being used by PyTorch
.
View -> Show Symbol -> uncheck Show All characters
If you do truly want the IP assigned to your emulator:
adb shell
ifconfig eth0
Which will give you something like:
eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]
On the truth, if think that you want something like this:
preg_replace('/\n+|\t+|\s+/',' ',$string);
I just got this error and it was caused by a duplicate static content MIME type in the web.config
This error was being returned only on static files - eg images, css, js files were all saying this error (text by itself, no other html or text in the response).
The way to debug this is to look in web config under static content. Here we have a json file extension loaded. This was required on IIS7 but will kill the app if used on IIS8 because json is now pre-loaded at the server level.
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
So solution is to remove any of these mimeType entries one at a time to confirm which are needed and which kill your app!
Update
Actually the best solution was provided by a commenter here. You can remove and then add, which will always work regardless of whether it is already defined or not. Like this:
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
The a == b
expression invokes A.__eq__
, since it exists. Its code includes self.value == other
. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__
to see if it knows how to compare itself to an int.
If you amend your code to show what values are being compared:
class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other
a = A()
a.value = 3
b = B()
b.value = 4
a == b
it will print:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
It worked for me by executing "python37 -m pip install openpyxl"
This will work:
setItemBackgroundResource(android.R.color.holo_red_light)
Make them display: block
in your CSS.
You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)
$form = $this->createFormBuilder()
->add('status', 'choice', array(
'choices' => array(
0 => 'Published',
1 => 'Draft'
),
'data' => 1
))
->getForm();
In this example, 'Draft' would be set as the default selected value.
Do you want to print the date in that format? This is the Python documentation: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> a = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366)
>>> print a.strftime('%Y %d %B, %M:%S%p')
>>> 2013 07 January, 31:34AM
For the timedelta:
>>> a = datetime.timedelta(0,5,41038)
>>> print '%s seconds, %s microseconds' % (a.seconds, a.microseconds)
But please notice, you should make sure it has the related value. For the above cases, it doesn't have the hours and minute values, and you should calculate from the seconds.
I'm posting this as an answer because it deserves to be it's own answer rather than a comment under a less useful answer. I find this method much better than the accepted answer since it can keep all the js in a separate file from the HTML.
Answer provided by Jamrelian in his comment under the accepted answer.
$("#myelement").on("input change", function() {
//do something
});
Just be aware of this comment by Jaime though
Just note that with this solution, in chrome you will get two calls to the handler (one per event), so if you care for that, then you need to guard against it.
As in it will fire the event when you have stopped moving the mouse, and then again when you release the mouse button.
In relation to the change
event and input
event causing the functionality to trigger twice, this is pretty much a non-issue.
If you have a function firing off on input
, it is extremely unlikely that there will be a problem when the change
event fires.
input
fires rapidly as you drag a range input slider. Worrying about one more function call firing at the end is like worrying about a single drop of water compared to the ocean of water that is the input
events.
The reason for even including the change
event at all is for the sake of browser compatibility (mainly with IE).
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
You could do it something like this:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function(){
$.ajax({
url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
data: '<any parameters you want to send as the Request body or query string>',
dataType: json,
async: true,
method: "GET"
success: function(data){
//If the REST API returned a successful response it'll be stored in data,
//just parse that field using jQuery and you're all set
var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td>' + value + '</td>';
});
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('#tblSomething').html(tblSomething);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
});
</script>
<table id = "tblSomething" class = "table table-hover"></table>
An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)
'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).
An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!
'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
From Here
as for Swift 2.2 , Xcode 7.3 (10,June,2016) :
for (index,number) in (0...10).enumerate() {
print("index \(index) , number \(number)")
}
for (index,number) in (0...10).reverse().enumerate() {
print("index \(index) , number \(number)")
}
Output :
index 0 , number 0
index 1 , number 1
index 2 , number 2
index 3 , number 3
index 4 , number 4
index 5 , number 5
index 6 , number 6
index 7 , number 7
index 8 , number 8
index 9 , number 9
index 10 , number 10
index 0 , number 10
index 1 , number 9
index 2 , number 8
index 3 , number 7
index 4 , number 6
index 5 , number 5
index 6 , number 4
index 7 , number 3
index 8 , number 2
index 9 , number 1
index 10 , number 0
Apparently match_parent
is :
ConstraintLayout
ConstraintLayout
So if you need your views to function as match_parent
, then:
ConstraintLayout
should use 0dp
match_parent
Example:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp">
<android.support.design.widget.TextInputLayout
android:id="@+id/phoneNumberInputLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.design.widget.TextInputEditText
android:id="@+id/phoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.TextInputLayout>
It took me a lot of time to figure out, but finally here is a simple way to list contents of a subfolder in S3 bucket using boto3. Hope it helps
prefix = "folderone/foldertwo/"
s3 = boto3.resource('s3')
bucket = s3.Bucket(name="bucket_name_here")
FilesNotFound = True
for obj in bucket.objects.filter(Prefix=prefix):
print('{0}:{1}'.format(bucket.name, obj.key))
FilesNotFound = False
if FilesNotFound:
print("ALERT", "No file in {0}/{1}".format(bucket, prefix))
The official naming conventions aren't that strict, they don't even 'forbid' camel case notation except for prefix (com
in your example).
But I personally would avoid upper case letters and hyphenations, even numbers. I'd choose com.stackoverflow.mypackage
like Bragboy suggested too.
(hyphenations '-' are not legal in package names)
EDIT
Interesting - the language specification has something to say about naming conventions too.
In Chapter 7.7 Unique Package Names we see examples with package names that consist of upper case letters (so CamelCase notation would be OK) and they suggest to replace hyphonation by an underscore ("mary-lou" -> "mary_lou") and prefix java keywords with an underscore ("com.example.enum" -> "com.example._enum")
Some more examples for upper case letters in package names can be found in chapter 6.8.1 Package Names.
Guava looks like a good option:
if (-e $base_path)
{
# code
}
-e
is the 'existence' operator in Perl.
You can check permissions and other attributes using the code on this page.
Try powershell's switch statement as an alternative, especially for variable assignment - multiple lines, but readable.
Example,
$WinVer = switch ( Test-Path $Env:windir\SysWOW64 ) {
$true { "64-bit" }
$false { "32-bit" }
}
"This version of Windows is $WinVer"
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
i tried that successful.
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.smoothScrollTo(0, scrollView.getHeight());
}
}, 1000);
Since MultiMarkdown was mentioned as an option in comments.
In MultiMarkdown the syntax for an internal link is simple.
For any heading in the document simply give the heading name in this format [heading][]
to create an internal link.
Read more here: MultiMarkdown-5 Cross-references.
Cross-References
An oft-requested feature was the ability to have Markdown automatically handle within-document links as easily as it handled external links. To this aim, I added the ability to interpret [Some Text][] as a cross-link, if a header named “Some Text” exists.
As an example, [Metadata][] will take you to # Metadata (or any of ## Metadata, ### Metadata, #### Metadata, ##### Metadata, ###### Metadata).
Alternatively, you can include an optional label of your choosing to help disambiguate cases where multiple headers have the same title:
### Overview [MultiMarkdownOverview] ##
This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.
If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.
In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.
You can use list comprehension on a dataframe to count frequencies of the columns as such
[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]
Breakdown:
my_series.select_dtypes(include=['O'])
Selects just the categorical data
list(my_series.select_dtypes(include=['O']).columns)
Turns the columns from above into a list
[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]
Iterates through the list above and applies value_counts() to each of the columns
Paul Dixon's answer worked brilliantly for me. To add to this, here are some things I observed for those interested in using REGEXP:
To Accomplish multiple LIKE filters with Wildcards:
SELECT * FROM fiberbox WHERE field LIKE '%1740 %'
OR field LIKE '%1938 %'
OR field LIKE '%1940 %';
Use REGEXP Alternative:
SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 |1940 ';
Values within REGEXP quotes and between the | (OR) operator are treated as wildcards. Typically, REGEXP will require wildcard expressions such as (.*)1740 (.*) to work as %1740 %.
If you need more control over placement of the wildcard, use some of these variants:
To Accomplish LIKE with Controlled Wildcard Placement:
SELECT * FROM fiberbox WHERE field LIKE '1740 %'
OR field LIKE '%1938 '
OR field LIKE '%1940 % test';
Use:
SELECT * FROM fiberbox WHERE field REGEXP '^1740 |1938 $|1940 (.*) test';
Placing ^ in front of the value indicates start of the line.
Placing $ after the value indicates end of line.
Placing (.*) behaves much like the % wildcard.
The . indicates any single character, except line breaks. Placing . inside () with * (.*) adds a repeating pattern indicating any number of characters till end of line.
There are more efficient ways to narrow down specific matches, but that requires more review of Regular Expressions. NOTE: Not all regex patterns appear to work in MySQL statements. You'll need to test your patterns and see what works.
Finally, To Accomplish Multiple LIKE and NOT LIKE filters:
SELECT * FROM fiberbox WHERE field LIKE '%1740 %'
OR field LIKE '%1938 %'
OR field NOT LIKE '%1940 %'
OR field NOT LIKE 'test %'
OR field = '9999';
Use REGEXP Alternative:
SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 |^9999$'
OR field NOT REGEXP '1940 |^test ';
OR Mixed Alternative:
SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 '
OR field NOT REGEXP '1940 |^test '
OR field NOT LIKE 'test %'
OR field = '9999';
Notice I separated the NOT set in a separate WHERE filter. I experimented with using negating patterns, forward looking patterns, and so on. However, these expressions did not appear to yield the desired results. In the first example above, I use ^9999$ to indicate exact match. This allows you to add specific matches with wildcard matches in the same expression. However, you can also mix these types of statements as you can see in the second example listed.
Regarding performance, I ran some minor tests against an existing table and found no differences between my variations. However, I imagine performance could be an issue with bigger databases, larger fields, greater record counts, and more complex filters.
As always, use logic above as it makes sense.
If you want to learn more about regular expressions, I recommend www.regular-expressions.info as a good reference site.
I wanted to add a method which I think was simplest of all.
Simply right click the pfx file, click "Install" follow the wizard, and add it to a store (I added to the Personal store).
In start menu type certmgr.msc and go to CertManager program.
Find your pfx certificate (tabs at top are the various stores), click the export button and follow the wizard (there is an option to export as .CER)
Essentially it does the same thing as Andrew's answer, but it avoids using Windows Management Console (goes straight to the import/export).
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n)
is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange()
was renamed to range()
- if you want a list, you have to specifically request it via list(range(n))
.
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
On multi-server environment, this error likely occurs when session expires and another instance of an application is resorted with same session id and machine key but on a different server. At first, each server produce its own machine key which later is associated with a single instance of an application. When session expires and current server is busy, the application is redirected like, via load balancer to a more operational server. In my case I run same app from multiple servers, the error message:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm
Defining the machine code under in web.config have solve the problem. But instead of using 3rd party sites for code generation which might be corrupted, please run this from your command shell: Based on microsoft solution 1a, https://support.microsoft.com/en-us/kb/2915218#AppendixA
# Generates a <machineKey> element that can be copied + pasted into a Web.config file.
function Generate-MachineKey {
[CmdletBinding()]
param (
[ValidateSet("AES", "DES", "3DES")]
[string]$decryptionAlgorithm = 'AES',
[ValidateSet("MD5", "SHA1", "HMACSHA256", "HMACSHA384", "HMACSHA512")]
[string]$validationAlgorithm = 'HMACSHA256'
)
process {
function BinaryToHex {
[CmdLetBinding()]
param($bytes)
process {
$builder = new-object System.Text.StringBuilder
foreach ($b in $bytes) {
$builder = $builder.AppendFormat([System.Globalization.CultureInfo]::InvariantCulture, "{0:X2}", $b)
}
$builder
}
}
switch ($decryptionAlgorithm) {
"AES" { $decryptionObject = new-object System.Security.Cryptography.AesCryptoServiceProvider }
"DES" { $decryptionObject = new-object System.Security.Cryptography.DESCryptoServiceProvider }
"3DES" { $decryptionObject = new-object System.Security.Cryptography.TripleDESCryptoServiceProvider }
}
$decryptionObject.GenerateKey()
$decryptionKey = BinaryToHex($decryptionObject.Key)
$decryptionObject.Dispose()
switch ($validationAlgorithm) {
"MD5" { $validationObject = new-object System.Security.Cryptography.HMACMD5 }
"SHA1" { $validationObject = new-object System.Security.Cryptography.HMACSHA1 }
"HMACSHA256" { $validationObject = new-object System.Security.Cryptography.HMACSHA256 }
"HMACSHA385" { $validationObject = new-object System.Security.Cryptography.HMACSHA384 }
"HMACSHA512" { $validationObject = new-object System.Security.Cryptography.HMACSHA512 }
}
$validationKey = BinaryToHex($validationObject.Key)
$validationObject.Dispose()
[string]::Format([System.Globalization.CultureInfo]::InvariantCulture,
"<machineKey decryption=`"{0}`" decryptionKey=`"{1}`" validation=`"{2}`" validationKey=`"{3}`" />",
$decryptionAlgorithm.ToUpperInvariant(), $decryptionKey,
$validationAlgorithm.ToUpperInvariant(), $validationKey)
}
}
Then:
Generate-MachineKey
Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="HMACSHA256" validationKey="..." />
Generate-MachineKey -validation sha1
Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="SHA1" validationKey="..." />
try to implement Application_AuthenticateRequest
instead of Application_Start
.
this method has an instance for HttpContext.Current
, unlike Application_Start
(which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current
object yet).
hope that helps.
I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.
If you make an AJAX request with fetch
, the response isn't shown unless it's read with .text()
, .json()
, etc.
If you just do:
r = fetch("/some-path");
the response won't be shown in dev tools.
It shows up after you run:
r.then(r => r.text())
I had the same issue and I fixed removing the library that were unnecessary
compile fileTree(dir: 'libs', include: ['*.jar'])
I removed that library and I could run the project without any problem.
According to this article, != performs faster
The particular format for strptime
:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)
When the game starts:
long tStart = System.currentTimeMillis();
When the game ends:
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
You could also try,
OIFS=$IFS;
IFS="\t";
animals=`cat animals.txt`
animalArray=$animals;
for animal in $animalArray
do
echo $animal
done
IFS=$OIFS;
If table_2
is empty, then try the following insert statement:
insert into table_2 (itemid,location1)
select itemid,quantity from table_1 where locationid=1
If table_2
already contains the itemid
values, then try this update statement:
update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)
install https://www.microsoft.com/en-us/download/details.aspx?id=49978 Microsoft .NET Framework 4.6.1 Developer Pack and add this line of code in Web.config file
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</assemblies>
</compilation>
yes, but you'll have to hack it a little yourself. I've written a filter that replaces latex tags $\some\inline\latex$
or $$\some\equation$$
with appropriate image tags to a mimetex.cgi script. It took all of 5 minutes.
Warning: spectacularly ugly...
#!/usr/bin/env python
import sys, markdown,re
MIMETEX_LOC="http://some.server.com/cgi-bin/mimetex.cgi"
def sanitizeLatex(text):
return re.sub(r"\\",r"%5C", text)
def wrapLatexBlock(text):
return '<img alt="equation" class="block" src="%s?%s"></img>'%(MIMETEX_LOC,text)
def wrapLatexInline(text):
return '<img alt="equation" class="inline" src="%s?%s"></img>'%(MIMETEX_LOC,text)
def prepLatexBlock(matchobj):
return wrapLatexBlock(sanitizeLatex(matchobj.group()[2:-2]))
def prepLatexInline(matchobj):
return wrapLatexInline(sanitizeLatex(matchobj.group()[1:-1]))
if __name__ == "__main__":
# initialise markdown
md=markdown.Markdown()
raw_md=open(sys.argv[1],"r").read()
##
# deal with embedded latex
##
raw_md=re.sub(r'\$\$(.*?)\$\$',prepLatexBlock, raw_md)
raw_md=re.sub(r'\$(.*?)\$',prepLatexInline, raw_md)
##
# once latex is parsed, convert md to html
##
main_html=md.convert(raw_md)
# hey presto!
print(main_html)
Of course, you have to define the appropriate css yourself for .block and .inline images...
The only difference : synchronized blocks allows granular locking unlike synchronized method
Basically synchronized
block or methods have been used to write thread safe code by avoiding memory inconsistency errors.
This question is very old and many things have been changed during last 7 years. New programming constructs have been introduced for thread safety.
You can achieve thread safety by using advanced concurrency API instead of synchronied
blocks. This documentation page provides good programming constructs to achieve thread safety.
Lock Objects support locking idioms that simplify many concurrent applications.
Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.
ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Better replacement for synchronized is ReentrantLock, which uses Lock
API
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
Example with locks:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.
Refer to this related question too:
While others have pointed out it is not possible to override constructors syntactically, I would like to also point out, it would be conceptually bad to do so. Say the superclass is a dog object, and the subclass is a Husky object. The dog object has properties such as "4 legs", "sharp nose", if "override" means erasing dog and replacing it with Husky then Husky would be missing these properties and be a broken object. Husky never had those properties and simply inherited them from dog. On the other hand, if you intend to give Husky everything that dog has, then conceptually you could "override" dog with Husky, but there would be no point in creating a class that is the same as dog, it's not practically an inherited class but a complete replacement.
Just for fun, another alternative using lookaheads:
^(?=\d*[1-9])\d+$
As many digits as you want, but at least one must be [1-9]
.
I think this error occurs due to the mismatch with number of columns in table definition and number of columns in the insert query. Also the length of the column is omitted with the entered value. So just review the table definition to resolve this issue
Simplest version, assuming you're working on the same branch that the file you want is on:
git checkout path/to/file
.
I do this so often that I've got an alias set to gc='git checkout'
.
You can also try this on big dictionaries for multithreaded processing.
dictionary
.AsParallel()
.ForAll(pair =>
{
// Process pair.Key and pair.Value here
});
Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.
A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:
Our reusable, serializable object:
[Serializable]
public class UserProfileSessionData
{
public int UserId { get; set; }
public string EmailAddress { get; set; }
public string FullName { get; set; }
}
Use case:
public class LoginController : Controller {
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
var profileData = new UserProfileSessionData {
UserId = model.UserId,
EmailAddress = model.EmailAddress,
FullName = model.FullName
}
this.Session["UserProfile"] = profileData;
}
}
public ActionResult LoggedInStatusMessage()
{
var profileData = this.Session["UserProfile"] as UserProfileSessionData;
/* From here you could output profileData.FullName to a view and
save yourself unnecessary database calls */
}
}
Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.
Inject your session object using Dependency Injection
In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).
public class WebsiteRegistry : Registry
{
public WebsiteRegistry()
{
this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());
}
public static IUserProfileSessionData GetUserProfileFromSession()
{
var session = HttpContext.Current.Session;
if (session["UserProfile"] != null)
{
return session["UserProfile"] as IUserProfileSessionData;
}
/* Create new empty session object */
session["UserProfile"] = new UserProfileSessionData();
return session["UserProfile"] as IUserProfileSessionData;
}
}
You would then register this in your Global.asax.cs
file.
For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.
A word of warning:
It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.
It's also recommended to not store any sensitive data in them (passwords, etc).
Have a look at this jsfiddle.
The idea is to filter rows with function which will loop through words.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
EDIT: Note that case insensitive filtering cannot be achieved using :contains()
selector but luckily there's text()
function so filter string should be uppercased and condition changed to if ($t.text().toUpperCase().indexOf(data[d]) > -1)
. Look at this jsfiddle.
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH
clause. See this article for one example of translating a CONNECT BY
into a WITH
(technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.
Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:
CREATE TABLE emp(empid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(10),
salary DECIMAL(9, 2),
mgrid INTEGER);
where mgrid
references an employee's manager's empid
, the task is, get the names of everybody who reports directly or indirectly to Joan
. In Oracle, that's a simple CONNECT
:
SELECT name
FROM emp
START WITH name = 'Joan'
CONNECT BY PRIOR empid = mgrid
In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
WITH n(empid, name) AS
(SELECT empid, name
FROM emp
WHERE name = 'Joan'
UNION ALL
SELECT nplus1.empid, nplus1.name
FROM emp as nplus1, n
WHERE n.empid = nplus1.mgrid)
SELECT name FROM n
Oracle's START WITH
clause becomes the first nested SELECT
, the base case of the recursion, to be UNION
ed with the recursive part which is just another SELECT
.
SQL Server's specific flavor of WITH
is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.
extend class to AppCompatActivity
instead of Activity
What happens, if you do this way:-
$('#new_user_form input, #new_user_form select').each(function(key, value) {
Refer LIVE DEMO
you can write the function in a separate file (say common-functions.php) and include it wherever needed.
function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}
You can include common-functions.php in another file as below.
include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);
You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.
I agree with @ZombieSheep. Just one more thing - I generally don't think that databases actually need be portable because you miss all the features your DBMS vendor provides. I think that migrating to another database would be the last thing one would consider. Just my $.02
Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff
You can keep your initial linear layout by nesting the relative layout within the linear layout:
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="welcome"
android:id="@+id/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:text="submit"
android:id="@+id/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true">
</Button>
<EditText android:id="@+id/EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/Button"
android:layout_alignParentBottom="true">
</EditText>
</RelativeLayout>
</LinearLayout>
To detect MSIE (from version 6 to 11) quickly:
if(navigator.userAgent.indexOf('MSIE')!==-1
|| navigator.appVersion.indexOf('Trident/') > -1){
/* Microsoft Internet Explorer detected in. */
}
I just reinstalled it with pip.
sudo pip uninstall virtualenvwrapper
sudo pip install virtualenvwrapper
And this time it put it in /usr/local/bin.
On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress
, write the name of your installed instance (by default it's .\SQLEXPRESS
for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI
.
The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.
http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm
Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.
I put the data starting on row 5:
Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.
That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.
root@APPLICATIOSERVER:/var/www/html# php connectiontest.php 61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#
Post declaring the proxy settings in the php script file issue has been fixed.
$proxy = '10.172.123.1:80'; curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port
1 - 8 = -7
9 - 15 = -6
16 - 100 = -84
You have:
case -7:
...
break;
case -6:
...
break;
case -84:
...
break;
Either use:
case 1:
case 2:
case 3:
etc, or (perhaps more readable) use:
if(age >= 1 && age <= 8) {
...
} else if (age >= 9 && age <= 15) {
...
} else if (age >= 16 && age <= 100) {
...
} else {
...
}
etc
just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button).
public class Matrix
{
public static void main(String[] args)
{
double Matrix [] []={
{0*1,0*2,0*3,0*4),
{0*1,1*1,2*1,3*1),
{0*2,1*2,2*2,3*2),
{0*3,1*3,2*3,3*3)
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
System.out.print(Matrix [i] [j] + " ");
System.out.println();
}
}
}
Bash does not support multidimensional arrays, nor hashes, and it seems that you want a hash that values are arrays. This solution is not very beautiful, a solution with an xml file should be better :
array=('d1=(v1 v2 v3)' 'd2=(v1 v2 v3)')
for elt in "${array[@]}";do eval $elt;done
echo "d1 ${#d1[@]} ${d1[@]}"
echo "d2 ${#d2[@]} ${d2[@]}"
EDIT: this answer is quite old, since since bash 4 supports hash tables, see also this answer for a solution without eval.
You can overflow:hidden
to your #content
. Write like this:
#content
{
min-width:700px;
margin-left:10px;
overflow:hidden;
background-color:AppWorkspace;
}
Check this http://jsfiddle.net/Zvt2j/1/
The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:
int x = 0; //x is 0
int y = ++x; //x is 1 and y is 1
If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:
int x = 0; //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:
while (x < 5) //evaluates conditional statement
{
//some code
++x; //increments x
}
or
while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
//some code
}
You can also do this while indexing arrays and such:
int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678; //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
Etc, etc...
Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.
import unicodedata, re, itertools, sys
all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
For Python2
import unicodedata, re, sys
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:
Cc
(control): 65Cf
(format): 161Cs
(surrogate): 2048Co
(private-use): 137468Cn
(unassigned): 836601Edit Adding suggestions from the comments.
Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.
guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
return //Do Nothing
}
//Do something with picker
This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader
query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader()
when you have to call a method that is missing a ClassLoader
parameter.
When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()
). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.
When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader
as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader()
.
Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader()
, sun.misc.VM.latestUserDefinedLoader()
, or sun.reflect.Reflection.getCallerClass()
it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader()
exists only because whoever designed the ObjectInputStream
API forgot to accept the ClassLoader
as a parameter, and this mistake has haunted the Java community to this day.
That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader
(which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null
), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH
) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.
When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader
before the API call (and resetting it afterwards):
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
// call some API that uses reflection without taking ClassLoader param
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
>>> a = [0] * 10
>>> a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
I am using Ubuntu 11.10- 32 bit with ruby 1.9.3p194, rails 3.2.3, gem 1.8.24. Was receiving the same Javascript error while running "script/rails console".
However doing a "sudo apt-get install nodejs" solved my issue.
You can also use the following syntax:-
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
From here
Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.
If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".
Java 8 way to do this:
List<Integer> list = Arrays.asList(1,2,3,4);
Comparator<Integer> comparator = Integer::compare;
list.stream().sorted(comparator.reversed()).forEach(System.out::println);
Curious.....at least on Windows (my npm is 3.something) I needed to do:
"dependencies": {
"body-parser": "^1.17.1",
"module1": "../module1",
"module2": "../module2",
When I did an npm install ../module1 --save
it resulted in absolute paths and not relative per the documentation.
I messed around a little more and determined that ../xxx
was sufficient.
Specifically, I have the local node modules checked out to say d:\build\module1, d:\build\module2 and my node project (application) in d:\build\nodeApp.
To 'install', I:
d:\build\module1> rmdir "./node_modules" /q /s && npm install
d:\build\module2> rmdir "./node_modules" /q /s && npm install
d:\build\nodeApp> rmdir "./node_modules" /q /s && npm install
module1's package.json has a dependency of "module2": "../module2"; module2 has no local dependency; nodeApp has dependencies "module1": "../module1" and "module2": "../module2".
Not sure if this only works for me since all 3 folders (module1, module2 and nodeApp) sit on that same level.......
Because QuerySets implement the Python __or__
operator (|
), or union, it just works. As you'd expect, the |
binary operator returns a QuerySet
so order_by()
, .distinct()
, and other queryset filters can be tacked on to the end.
combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')
Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.
Is there a standard way in C++ to show the binary representation in memory of a number [...]?
No. There's no std::bin
, like std::hex
or std::dec
, but it's not hard to output a number binary yourself:
You output the left-most bit by masking all the others, left-shift, and repeat that for all the bits you have.
(The number of bits in a type is sizeof(T) * CHAR_BIT
.)
I think CAST(ROUND(yourColumn,2) as varchar)
should do the job.
But why do you want to do this presentational formatting in T-SQL?
My solution:_x000D_
_x000D_
ul {_x000D_
line-height: 1.3 !important;_x000D_
li {_x000D_
font-size: x-large;_x000D_
position: relative;_x000D_
&:before {_x000D_
content: '';_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 5px;_x000D_
left: -25px;_x000D_
height: 23px;_x000D_
width: 23px;_x000D_
background-image: url(../img/list-char.png) !important;_x000D_
background-size: 23px;_x000D_
background-repeat: no-repeat;_x000D_
}_x000D_
}_x000D_
}
_x000D_
You are repeating the y,m,d
.
Instead of
gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());
You should use it like
gmdate('Y-m-d h:m:s \G\M\T', time());
Try the fat-jar extension. It will include all external jars inside the jar.
I also got the same error but I noticed that I had typed in Foreign*k*ey and not Foreign*K*ey,(capital K) if there is a newbie out there, check out spelling and caps.
DisplayMetrics dimension = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dimension);
int width = dimension.widthPixels;
int height = dimension.heightPixels;
These solutions totally make sense. Unfortunately, neither worked for me as expected. Instead of trying to hassle with it, I went with a work around:
select * from information_schema.columns
where replace(table_name,'_','!') not like '%!%'
order by table_name
I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand &
is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R
. So the acc parameter ends when it reaches the ampersand character.
That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.
Try HostingEnvironment.MapPath
, which is static
.
See this SO question for confirmation that HostingEnvironment.MapPath
returns the same value as Server.MapPath
: What is the difference between Server.MapPath and HostingEnvironment.MapPath?
for (let key in data) {
let value = data[key];
for (i = 0; i < value.length; i++) {
console.log(value[i].msgFrom);
console.log(value[i].msgBody);
}
}
Oh, the many, many ways...
String concatenation:
plot.savefig('hanning' + str(num) + '.pdf')
Conversion Specifier:
plot.savefig('hanning%s.pdf' % num)
Using local variable names:
plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick
Using str.format()
:
plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way
Using f-strings:
plot.savefig(f'hanning{num}.pdf') # added in Python 3.6
Using string.Template
:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
To bring more prominence to the useful comment by @johanvdw:
If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile
file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"
somewhere in the file.
When Cygwin starts, it'll search directories in PATH and this one for executable files to run.
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
The problem is probably that you forgot to close the program and that you instead have the program running in the background.
Find the console window where the exe file program is running, and close it by clicking the X in the upper right corner. Then try to recompile the program. In my case this solved the problem.
I know this posting is old, but I am answering for the other people like me who find this through the search engines.
Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.
Try marginTop
in place of margin-top
, eg:
$("#ActionBox").css("marginTop", foo);
Actually I don't see any nulls:
given:
static void Main()
{
string[] testArray = new string[]
{
"aa",
"ab",
"ac",
"ad",
"ab",
"af"
};
Array.Sort(testArray, StringComparer.InvariantCulture);
Array.ForEach(testArray, x => Console.WriteLine(x));
}
I obtained:
If building a project through a build system (Maven, Gradle etc..) works but IntelliJ show Invalid target release
error, then do the following,
Close IntelliJ
Go to the directory of the project
Delete the .idea/ directory
Start IntelliJ with the project's directory
This will re-create the .idea/ directory and will no longer show the error.
NOTE: Any repository specific IntelliJ settings that you have added would be deleted when the .idea/ directory is deleted and they will be re-created with the defaults.
One of the aspects missing from some of the other answers here is a way to use enums with type hinting.
If you define your enum as a set of constants in an abstract class, e.g.
abstract class ShirtSize {
public const SMALL = 1;
public const MEDIUM = 2;
public const LARGE = 3;
}
then you can't type hint it in a function parameter - for one, because it's not instantiable, but also because the type of ShirtSize::SMALL
is int
, not ShirtSize
.
That's why native enums in PHP would be so much better than anything we can come up with. However, we can approximate an enum by keeping a private property which represents the value of the enum, and then restricting the initialization of this property to our predefined constants. To prevent the enum from being instantiated arbitrarily (without the overhead of type-checking a whitelist), we make the constructor private.
class ShirtSize {
private $size;
private function __construct ($size) {
$this->size = $size;
}
public function equals (ShirtSize $s) {
return $this->size === $s->size;
}
public static function SMALL () { return new self(1); }
public static function MEDIUM () { return new self(2); }
public static function LARGE () { return new self(3); }
}
Then we can use ShirtSize
like this:
function sizeIsAvailable ($productId, ShirtSize $size) {
// business magic
}
if(sizeIsAvailable($_GET["id"], ShirtSize::LARGE())) {
echo "Available";
} else {
echo "Out of stock.";
}
$s2 = ShirtSize::SMALL();
$s3 = ShirtSize::MEDIUM();
echo $s2->equals($s3) ? "SMALL == MEDIUM" : "SMALL != MEDIUM";
This way, the biggest difference from the user's perspective is that you have to tack on a ()
on the constant's name.
One downside though is that ===
(which compares object equality) will return false when ==
returns true. For that reason, it's best to provide an equals
method, so that users don't have to remember to use ==
and not ===
to compare two enum values.
EDIT: A couple of the existing answers are very similar, particularly: https://stackoverflow.com/a/25526473/2407870.
The -L
option to ls
will accomplish what you want. It dereferences symbolic links.
So your command would be:
ls -LR
You can also accomplish this with
find -follow
The -follow
option directs find to follow symbolic links to directories.
On Mac OS X use
find -L
as -follow
has been deprecated.
After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.
Dim intChoice As Integer
Dim strPath As String
' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show
' Get back the user option
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String
Set fsoStream = FSO.OpenTextFile(strPath)
Do Until fsoStream.AtEndOfStream = True
strLine = fsoStream.ReadLine
' ... do your work ...
Loop
fsoStream.Close
Set FSO = Nothing
Hope it help!
Best regards
Fabio
You can use ObjectMapper.convertValue()
, either value by value or even for the whole list. But you need to know the type to convert to:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });
this is functionally same as if you did:
byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);
but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.
From @Jon Skeet comment, really the String
value is "null"
. Following code solved it
if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))
To close all splits, I usually place the cursor in the window that shall be the on-ly visible one and then do :on
which makes the current window the on-ly visible window. Nice mnemonic to remember.
Edit: :help :on
showed me that these commands are the same:
Each of these four closes all windows except the active one.
#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif
Make sure you have the checkbox to define DEBUG checked in your build properties.
The window.navigator.platform property is not spoofed when the userAgent string is changed. I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel.
The property is also read-only
I could came up with the following table
Mac Computers
Mac68K
Macintosh 68K system.
MacPPC
Macintosh PowerPC system.
MacIntel
Macintosh Intel system.iOS Devices
iPhone
iPhone.
iPod
iPod Touch.
iPad
iPad.
Modern macs returns navigator.platform == "MacIntel"
but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM
or MacQuantum
in future.
var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;
To include iOS that also use the "left side"
var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);
var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;_x000D_
var is_iPhone = navigator.platform == "iPhone";_x000D_
var is_iPod = navigator.platform == "iPod";_x000D_
var is_iPad = navigator.platform == "iPad";_x000D_
_x000D_
/* Output */_x000D_
var out = document.getElementById('out');_x000D_
if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";_x000D_
if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";_x000D_
if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";_x000D_
if (is_iPhone) out.innerHTML += "This is an iPhone!";_x000D_
if (is_iPod) out.innerHTML += "This is an iPod Touch!";_x000D_
if (is_iPad) out.innerHTML += "This is an iPad!";_x000D_
out.innerHTML += "\nPlatform: " + navigator.platform;
_x000D_
<pre id="out"></pre>
_x000D_
Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right.
setTimeout(test, 1000); //delay for demonstration_x000D_
_x000D_
function test() {_x000D_
_x000D_
var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
if (mac) {_x000D_
document.getElementById('close').classList.add("left");_x000D_
}_x000D_
}
_x000D_
#window {_x000D_
position: absolute;_x000D_
margin: 1em;_x000D_
width: 300px;_x000D_
padding: 10px;_x000D_
border: 1px solid gray;_x000D_
background-color: #DDD;_x000D_
text-align: center;_x000D_
box-shadow: 0px 1px 3px #000;_x000D_
}_x000D_
#close {_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
margin: -12px;_x000D_
box-shadow: 0px 1px 3px #000;_x000D_
background-color: #000;_x000D_
border: 2px solid #FFF;_x000D_
border-radius: 22px;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
font: 14px"Comic Sans MS", Monaco;_x000D_
}_x000D_
#close.left{_x000D_
left: 0px;_x000D_
}
_x000D_
<div id="window">_x000D_
<div id="close">x</div>_x000D_
<p>Hello!</p>_x000D_
<p>If the "close button" change to the left side</p>_x000D_
<p>you're on a Mac like system!</p>_x000D_
</div>
_x000D_
http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/
If the resource is showing and is a view, you can also capture it. Like a screenshot:
View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
This actually grabs the whole layout but you can alter as you wish.
You can also init multiple values if your selectbox is a multipl:
$('#selectBox').val(['A', 'B', 'C']);
This is how I make it work.
My Environment:
Angular CLI Global : 6.0.0, Local: 1.7.4, Angular: 5.2, Typescript 2.5.3
Note: To enable
ng Update
you need to install Angular CLI 6.0 firstnpm install -g @angular/cli or npm install @angular/cli
ng update //update Angular Package core/common/complier... to 6.0.0
ng update @angular/cli //change angular-cli.json to angular.json
optional if you have angular-material 5.4.2, ngx-translate 9.1.1, ng-bootstrap/ng-bootstrap 1.1.1:
ng update @angular/material //upgrade to 6.0.1
npm install @ngx-translate/[email protected] --save //upgrade ngX translate to 10.0.1 for Angular 6
5 npm install --save @ng-bootstrap/[email protected] //for ng-bootstrap
If you use Observable and get the error:
ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'. node_modules/rxjs/observable/of.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/observable/of'.
Change: import { Observable } from "rxjs/Observable"; import { of } from 'rxjs/observable/of';
To
import { Observable, of } from "rxjs";
Angular CLI issue: https://github.com/angular/angular-cli/issues/10621
Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.
As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:
To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash
and the command to export
. You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources. Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.
The result is this incredibly helpful listing of current environment variables used for building:
C++ Standard has: It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).
The code to illustrate this rule:
#include <iostream>
using namespace std;
class X {
public:
X()
{
cout << "constructor" << endl;
}
~X()
{
cout << "destructor" << endl;
}
};
template <class type>
void ill_formed()
{
goto lx;
ly:
type a;
lx:
goto ly;
}
template <class type>
void ok()
{
ly:
type a;
lx:
goto ly;
}
void test_class()
{
ok<X>();
// compile error
ill_formed<X>();
}
void test_scalar()
{
ok<int>();
ill_formed<int>();
}
int main(int argc, const char *argv[])
{
return 0;
}
The code to show the initializer effect:
#include <iostream>
using namespace std;
int test1()
{
int i = 0;
// There jumps fo "case 1" and "case 2"
switch(i) {
case 1:
// Compile error because of the initializer
int r = 1;
break;
case 2:
break;
};
}
void test2()
{
int i = 2;
switch(i) {
case 1:
int r;
r= 1;
break;
case 2:
cout << "r: " << r << endl;
break;
};
}
int main(int argc, const char *argv[])
{
test1();
test2();
return 0;
}
The return type of a procedure is int.
You can also return result sets (as your code currently does) (okay, you can also send messages, which are strings)
Those are the only "returns" you can make. Whilst you can add table-valued parameters to a procedure (see BOL), they're input only.
Edit:
(Or as another poster mentioned, you could also use a Table Valued Function, rather than a procedure)
Well In my parent directory I see:
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Unmerged paths:
(use "git reset HEAD <file>..." to unstage)
(use "git add <file>..." to mark resolution)
So I just did this
git reset HEAD linux
first use this:
LayoutInflater inflater = (LayoutInflater) Read_file.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Read file is current activity in which you want your context.
View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));
then you can use this to find any element in layout.
ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);
For anyone using lodash, it is extremely easy to debounce any function:
changed = _.debounce(function() {
console.log("name changed!");
}, 400);
then just throw something like this into your template:
<(input)="changed($event.target.value)" />
You can use
t1<- t1[-4:-6,-7:-9]
or
t1 <- t1[-(4:6), -(7:9)]
or
t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]
You can pass vectors
to select rows/columns
to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns
.
> t1 <- array(1:20, dim=c(10,10));
> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 2 12 2 12 2 12
[2,] 3 13 3 13 3 13
[3,] 5 15 5 15 5 15
[4,] 8 18 8 18 8 18
[5,] 10 20 10 20 10 20
The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.
If someone is using frameworks like scrapy
the you will have to use /html/body//a[contains(@href,'com')][2]/@href
along with get() like this:
response.xpath('//a[contains(@href,'com')][2]/@href').get()
The two options I use are:
list1.AddRange(list2);
or
list1.Concat(list2);
However I noticed as I used that when using the AddRange
method with a recursive function, that calls itself very often I got an SystemOutOfMemoryException because the maximum number of dimensions was reached.
(Message Google Translated)
The array dimensions exceeded the supported range.
Using Concat
solved that issue.
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
in addition,if you try to use CustomActionBarTheme,make sure there is
<application android:theme="@style/CustomActionBarTheme" ... />
in AndroidManifest.xml
not
<application android:theme="@android:style/CustomActionBarTheme" ... />
For a backgrounder, there are 2 ways to use a ComboBox/ListBox
1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.
2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue
For 2) you will need a list of countries first
// not tested, schematic:
List<Country> countries = ...;
...; // fill
comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";
And then in the SelectionChanged,
if (comboBox1.Selecteditem != null)
{
comboBox2.DataSource=comboBox1.SelectedValue;
}
Just type javac
. If it is installed you get usage information, otherwise it would just ask if you would like to install Java.
brute force (and only tested on an Oracle system, but I think this is pretty standard):
select distinct usr_id from users where user_id in (
select user_id from (
Select user_id, Count(User_Id) As Cc
From users
GROUP BY user_id
) Where Cc =3
)
and ancestry in ('England', 'France', 'Germany')
;
edit: I like @HuckIt's answer even better.
the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.
if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.
If you use AppCompat v7, v21
getSupportActionBar().setDisplayShowTitleEnabled(false);
You can do it like below -
df <- data.frame(a=1:4, b=5:8, c=9:12)
df['d'] <- seq(10,13)
df <- df[,c('a','b','d','c')]
Please take into account that sorting the array will only be faster that looping up to certain size of the array. If your array is small (and it will be like that any time) then your solution is perfectly fine. But if it might get too large you should use a conditional to use the sort approach when the array is small, and the normal iteration when it is too large
VS 2019 Version 16.4.4 Solution targeting .NET Core 3.1
After having tried almost all the solutions proposed here, I closed VS. When I reopened it, after some seconds all was back to be OK...
Another way to do this is to use the numpy matrix
class (rather than a numpy array) and the I
attribute. For example:
>>> m = np.matrix([[2,3],[4,5]])
>>> m.I
matrix([[-2.5, 1.5],
[ 2. , -1. ]])
CHARINDEX
will return 0
if no spaces are in the string and then you look for a substring of -1
length.
You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.
SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)
You can use this:
function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('video'));
This is very nice:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7)
.
There are 10^7 equiprobable (if java.util.Random
is not broken) distinct values so uniqueness may be a concern.
It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.
create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
-- just in case it came in with 0x prefix or dashes...
set @s = replace(replace(@s,'0x',''),'-','')
-- inject dashes in the right places
set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
return cast(@s as uniqueidentifier)
end
well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor
function. You can get current theme with getTheme()
.
This will do the trick in fragment, you can replace getActivity()
with getBaseContext()
, yourContext
, etc which hold your current context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
*p.s : color is deprecated in M, but drawable is deprecated in L
If you want a ksh only method that is as fast as "test", you can do something like:
contains() # haystack needle
{
haystack=${1/$2/}
if [ ${#haystack} -ne ${#1} ] ; then
return 1
fi
return 0
}
It works by deleting the needle in the haystack and then comparing the string length of old and new haystacks.
As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps
of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webapp
directory.
Now, if Tomcat is installed and running on bilgin.ath.cx
(as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80
on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk
?, mod_proxy
?). You should either give us more details or discuss this with your hosting provider.
Update: As expected, the bilgin.ath.cx
is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties
file to configure the workers and the httpd.conf
for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount
directive in Apache httpd.conf
for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf
will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.
1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)
If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
In this case, $preview
will be "Knowledge is a natural right of every human being"
.
Live code example: http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713
Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:
def sqlite_insert(conn, table, row):
cols = ', '.join('"{}"'.format(col) for col in row.keys())
vals = ', '.join(':{}'.format(col) for col in row.keys())
sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
conn.cursor().execute(sql, row)
conn.commit()
Example of use:
sqlite_insert(conn, 'stocks', {
'created_at': '2016-04-17',
'type': 'BUY',
'amount': 500,
'price': 45.00})
Note, that table name and column names should be validated beforehand.
The Transact-SQL control-of-flow language keywords are:
BEGIN
...END
BREAK
CONTINUE
GOTO
label
IF
...ELSE
RETURN
THROW
TRY
...CATCH
WAITFOR
WHILE
You can do these conversions also with the .NET Framework:
JSON to XML: by using System.Runtime.Serialization.Json
var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));
XML to JSON: by using System.Web.Script.Serialization
var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));
private static Dictionary<string, object> GetXmlData(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
It's also important to set the necessary headers in the express response. These are those which worked for me:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', yourExactHostname);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
DELETE FROM table WHERE ID NOT IN
(SELECT MAX(ID) ID FROM table)
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
Chrome and Opera browsers do not support thead {display: table-header-group;}
but rest of others support properly..
In my case problem was at context.xml file of my project.
The following from context.xml causes the java.lang.AbstractMethodError, since we didn't show the datasource factory.
<Resource name="jdbc/myoracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@(DESCRIPTION = ... "
username="****" password="****" maxActive="10" maxIdle="1"
maxWait="-1" removeAbandoned="true"/>
Simpy adding factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" solved the issue:
<Resource name="jdbc/myoracle"
auth="Container"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@(DESCRIPTION = ... "
username="****" password="****" maxActive="10" maxIdle="1"
maxWait="-1" removeAbandoned="true"/>
To make sure I reproduced the issue several times by removing factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" from Resource
and, just to add to the pile, here's an object you can use
import sys
class ProgressBar(object):
DEFAULT_BAR_LENGTH = 65
DEFAULT_CHAR_ON = '='
DEFAULT_CHAR_OFF = ' '
def __init__(self, end, start=0):
self.end = end
self.start = start
self._barLength = self.__class__.DEFAULT_BAR_LENGTH
self.setLevel(self.start)
self._plotted = False
def setLevel(self, level):
self._level = level
if level < self.start: self._level = self.start
if level > self.end: self._level = self.end
self._ratio = float(self._level - self.start) / float(self.end - self.start)
self._levelChars = int(self._ratio * self._barLength)
def plotProgress(self):
sys.stdout.write("\r %3i%% [%s%s]" %(
int(self._ratio * 100.0),
self.__class__.DEFAULT_CHAR_ON * int(self._levelChars),
self.__class__.DEFAULT_CHAR_OFF * int(self._barLength - self._levelChars),
))
sys.stdout.flush()
self._plotted = True
def setAndPlot(self, level):
oldChars = self._levelChars
self.setLevel(level)
if (not self._plotted) or (oldChars != self._levelChars):
self.plotProgress()
def __add__(self, other):
assert type(other) in [float, int], "can only add a number"
self.setAndPlot(self._level + other)
return self
def __sub__(self, other):
return self.__add__(-other)
def __iadd__(self, other):
return self.__add__(other)
def __isub__(self, other):
return self.__add__(-other)
def __del__(self):
sys.stdout.write("\n")
if __name__ == "__main__":
import time
count = 150
print "starting things:"
pb = ProgressBar(count)
#pb.plotProgress()
for i in range(0, count):
pb += 1
#pb.setAndPlot(i + 1)
time.sleep(0.01)
del pb
print "done"
results in:
starting things:
100% [=================================================================]
done
This would most commonly be considered to be "over the top", but it's handy when you're using it a lot
I recently encountered this issue, and here is the solution I came up with
final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";
Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.
StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
currentSb.append( test.charAt( i ) ); // add the current char to our sb
}
List<String> comments = stringBuilderMap.entrySet().stream()
.sorted( Comparator.comparing( Map.Entry::getKey ) )
.map( entrySet -> entrySet.getValue().toString() )
.collect( Collectors.toList() );
//done
// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8
// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true
Either delete the selector or set it to the same color as your text appears normally.
Use isinstance
, nothing else:
if isinstance(x, pd.DataFrame):
... # do something
PEP8 says explicitly that isinstance
is the preferred way to check types
No: type(x) is pd.DataFrame
No: type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)
And don't even think about
if obj.__class__.__name__ = 'DataFrame':
expect_problems_some_day()
isinstance
handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str
or unicode
), because they derive from basestring
)
if isinstance(obj, basestring):
i_am_string(obj)
Specifically for pandas
DataFrame
objects:
import pandas as pd
isinstance(var, pd.DataFrame)
This should work:
your_str='GenFiltEff=7.092200e-01'
echo $your_str | cut -d "=" -f2
If you don't mind a paid-for product, PowerGREP is my personal favorite.
Arrays are not changeable after initialization. You have to give it a value, and that value is what that array length stays. You can create multiple arrays to contain certain parts of player information like their hand and such, and then create an arrayList to sort of shepherd those arrays.
Another point of contention I see, and I may be wrong about this, is the fact that your private Player[] InitializePlayers() is static where the class is now non-static. So:
private Player[] InitializePlayers(int playerCount)
{
...
}
My last point would be that you should probably have playerCount declared outside of the method that is going to change it so that the value that is set to it becomes the new value as well and it is not just tossed away at the end of the method's "scope."
Hope this helps
I've used both but in massive complex procedures have always found temp tables better to work with and more methodical. CTEs have their uses but generally with small data.
For example I've created sprocs that come back with results of large calculations in 15 seconds yet convert this code to run in a CTE and have seen it run in excess of 8 minutes to achieve the same results.
Alternate solution to doing shallow clone (git clone --depth=1 <URL>
) would be, if remote side supports it, to use --remote
option of git archive:
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
There is no more plugin in netbeans 12. In case someone comes to this page. Tools->Options->Appearance->Look and feel->Flatlaf Dark
The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.
Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.
Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.
<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
<S11:Header>
...
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>NNK</wsse:Username>
<wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
<wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
<wsu:Created>2003-07-16T01:24:32</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
...
</S11:Header>
...
</S11:Envelope>
Per the documentation:
os.listdir(path)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
Order cannot be relied upon and is an artifact of the filesystem.
To sort the result, use sorted(os.listdir(path))
.
You can use isset
function:
if(isset($_GET['id'])) {
// id index exists
}
You can create a handy function to return default value if index doesn't exist:
function Get($index, $defaultValue) {
return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}
// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');
You can also try to validate it at the same time:
function GetInt($index, $defaultValue) {
return isset($_GET[$index]) && ctype_digit($_GET[$index])
? (int)$_GET[$index]
: $defaultValue;
}
// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);
What @deceze said is correct, it seems that your JSON is malformed, try this:
{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
}]
}
Use json_decode
to convert String into Object (stdClass
) or array: http://php.net/manual/en/function.json-decode.php
[edited]
I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?
assuming you have the following variable:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
You should convert it to Object (stdClass):
$manage = json_decode($data);
But working with stdClass
is more complicated than PHP-Array, then try this (use second param with true
):
$manage = json_decode($data, true);
This way you can use array functions: http://php.net/manual/en/function.array.php
adding an item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
echo '<br>After: <br>';
print_r($manage);
remove first item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);
any chance you want to save to json to a database or a file:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
$manage = json_decode($data, true);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
if (($id = fopen('datafile.txt', 'wb'))) {
fwrite($id, json_encode($manage));
fclose($id);
}
I hope I have understood your question.
Good luck.
You can do it this way using INSTR:
SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;
INSTR returns zero if the substring is not in the string.
Out of interest, why don't you want to use like?
Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)