content
stringlengths
10
4.9M
package cn.minsin.feign.util; import org.springframework.core.env.Environment; /** * @author: minton.zhang * @since: 2020/6/4 14:54 */ public final class FeignExceptionHandlerContext { private static Environment ENVIRONMENT; public static String getApplicationName() { return ENVIRONMENT == null ? "unknownServer" : ENVIRONMENT.getProperty("spring.application.name"); } /** * 获取配置项 * * @param name 配置名称 * @return */ public static String getProperty(String name) { return ENVIRONMENT == null ? null : ENVIRONMENT.getProperty(name); } /** * 获取配置项 * * @param name 配置名称 * @param defaultValue 默认值 */ public static String getProperty(String name, String defaultValue) { return ENVIRONMENT == null ? defaultValue : ENVIRONMENT.getProperty(name, defaultValue); } /** * 获取环境对象 */ public static Environment getEnvironment() { return ENVIRONMENT; } public static void setEnvironment(Environment environment) { if (ENVIRONMENT == null) { FeignExceptionHandlerContext.ENVIRONMENT = environment; } } }
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2019 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: <NAME>, <NAME> // ============================================================================= // // ============================================================================= #include "chrono_sensor/filters/ChFilterImageOps.h" #include "chrono_sensor/ChSensor.h" #include "chrono_sensor/cuda/image_ops.cuh" #include "chrono_sensor/utils/CudaMallocHelper.h" #include <npp.h> namespace chrono { namespace sensor { CH_SENSOR_API ChFilterImageResize::ChFilterImageResize(int w, int h, std::string name) : m_w(w), m_h(h), ChFilter(name) {} CH_SENSOR_API void ChFilterImageResize::Apply(std::shared_ptr<ChSensor> pSensor, std::shared_ptr<SensorBuffer>& bufferInOut) { // this filter CANNOT be the first filter in a sensor's filter list, so the bufferIn CANNOT null. assert(bufferInOut != nullptr); if (!bufferInOut) throw std::runtime_error("The lidar reduce filter was not supplied an input buffer"); if (auto pOpx = std::dynamic_pointer_cast<SensorOptixBuffer>(bufferInOut)) { if (pOpx->Buffer->getFormat() != RT_FORMAT_UNSIGNED_BYTE4) { throw std::runtime_error( "The only optix format that can be resized is by lidar is RT_FORMAT_UNSIGNED_BYTE4"); } if (!m_buffer_rgba8) { m_buffer_rgba8 = chrono_types::make_shared<SensorDeviceRGBA8Buffer>(); DeviceRGBA8BufferPtr b(cudaMallocHelper<PixelRGBA8>(m_w * m_h), cudaFreeHelper<PixelRGBA8>); m_buffer_rgba8->Buffer = std::move(b); m_buffer_rgba8->Width = m_w; m_buffer_rgba8->Height = m_h; } // we need id of first device for this context (should only have 1 anyway) int device_id = pOpx->Buffer->getContext()->getEnabledDevices()[0]; void* ptr = pOpx->Buffer->getDevicePointer(device_id); // hard coded to grab from device 0 nppiResize_8u_C4R((unsigned char*)ptr, bufferInOut->Width * 4, NppiSize({(int)bufferInOut->Width, (int)bufferInOut->Height}), NppiRect({0, 0, (int)bufferInOut->Width, (int)bufferInOut->Height}), (unsigned char*)m_buffer_rgba8->Buffer.get(), m_w * 4, NppiSize({(int)m_w, (int)m_h}), NppiRect({0, 0, (int)m_w, (int)m_h}), NPPI_INTER_CUBIC); m_buffer_rgba8->LaunchedCount = bufferInOut->LaunchedCount; m_buffer_rgba8->TimeStamp = bufferInOut->TimeStamp; bufferInOut = m_buffer_rgba8; } else if (auto pRGBA = std::dynamic_pointer_cast<SensorDeviceRGBA8Buffer>(bufferInOut)) { if (!m_buffer_rgba8) { m_buffer_rgba8 = chrono_types::make_shared<SensorDeviceRGBA8Buffer>(); DeviceRGBA8BufferPtr b(cudaMallocHelper<PixelRGBA8>(m_w * m_h), cudaFreeHelper<PixelRGBA8>); m_buffer_rgba8->Buffer = std::move(b); m_buffer_rgba8->Width = m_w; m_buffer_rgba8->Height = m_h; } nppiResize_8u_C4R((unsigned char*)pRGBA->Buffer.get(), bufferInOut->Width * 4, NppiSize({(int)bufferInOut->Width, (int)bufferInOut->Height}), NppiRect({0, 0, (int)bufferInOut->Width, (int)bufferInOut->Height}), (unsigned char*)m_buffer_rgba8->Buffer.get(), m_w * 4, NppiSize({(int)m_w, (int)m_h}), NppiRect({0, 0, (int)m_w, (int)m_h}), NPPI_INTER_LINEAR); m_buffer_rgba8->LaunchedCount = bufferInOut->LaunchedCount; m_buffer_rgba8->TimeStamp = bufferInOut->TimeStamp; bufferInOut = m_buffer_rgba8; } else if (auto pR = std::dynamic_pointer_cast<SensorDeviceR8Buffer>(bufferInOut)) { if (!m_buffer_r8) { m_buffer_r8 = chrono_types::make_shared<SensorDeviceR8Buffer>(); DeviceR8BufferPtr b(cudaMallocHelper<char>(m_w * m_h), cudaFreeHelper<char>); m_buffer_r8->Buffer = std::move(b); m_buffer_r8->Width = m_w; m_buffer_r8->Height = m_h; } nppiResize_8u_C1R((unsigned char*)pR->Buffer.get(), bufferInOut->Width, NppiSize({(int)bufferInOut->Width, (int)bufferInOut->Height}), NppiRect({0, 0, (int)bufferInOut->Width, (int)bufferInOut->Height}), (unsigned char*)m_buffer_r8->Buffer.get(), m_w, NppiSize({(int)m_w, (int)m_h}), NppiRect({0, 0, (int)m_w, (int)m_h}), NPPI_INTER_LINEAR); m_buffer_r8->LaunchedCount = bufferInOut->LaunchedCount; m_buffer_r8->TimeStamp = bufferInOut->TimeStamp; bufferInOut = m_buffer_r8; } else { throw std::runtime_error("The image resizing filter requires Optix, RGBA8, or R8 buffer"); } } CH_SENSOR_API ChFilterImgAlias::ChFilterImgAlias(int factor, std::string name) : m_factor(factor), ChFilter(name) {} CH_SENSOR_API void ChFilterImgAlias::Apply(std::shared_ptr<ChSensor> pSensor, std::shared_ptr<SensorBuffer>& bufferInOut) { // this filter CANNOT be the first filter in a sensor's filter list, so the bufferIn CANNOT be null. assert(bufferInOut != nullptr); if (!bufferInOut) throw std::runtime_error("The lidar reduce filter was not supplied an input buffer"); unsigned int width_out = bufferInOut->Width / m_factor; unsigned int height_out = bufferInOut->Height / m_factor; // if the buffer is an optix buffer of UBYTE4 if (auto pOpx = std::dynamic_pointer_cast<SensorOptixBuffer>(bufferInOut)) { if (pOpx->Buffer->getFormat() != RT_FORMAT_UNSIGNED_BYTE4) { throw std::runtime_error( "The only optix format that can be resized is by lidar is RT_FORMAT_UNSIGNED_BYTE4"); } if (!m_buffer_rgba8) { m_buffer_rgba8 = chrono_types::make_shared<SensorDeviceRGBA8Buffer>(); DeviceRGBA8BufferPtr b(cudaMallocHelper<PixelRGBA8>(width_out * height_out), cudaFreeHelper<PixelRGBA8>); m_buffer_rgba8->Buffer = std::move(b); m_buffer_rgba8->Width = width_out; m_buffer_rgba8->Height = height_out; } // // // we need id of first device for this context (should only have 1 anyway) int device_id = pOpx->Buffer->getContext()->getEnabledDevices()[0]; void* ptr = pOpx->Buffer->getDevicePointer(device_id); // hard coded to grab from device 0 // nppiFilterGaussBorder_8u_C4R((unsigned char*)ptr, width * 4, NppiSize({(int)width, (int)height}), // NppiPoint({0, 0}), (unsigned char*)ptr, width * 4, // NppiSize({(int)width, (int)height}), NPP_MASK_SIZE_3_X_3, NPP_BORDER_REPLICATE); // auto err = nppiResize_8u_C4R((unsigned char*)ptr, width * 4, NppiSize({(int)width, (int)height}), // NppiRect({0, 0, width, height}), (unsigned char*)m_buffer_rgba8->Buffer.get(), // width_out * 4, NppiSize({width_out, height_out}), // NppiRect({0, 0, width_out, height_out}), 2); cuda_image_alias(ptr, m_buffer_rgba8->Buffer.get(), (int)width_out, (int)height_out, m_factor, sizeof(PixelRGBA8)); m_buffer_rgba8->LaunchedCount = bufferInOut->LaunchedCount; m_buffer_rgba8->TimeStamp = bufferInOut->TimeStamp; bufferInOut = m_buffer_rgba8; } else if (auto pRGBA = std::dynamic_pointer_cast<SensorDeviceRGBA8Buffer>(bufferInOut)) { if (!m_buffer_rgba8) { m_buffer_rgba8 = chrono_types::make_shared<SensorDeviceRGBA8Buffer>(); DeviceRGBA8BufferPtr b(cudaMallocHelper<PixelRGBA8>(width_out * height_out), cudaFreeHelper<PixelRGBA8>); m_buffer_rgba8->Buffer = std::move(b); m_buffer_rgba8->Width = bufferInOut->Width / m_factor; m_buffer_rgba8->Height = bufferInOut->Height / m_factor; } // cuda_image_gauss_blur_char(pRGBA->Buffer.get(), (int)width, (int)height, 4, m_factor); // nppiFilterGaussBorder_8u_C4R((unsigned char*)pRGBA->Buffer.get(), width * 4, // NppiSize({(int)width, (int)height}), NppiPoint({0, 0}), // (unsigned char*)pRGBA->Buffer.get(), width * 4, // NppiSize({(int)width, (int)height}), NPP_MASK_SIZE_3_X_3, NPP_BORDER_REPLICATE); cuda_image_alias(pRGBA->Buffer.get(), m_buffer_rgba8->Buffer.get(), (int)width_out, (int)height_out, m_factor, sizeof(PixelRGBA8)); m_buffer_rgba8->LaunchedCount = bufferInOut->LaunchedCount; m_buffer_rgba8->TimeStamp = bufferInOut->TimeStamp; bufferInOut = m_buffer_rgba8; } else if (auto pR = std::dynamic_pointer_cast<SensorDeviceR8Buffer>(bufferInOut)) { if (!m_buffer_r8) { m_buffer_r8 = chrono_types::make_shared<SensorDeviceR8Buffer>(); DeviceR8BufferPtr b(cudaMallocHelper<char>(width_out * height_out), cudaFreeHelper<char>); m_buffer_r8->Buffer = std::move(b); m_buffer_r8->Width = bufferInOut->Width / m_factor; m_buffer_r8->Height = bufferInOut->Height / m_factor; } // cuda_image_gauss_blur_char(pR->Buffer.get(), (int)width, (int)height, 1, m_factor); cuda_image_alias(pR->Buffer.get(), m_buffer_r8->Buffer.get(), (int)width_out, (int)height_out, m_factor, sizeof(char)); m_buffer_r8->LaunchedCount = bufferInOut->LaunchedCount; m_buffer_r8->TimeStamp = bufferInOut->TimeStamp; bufferInOut = m_buffer_r8; } else { throw std::runtime_error("The image antialiasing downscale filter requires Optix, RGBA8, or R8 buffer"); } } } // namespace sensor } // namespace chrono
def _execute(self, options={}, args=[]): if requests is None: print('To use the import_wordpress command,' ' you have to install the "requests" package.') return if not args: print(self.help()) return options['filename'] = args.pop(0) if args and ('output_folder' not in args or options['output_folder'] == 'new_site'): options['output_folder'] = args.pop(0) if args: print('You specified additional arguments ({0}). Please consider ' 'putting these arguments before the filename if you ' 'are running into problems.'.format(args)) self.wordpress_export_file = options['filename'] self.squash_newlines = options.get('squash_newlines', False) self.no_downloads = options.get('no_downloads', False) self.output_folder = options.get('output_folder', 'new_site') self.import_into_existing_site = False self.exclude_drafts = options.get('exclude_drafts', False) self.url_map = {} channel = self.get_channel_from_file(self.wordpress_export_file) self.context = self.populate_context(channel) conf_template = self.generate_base_site() self.timezone = None self.import_posts(channel) self.context['REDIRECTIONS'] = self.configure_redirections( self.url_map) self.write_urlmap_csv( os.path.join(self.output_folder, 'url_map.csv'), self.url_map) rendered_template = conf_template.render(**self.context) rendered_template = re.sub('# REDIRECTIONS = ', 'REDIRECTIONS = ', rendered_template) if self.timezone: rendered_template = re.sub('# TIMEZONE = \'Europe/Zurich\'', 'TIMEZONE = \'' + self.timezone + '\'', rendered_template) self.write_configuration(self.get_configuration_output_path(), rendered_template)
def _latlong_to_screen(self, location: Tuple[float, float]) -> Tuple[int, int]: x = round((location[0] - self.min_coords[0]) / (self.max_coords[0] - self.min_coords[0]) * self.image.get_width()) y = round((location[1] - self.min_coords[1]) / (self.max_coords[1] - self.min_coords[1]) * self.image.get_height()) x = round((x - self._xoffset) * self._zoom * self.screensize[0] / self.image.get_width()) y = round((y - self._yoffset) * self._zoom * self.screensize[1] / self.image.get_height()) return x, y
<reponame>jiansheng/cassandra<filename>src/com/facebook/infrastructure/service/WriteResponseResolver.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.infrastructure.service; import java.util.List; import org.apache.log4j.Logger; import com.facebook.infrastructure.db.WriteResponseMessage; import com.facebook.infrastructure.net.Message; /** * Author : <NAME> ( <EMAIL>) & <NAME> ( <EMAIL> ) */ public class WriteResponseResolver implements IResponseResolver<Boolean> { private static Logger logger_ = Logger.getLogger(WriteResponseResolver.class); /* * The resolve function for the Write looks at all the responses if all the * respones returned are false then we have a problem since that means the * key wa not written to any of the servers we want to notify the client of * this so in that case we should return a false saying that the write * failed. * */ public Boolean resolve(List<Message> responses) throws DigestMismatchException { // TODO: We need to log error responses here for example // if a write fails for a key log that the key could not be replicated boolean returnValue = false; for (Message response : responses) { Object[] body = response.getMessageBody(); WriteResponseMessage writeResponseMessage = (WriteResponseMessage) body[0]; boolean result = writeResponseMessage.isSuccess(); if (!result) { logger_.debug("Write at " + response.getFrom() + " may have failed for the key " + writeResponseMessage.key()); } returnValue |= result; } return returnValue; } public boolean isDataPresent(List<Message> responses) { return true; } }
def handle_enter(self, evt): self.pointed_to = evt.widget pointed_row = self.pointed_to.grid_info()['row'] for child in self.search_table.winfo_children(): if child.grid_info()['row'] in (0, 1): pass elif (child.grid_info()['column'] == 0 and child.grid_info()['row'] == pointed_row): self.person_id = child['text'] for row in self.result_rows: if row[0] == self.person_id: pointed_dict = row self.nametip_text = pointed_dict[9] if self.nametip_text: self.show_nametip()
/** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(RobolectricTestRunner.class) @Config(manifest = "AndroidManifest.xml") public class AppSyncClientUnitTest { Resources res; Context mockContext; Context shadowContext; private static final String TAG = AppSyncClientUnitTest.class.getSimpleName(); private String jsonConfig; private AWSConfiguration awsConfiguration; @Before public void setup() { shadowContext = ShadowApplication.getInstance().getApplicationContext(); mockContext = Mockito.mock(Context.class); res = Mockito.mock(Resources.class); Mockito.when(mockContext.getResources()).thenReturn(res); jsonConfig = "{\n" + " \"CredentialsProvider\": {\n" + " \"CognitoIdentity\": {\n" + " \"AwsIam\": {\n" + " \"PoolId\": \"us-east-1:xxxx\",\n" + " \"Region\": \"us-east-1\"\n" + " }\n" + " }\n" + " },\n" + " \"CognitoUserPool\": {\n" + " \"AmazonCognitoUserPools\": {\n" + " \"PoolId\": \"us-east-1_zzzz\",\n" + " \"AppClientId\": \"aaaa\",\n" + " \"AppClientSecret\": \"bbbb\",\n" + " \"Region\": \"us-east-1\"\n" + " }\n" + " },\n" + " \"AppSync\": {\n" + " \"Default\": {\n" + " \"ApiUrl\": \"https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql\",\n" + " \"Region\": \"us-east-1\",\n" + " \"ApiKey\": \"da2-xxxx\",\n" + " \"AuthMode\": \"API_KEY\"\n" + " },\n" + " \"ApiKey\": {\n" + " \"ApiUrl\": \"https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql\",\n" + " \"Region\": \"us-east-1\",\n" + " \"ApiKey\": \"da2-xxxx\",\n" + " \"AuthMode\": \"API_KEY\"\n" + " },\n" + " \"AwsIam\": {\n" + " \"ApiUrl\": \"https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql\",\n" + " \"Region\": \"us-east-1\",\n" + " \"AuthMode\": \"AWS_IAM\"\n" + " },\n" + " \"AmazonCognitoUserPools\": {\n" + " \"ApiUrl\": \"https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql\",\n" + " \"Region\": \"us-east-1\",\n" + " \"AuthMode\": \"AMAZON_COGNITO_USER_POOLS\"\n" + " },\n" + " \"OpenidConnect\": {\n" + " \"ApiUrl\": \"https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql\",\n" + " \"Region\": \"us-east-1\",\n" + " \"AuthMode\": \"OPENID_CONNECT\"\n" + " }\n" + " }\n" + "}"; Mockito.when(res.openRawResource(3213210)).thenReturn(new ByteArrayInputStream(jsonConfig.getBytes())); awsConfiguration = new AWSConfiguration(mockContext, 3213210); } @Test public void testDefault() { awsConfiguration.setConfiguration("Default"); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .build(); assertNotNull(awsAppSyncClient); } @Test public void testApiKeyAuthProvider() { awsConfiguration.setConfiguration("ApiKey"); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .apiKey(new BasicAPIKeyAuthProvider(awsConfiguration)) .build(); assertNotNull(awsAppSyncClient); } @Test public void testAwsIamAuthProvider() { awsConfiguration.setConfiguration("AwsIam"); final CognitoCredentialsProvider credentialsProvider = new CognitoCredentialsProvider(awsConfiguration); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .credentialsProvider(credentialsProvider) .build(); assertNotNull(awsAppSyncClient); } @Test public void testAmazonCognitoUserPoolsAuthProvider() { awsConfiguration.setConfiguration("AmazonCognitoUserPools"); CognitoUserPool cognitoUserPool = new CognitoUserPool(shadowContext, awsConfiguration); BasicCognitoUserPoolsAuthProvider basicCognitoUserPoolsAuthProvider = new BasicCognitoUserPoolsAuthProvider(cognitoUserPool); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .cognitoUserPoolsAuthProvider(basicCognitoUserPoolsAuthProvider) .build(); assertNotNull(awsAppSyncClient); } @Test public void testOpenidConnectAuthProvider() { awsConfiguration.setConfiguration("OpenidConnect"); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .oidcAuthProvider(new OidcAuthProvider() { @Override public String getLatestAuthToken() { return null; } }) .build(); assertNotNull(awsAppSyncClient); } @Test(expected = RuntimeException.class) public void testConfigMismatch_ApiKey() { awsConfiguration.setConfiguration("AwsIam"); final CognitoCredentialsProvider credentialsProvider = new CognitoCredentialsProvider(awsConfiguration); awsConfiguration.setConfiguration("ApiKey"); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .credentialsProvider(credentialsProvider) .build(); } @Test(expected = RuntimeException.class) public void testConfigMismatch_AmazonCognitoUserPools() { awsConfiguration.setConfiguration("ApiKey"); APIKeyAuthProvider apiKeyAuthProvider = new BasicAPIKeyAuthProvider(awsConfiguration); awsConfiguration.setConfiguration("AmazonCognitoUserPools"); CognitoUserPool cognitoUserPool = new CognitoUserPool(shadowContext, awsConfiguration); BasicCognitoUserPoolsAuthProvider basicCognitoUserPoolsAuthProvider = new BasicCognitoUserPoolsAuthProvider(cognitoUserPool); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .apiKey(apiKeyAuthProvider) .build(); } @Test(expected = RuntimeException.class) public void testMultipleAuth() { awsConfiguration.setConfiguration("ApiKey"); APIKeyAuthProvider apiKeyAuthProvider = new BasicAPIKeyAuthProvider(awsConfiguration); awsConfiguration.setConfiguration("AmazonCognitoUserPools"); CognitoUserPool cognitoUserPool = new CognitoUserPool(shadowContext, awsConfiguration); BasicCognitoUserPoolsAuthProvider basicCognitoUserPoolsAuthProvider = new BasicCognitoUserPoolsAuthProvider(cognitoUserPool); final AWSAppSyncClient awsAppSyncClient = AWSAppSyncClient.builder() .context(shadowContext) .awsConfiguration(awsConfiguration) .apiKey(apiKeyAuthProvider) .cognitoUserPoolsAuthProvider(basicCognitoUserPoolsAuthProvider) .build(); } }
// Play decode the gif file content then play it in the terminal func (terminalPlayer *GifTerminalPlayer) Play(filename string, playOptions *PlayOptions) { frames, err := terminalPlayer.decoder.DecodeFromFile(filename, nil) if err != nil { log.Fatal(err) } convertOptions := playOptions.Options delay := playOptions.Delay stdout := os.Stdout for { for _, frame := range frames { asciiImageStr := terminalPlayer.converter.Image2ASCIIString(frame, &convertOptions) fmt.Fprint(stdout, asciiImageStr) time.Sleep(delay) fmt.Fprint(stdout, ClearScreen) } } }
/** * This function checks if a given queue is empty. * * @param queue The queue structure. * @return 1 if the queue is empty, else 0. */ static int threadpool_queue_is_empty(struct threadpool_queue *queue) { if (queue->num_of_cells == 0) { return 1; } return 0; }
// Attack length must be between range bool Wheel::checkAttackLength(Uint32 aLen) { if (aLen < MIN_ATTACK_LENGTH || aLen > SDL_MAX_UINT32) { log("Error: attack length in mS Out of Bounds"); return false; } return true; }
/* Euclidean modulo where the remainder has same sign as divisor. */ inline float emod( float a, float b ) { float v = fmod( a, b ); if ( ( b < 0 ) != ( v < 0 ) ) { v += b; } return v; }
/** * Cudnn set sumChannels tensor descriptor int. * * @param reduceTensorDesc the sumChannels tensor desc * @param reduceTensorOp the sumChannels tensor op * @param reduceTensorCompType the sumChannels tensor comp type * @param reduceTensorNanOpt the sumChannels tensor nan opt * @param reduceTensorIndices the sumChannels tensor indices * @param reduceTensorIndicesType the sumChannels tensor indices type * @return the int */ public int cudnnSetReduceTensorDescriptor(cudnnReduceTensorDescriptor reduceTensorDesc, int reduceTensorOp, int reduceTensorCompType, int reduceTensorNanOpt, int reduceTensorIndices, int reduceTensorIndicesType) { long startTime = System.nanoTime(); final int result = JCudnn.cudnnSetReduceTensorDescriptor(reduceTensorDesc, reduceTensorOp, reduceTensorCompType, reduceTensorNanOpt, reduceTensorIndices, reduceTensorIndicesType); cudnnSetReduceTensorDescriptor_execution.accept((System.nanoTime() - startTime) / 1e9); log("cudnnCreateReduceTensorDescriptor", result, new Object[]{reduceTensorDesc}); return result; }
<filename>nice/sdk/json/Skills/TSGetCampaignsResponse.ts export var GetCampaignsResponse_Skills = { "resultSet": { "_links": { "self": "", "next": "", "previous": "" }, "businessUnitId": 0, "totalRecords": 0, "campaigns": [ { "campaignId": 0, "campaignName": "", "isActive": true, "description": "", "notes": "", "lastUpdateTime": "2020-07-26T23:59:59.678Z" } ] } };
<filename>platform/busybox/selinux/load_policy.c /* * load_policy * This implementation is based on old load_policy to be small. * Author: <NAME> <<EMAIL>> */ #include "libbb.h" int load_policy_main(int argc, char **argv); int load_policy_main(int argc, char **argv) { int fd; struct stat st; void *data; if (argc != 2) { bb_show_usage(); } fd = xopen(argv[1], O_RDONLY); if (fstat(fd, &st) < 0) { bb_perror_msg_and_die("can't fstat"); } data = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (data == MAP_FAILED) { bb_perror_msg_and_die("can't mmap"); } if (security_load_policy(data, st.st_size) < 0) { bb_perror_msg_and_die("can't load policy"); } return 0; }
ipt = int(input()) if(ipt % 10 == 7): print("Yes") elif((ipt // 10) % 10 == 7): print("Yes") elif(((ipt // 10) // 10) % 10 == 7): print("Yes") else: print("No")
Potential benefits of using ecological momentary assessment to study high-risk polydrug use. Background While studies have documented both the feasibility and acceptability of using ecological momentary assessment (EMA) to study drug use, there is little empirical research assessing participants' perceptions of utilizing this technology-driven approach. Methods Participants were English-speaking persons ≥18 years old who reported injection drug use and sequential (e.g., alcohol followed by opioid use) or simultaneous (i.e., injecting heroin and cocaine in one shot) polydrug use within 30 days recruited in San Diego, CA and Philadelphia, PA. Participants (N=36) completed two cell phone-based EMA simulations assessing mood, drug use, HIV risk behaviors, and daily activities, followed by semi-structured interviews that probed for potential benefits of participation over time. Qualitative analysis involved an iterative process of reviewing texts from the interviews to create a coding framework, which was then applied to all transcripts to identify themes. Results Findings suggest participants may derive indirect benefits from participation in EMA studies including: improved self-worth from helping others; experiencing increased social support through utilization of the study-provided mobile device for non-research purposes; and most importantly, increased self-reflection, which could lead to therapeutic and intervention-like effects such as decreased substance use or reduced HIV risk. Conclusions Participants identified a variety of potential benefits from participating in a study that utilizes EMA. This research suggests that benefits are highly salient for individuals involved in studies of polydrug use.
/** * A daemon thread. Also see StoppableThread for an alternative daemon * construct. */ public abstract class DaemonThread implements DaemonRunner, Runnable { private static final int JOIN_MILLIS = 10; private volatile long waitTime; private final Object synchronizer = new Object(); private Thread thread; protected String name; protected int nWakeupRequests; public static boolean stifleExceptionChatter = false; /* Fields shared between threads must be 'volatile'. */ private volatile boolean shutdownRequest = false; private volatile boolean paused = false; /* This is not volatile because it is only an approximation. */ private boolean running = false; /* Fields for DaemonErrorListener, enabled only during testing. */ protected final EnvironmentImpl envImpl; private static final String ERROR_LISTENER = "setErrorListener"; /* Logger used in DaemonThread's subclasses. */ protected final Logger logger; public DaemonThread(final long waitTime, final String name, final EnvironmentImpl envImpl) { this.waitTime = waitTime; String nodeName = envImpl.getNodeName(); if (nodeName == null) { this.name = name; } else { this.name = name + " (" + nodeName + ")"; } this.envImpl = envImpl; this.logger = createLogger(); } protected Logger createLogger() { return LoggerUtils.getLogger(getClass()); } /** * For testing. */ public Thread getThread() { return thread; } /** * If run is true, starts the thread if not started or unpauses it * if already started; if run is false, pauses the thread if * started or does nothing if not started. */ public void runOrPause(boolean run) { if (run) { paused = false; if (thread != null) { wakeup(); } else { thread = new Thread(this, name); thread.setDaemon(true); thread.start(); } } else { paused = true; } } public void requestShutdown() { shutdownRequest = true; } /** * Requests shutdown and calls join() to wait for the thread to stop. */ public void shutdown() { if (thread != null) { shutdownRequest = true; while (thread.isAlive()) { synchronized (synchronizer) { synchronizer.notifyAll(); } try { thread.join(JOIN_MILLIS); } catch (InterruptedException e) { /* * Klockwork - ok * Don't say anything about exceptions here. */ } } thread = null; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<DaemonThread name=\"").append(name).append("\"/>"); return sb.toString(); } public void wakeup() { if (!paused) { synchronized (synchronizer) { synchronizer.notifyAll(); } } } public void run() { while (!shutdownRequest) { try { /* Do a unit of work. */ int numTries = 0; long maxRetries = nDeadlockRetries(); while (numTries <= maxRetries && !shutdownRequest && !paused) { try { nWakeupRequests++; running = true; onWakeup(); break; } catch (LockConflictException e) { } finally { running = false; } numTries++; } /* Wait for notify, timeout or interrupt. */ if (!shutdownRequest) { synchronized (synchronizer) { if (waitTime == 0 || paused) { synchronizer.wait(); } else { synchronizer.wait(waitTime); } } } } catch (InterruptedException e) { notifyExceptionListener(e); if (!stifleExceptionChatter) { logger.info ("Shutting down " + this + " due to exception: " + e); } shutdownRequest = true; assert checkErrorListener(e); } catch (Exception e) { notifyExceptionListener(e); if (!stifleExceptionChatter) { /* * If the exception caused the environment to become * invalid, then shutdownRequest will have been set to true * by EnvironmentImpl.invalidate, which is called by the * EnvironmentFailureException ctor. */ logger.log(Level.SEVERE, this.toString() + " caught exception, " + e + (shutdownRequest ? " Exiting" : " Continuing"), e); } assert checkErrorListener(e); } catch (Error e) { assert checkErrorListener(e); envImpl.invalidate(e); /* [#21929] */ /* * Since there is no uncaught exception handler (yet) we * shutdown the thread here and log the exception. */ shutdownRequest = true; logger.log(Level.SEVERE, "Error caught in " + this, e); } } } private void notifyExceptionListener(Exception e) { if (envImpl == null) { return; } final ExceptionListener listener = envImpl.getExceptionListener(); if (listener == null) { return; } listener.exceptionThrown(DbInternal.makeExceptionEvent(e, name)); } /** * If Daemon Thread throws errors and exceptions, this function will catch * it and throw a EnvironmentFailureException, and fail the test. * * Only used during testing. */ public boolean checkErrorListener(Throwable e) { if (Boolean.getBoolean(ERROR_LISTENER)) { if (!stifleExceptionChatter) { logger.severe(name + " " + LoggerUtils.getStackTrace(e)); } new EnvironmentFailureException (envImpl, EnvironmentFailureReason.TEST_INVALIDATE, "Daemon thread failed during testing", e); } return true; } /** * Returns the number of retries to perform when Deadlock Exceptions * occur. */ protected long nDeadlockRetries() { return 0; } /** * onWakeup is synchronized to ensure that multiple invocations of the * DaemonThread aren't made. */ abstract protected void onWakeup() throws DatabaseException; /** * Returns whether shutdown has been requested. This method should be * used to to terminate daemon loops. */ protected boolean isShutdownRequested() { return shutdownRequest; } /** * Returns whether the daemon is currently paused/disabled. This method * should be used to to terminate daemon loops. */ protected boolean isPaused() { return paused; } /** * Returns whether the onWakeup method is currently executing. This is * only an approximation and is used to avoid unnecessary wakeups. */ public boolean isRunning() { return running; } public void setWaitTime(long waitTime) { this.waitTime = waitTime; } /** * For unit testing. */ public int getNWakeupRequests() { return nWakeupRequests; } }
/** * This is the standard version of the UserOverlay. * * @author ricky barrette */ public class UserOverlay extends BaseUserOverlay { private final AndroidGPS mAndroidGPS; public UserOverlay(final MapView mapView, final Context context) { super(mapView, context); mAndroidGPS = new AndroidGPS(context); } public UserOverlay(final MapView mapView, final Context context, final boolean followUser) { super(mapView, context, followUser); mAndroidGPS = new AndroidGPS(context); } @Override public void onFirstFix(final boolean isFistFix) { // unused } @Override public void onMyLocationDisabled() { mAndroidGPS.disableLocationUpdates(); } @Override public void onMyLocationEnabled() { mAndroidGPS.enableLocationUpdates(this); } }
<filename>nukkit/src/main/java/com/github/imdabigboss/kitduels/nukkit/interfaces/NukkitOfflinePlayer.java package com.github.imdabigboss.kitduels.nukkit.interfaces; import cn.nukkit.IPlayer; public class NukkitOfflinePlayer implements com.github.imdabigboss.kitduels.common.interfaces.CommonOfflinePlayer { private IPlayer player; public NukkitOfflinePlayer(IPlayer player) { this.player = player; } @Override public String getName() { return this.player.getName(); } }
/* Generic task switch macro wrapper, based on MN10300 definitions. * * It should be possible to use these on really simple architectures, * but it serves more as a starting point for new ports. * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #ifndef __ASM_GENERIC_SWITCH_TO_H #define __ASM_GENERIC_SWITCH_TO_H #include <linux/thread_info.h> /* * Context switching is now performed out-of-line in switch_to.S */ extern struct task_struct *__switch_to(struct task_struct *, struct task_struct *); #define switch_to(prev, next, last) \ do { \ ((last) = __switch_to((prev), (next))); \ } while (0) #endif /* __ASM_GENERIC_SWITCH_TO_H */
package com.almasb.event; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * @author <NAME> (AlmasB) (<EMAIL>) */ public class GameApp extends Application { private EventBus eventBus; private AudioPlayer audioPlayer; @Override public void start(Stage stage) throws Exception { eventBus = ServiceLocator.INSTANCE.getService(EventBus.class); audioPlayer = ServiceLocator.INSTANCE.getService(AudioPlayer.class); Scene scene = new Scene(new VBox(), 600, 600); scene.setOnMouseClicked(event -> { eventBus.fireEvent(new GameEvent(GameEvent.PLAYER_DIED)); }); stage.setScene(scene); stage.show(); } public static void main(String[] args) { ServiceLocator.INSTANCE.registerService(EventBus.class, EventBusProvider.class); ServiceLocator.INSTANCE.registerService(AudioPlayer.class, MockAudioPlayer.class); launch(args); } }
#include <bits/stdc++.h> using namespace std; #define FOR(x,n) for(int x=0;x<n;x++) #define mp make_pair #define PI 3.14159265358979323846264338327950288 typedef long long ll; typedef pair<int,int> ii; int n; void check(vector<int>& ans) { FOR(i,n) { if(ans[i] < 0) return; } for(int i = 1; i < n; i++) { if(abs(ans[i] - ans[i - 1]) != 1) return; } cout << "YES\n"; FOR(i,n) { cout << ans[i] << ' '; } cout << '\n'; exit(0); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int c0, c1, c2, c3; cin >> c0 >> c1 >> c2 >> c3; n = c0 + c1 + c2 + c3; vector<int> ans1(3*n, -5); vector<int> ans2(3*n, -5); int even = c0 + c2; int odd = c1 + c3; int a = c0, b = c1, c = c2, d = c3; for(int i = 0; i < 2*even; i += 2) { if(c) { ans1[i] = 2; ans2[i + 1] = 2; c--; } else { ans1[i] = 0; ans2[i + 1] = 0; a--; } } for(int i = 0; i < 2*odd; i += 2) { if(d) { ans1[i + 1] = 3; ans2[i] = 3; d--; } else { ans1[i + 1] = 1; ans2[i] = 1; b--; } } check(ans1); check(ans2); cout << "NO\n"; } // UPDATE N WHEN UR DONE AAAAAAAAAAAAAAAAAAAAAAAAAAA (if it applies lol)
#pragma once #include <cstdint> extern std::uintptr_t ContinueTerminalInput; char PasswordMasker(char* buffer, char currChar, int position); void PasswordMaskerStub();
/* * dynamic_conf.h * * Created on: Dec 26, 2017 * by: <NAME> */ #ifndef SRC_MODULES_DYNAMIC_CONF_DYNAMIC_CONF_H_ #define SRC_MODULES_DYNAMIC_CONF_DYNAMIC_CONF_H_ #include <stdbool.h> #include "agency.h" typedef struct dynamic_conf_struct dynamic_config_context_t; bool dynamic_conf_alloc_and_init( pid_t *processing_pid ); /** * Create a new process to listen on a local UNIX socket to receive control commands. * @param unix_socket_domain_descriptor_name * @param clean_resource callback will be called before exiting the child process * @return pid of the child process being created */ pid_t dynamcic_conf_create_new_process_to_receive_command( const char * unix_socket_domain_descriptor_name, void (*clean_resource)() ); /** * This function must be called periodically by each process to check if there will be new configuration */ void dynamic_conf_check(); void dynamic_conf_release(); #endif /* SRC_MODULES_DYNAMIC_CONF_DYNAMIC_CONF_H_ */
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { AuthService } from '../_services/auth.service'; import { TokenStorageService } from '../_services/token-storage.service'; import { HttpClient } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; import { GroupService } from '../_services/group.service'; import { AccountService } from '../_services/account.service'; import { connectableObservableDescriptor } from 'rxjs/internal/observable/ConnectableObservable'; @Component({ selector: 'donate-group', templateUrl: './group-donate.component.html', styleUrls: ['./group-donate.component.css'] }) export class GroupDonateComponent implements OnInit { form: any = { group: null, money: null, currency:null }; groups = [ {id: 0, groupName: ""}, ]; selectedGroup = ""; currencies = [ {id: 0, currency: ""}, ]; selectedCurrency = ""; done=false; response=""; constructor(private groupService: GroupService,private tokenS:TokenStorageService,private accountService:AccountService) { } ngOnInit(): void { this.groupService.getAllGroups().subscribe(res => { this.groups=res }) this.accountService.getAllAccountByUsername(this.tokenS.getUser()).subscribe(res=>{ this.currencies=res }) } onSubmit(): void { const { money,currency } = this.form; if(this.currencies.length==1){ this.selectedCurrency=this.currencies[0].currency } if(this.groups.length==1){ this.selectedGroup=this.groups[0].groupName } this.groupService.donateGroup(this.selectedGroup,money,this.selectedCurrency).subscribe(res=>{ this.response=res.message }) this.done=true; } }
<reponame>cryptogarageinc/p2pderivatives-client<filename>src/renderer/store/login/sagas.ts import { all, call, fork, put, takeEvery, getContext } from 'redux-saga/effects' import { LoginActionTypes } from './types' import { loginSuccess, loginError, logoutError, logoutSuccess, loginRequest, refreshSuccess, refreshError, changePasswordRequest, changePasswordSuccess, changePasswordError, } from './actions' import { AuthenticationAPI } from '../../ipc/AuthenticationAPI' import { SagaIterator } from 'redux-saga' import { IPCError } from '../../../common/models/ipc/IPCError' export function* handleLogin( action: ReturnType<typeof loginRequest> ): SagaIterator { try { const authAPI: AuthenticationAPI = yield getContext('authAPI') yield call(authAPI.login, action.payload.username, action.payload.password) yield put(loginSuccess(action.payload.username)) } catch (err) { if (err instanceof IPCError && err.getMessage()) { yield put(loginError(err.getMessage())) } else { yield put(loginError('An unknown error occured.')) } } } export function* handleLogout(): SagaIterator { try { const authAPI: AuthenticationAPI = yield getContext('authAPI') yield call(authAPI.logout) yield put(logoutSuccess()) } catch (err) { if (err instanceof IPCError && err.getMessage()) { yield put(logoutError(err.getMessage())) } else { yield put(logoutError('An unknown error occured.')) } } } export function* handleRefresh(): SagaIterator { try { const authAPI: AuthenticationAPI = yield getContext('authAPI') yield call(authAPI.refresh) yield put(refreshSuccess()) } catch (err) { if (err instanceof IPCError && err.getMessage()) { yield put(refreshError(err.getMessage())) } else { yield put(refreshError('An unknown error occured.')) } } } export function* handleChangePassword( action: ReturnType<typeof changePasswordRequest> ): SagaIterator { try { const authAPI: AuthenticationAPI = yield getContext('authAPI') yield call( authAPI.changePassword, action.payload.oldPassword, action.payload.newPassword ) yield put(changePasswordSuccess()) } catch (err) { if (err instanceof Error && err.message) { yield put(changePasswordError(err.message)) } else { yield put(changePasswordError('An unknown error occured.')) } } } function* watchRequests(): SagaIterator { yield takeEvery(LoginActionTypes.LOGIN_REQUEST, handleLogin) yield takeEvery(LoginActionTypes.LOGOUT_REQUEST, handleLogout) yield takeEvery(LoginActionTypes.REFRESH_REQUEST, handleRefresh) yield takeEvery(LoginActionTypes.CHANGEPW_REQUEST, handleChangePassword) } function* loginSagas(): SagaIterator { yield all([fork(watchRequests)]) } export default loginSagas
<gh_stars>1-10 /* * Created on Dec 10, 2004 */ package impl.jena; import java.net.URI; import java.util.HashMap; import java.util.Map; import org.mindswap.exceptions.CastingException; import org.mindswap.exceptions.ConversionException; import org.mindswap.exceptions.NotImplementedException; import org.mindswap.owl.OWLClass; import org.mindswap.owl.OWLConfig; import org.mindswap.owl.OWLDataProperty; import org.mindswap.owl.OWLDataType; import org.mindswap.owl.OWLEntity; import org.mindswap.owl.OWLIndividual; import org.mindswap.owl.OWLObject; import org.mindswap.owl.OWLObjectConverter; import org.mindswap.owl.OWLObjectProperty; import org.mindswap.owl.OWLProperty; import org.mindswap.owl.OWLType; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; /** * @author <NAME> */ public class OWLConverters { public static Map getConverters() { Map converters = new HashMap(); OWLObjectConverter objPropConverter = new ObjectPropertyConverter(); OWLObjectConverter dataPropConverter = new DataPropertyConverter(); OWLObjectConverter propConverter = new CombinedOWLConverter(OWLProperty.class, new OWLObjectConverter[] { objPropConverter, dataPropConverter}); OWLObjectConverter classConverter = new ClassConverter(); OWLObjectConverter dataTypeConverter = new DataTypeConverter(); OWLObjectConverter typeConverter = new CombinedOWLConverter(OWLType.class, new OWLObjectConverter[] { classConverter, dataTypeConverter}); OWLObjectConverter indConverter = new IndividualConverter(); OWLObjectConverter entityConverter = new CombinedOWLConverter(OWLType.class, new OWLObjectConverter[] { classConverter, dataTypeConverter, objPropConverter, dataPropConverter, indConverter}); converters.put(OWLIndividual.class, indConverter); converters.put(OWLObjectProperty.class, objPropConverter); converters.put(OWLDataProperty.class, dataPropConverter); converters.put(OWLProperty.class, propConverter); converters.put(OWLClass.class, classConverter); converters.put(OWLDataType.class, dataTypeConverter); converters.put(OWLType.class, typeConverter); converters.put(OWLEntity.class, entityConverter); return converters; } public static class CombinedOWLConverter implements OWLObjectConverter { OWLObjectConverter[] converters; Class javaClass; public CombinedOWLConverter(Class javaClass, OWLObjectConverter[] converters) { this.converters = converters; this.javaClass = javaClass; } public boolean canCast(OWLObject object) { boolean strict = OWLConfig.setStrictConversion(true); for(int i = 0; i < converters.length; i++) { if(converters[i].canCast(object)) { OWLConfig.setStrictConversion(strict); return true; } } OWLConfig.setStrictConversion(strict); return false; } public OWLObject cast(OWLObject object) { boolean strict = OWLConfig.setStrictConversion(true); for(int i = 0; i < converters.length; i++) { if(converters[i].canCast(object)) { OWLConfig.setStrictConversion(strict); return converters[i].cast(object); } } OWLConfig.setStrictConversion(strict); throw new CastingException("OWLObject " + object + " cannot be cast to " + javaClass); } public OWLObject convert(OWLObject object) { if(!canCast(object)) throw new ConversionException("Cannot convert " + object + " to abstract class " + javaClass); return cast(object); } } public static class ObjectPropertyConverter implements OWLObjectConverter { public boolean canCast(OWLObject object) { if(object instanceof OWLEntity) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return (entity.getKB().getObjectProperty(uri) != null) || !OWLConfig.getStrictConversion(); } return false; } public OWLObject cast(OWLObject object) { if(!canCast(object)) throw new ConversionException("OWLObject " + object + " cannot be converted to ObjectProperty"); OWLEntity entity = (OWLEntity) object; Resource res = (Resource) entity.getImplementation(); Property prop = (Property) res.as(Property.class); return ((OWLModelImpl) entity.getKB()).wrapObjectProperty(prop, null); } public OWLObject convert(OWLObject object) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return entity.getOntology().createObjectProperty(uri); } } public static class DataPropertyConverter implements OWLObjectConverter { public boolean canCast(OWLObject object) { if(object instanceof OWLEntity) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return (entity.getKB().getDataProperty(uri) != null) || !OWLConfig.getStrictConversion(); } return false; } public OWLObject cast(OWLObject object) { if(!canCast(object)) throw new ConversionException("OWLObject " + object + " cannot be converted to DatatypeProperty"); OWLEntity entity = (OWLEntity) object; Resource res = (Resource) entity.getImplementation(); Property prop = (Property) res.as(Property.class); return ((OWLModelImpl) entity.getKB()).wrapDataProperty(prop, null); } public OWLObject convert(OWLObject object) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return entity.getOntology().createDataProperty(uri); } } public static class ClassConverter implements OWLObjectConverter { public boolean canCast(OWLObject object) { if(object instanceof OWLEntity) { OWLEntity entity = (OWLEntity) object; Resource res = (Resource) entity.getImplementation(); return (((OWLModelImpl)entity.getKB()).getClass(res) != null) || !OWLConfig.getStrictConversion(); } return false; } public OWLObject cast(OWLObject object) { if(!canCast(object)) throw new ConversionException("OWLObject " + object + " cannot be converted to OWLClass"); OWLEntity entity = (OWLEntity) object; Resource res = (Resource) entity.getImplementation(); return ((OWLModelImpl) entity.getKB()).wrapClass(res, null); } public OWLObject convert(OWLObject object) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return entity.getOntology().createClass(uri); } } public static class IndividualConverter implements OWLObjectConverter { public boolean canCast(OWLObject object) { if(object instanceof OWLEntity) { return true; } return false; } public OWLObject cast(OWLObject object) { if(!canCast(object)) throw new ConversionException("OWLObject " + object + " cannot be converted to OWLIndividual"); OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); OWLIndividual ind = entity.getKB().getIndividual(uri); if(ind == null) ind = entity.getKB().createIndividual( uri ); return ind; } public OWLObject convert(OWLObject object) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return entity.getOntology().createObjectProperty(uri); } } public static class DataTypeConverter implements OWLObjectConverter { public boolean canCast(OWLObject object) { if(object instanceof OWLEntity) { OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return (entity.getKB().getDataType(uri) != null); } return false; } public OWLObject cast(OWLObject object) { if(!canCast(object)) throw new ConversionException("OWLObject " + object + " cannot be converted to ObjectProperty"); OWLEntity entity = (OWLEntity) object; URI uri = entity.getURI(); return entity.getKB().getDataType(uri); } public OWLObject convert(OWLObject object) { if(canCast(object)) cast(object); throw new NotImplementedException(); } } }
Role of milk fractions, serum, and divalent cations in protection of mammary epithelial cells of cows against damage by Staphylococcus aureus toxins. OBJECTIVE To determine the effect of milk and blood serum constituents on cytotoxicity of Staphylococcus aureus on mammary epithelial cells. DESIGN In vitro incubation of cells with cytotoxic agents and milk and serum constituents. SAMPLE POPULATION Mammary cells, milk, and blood obtained from 3 cows. PROCEDURE Staphylococcal alpha-toxin and culture supernatants from S aureus M60 and an alpha-toxin-negative mutant of M60 were incubated with bovine mammary epithelial cells in the presence of milk fractions, serum, and divalent cations. Propidium iodide fluorescence was used as a measure of cell damage. RESULTS Skim milk and milk whey inhibited S aureus cytotoxic agents. Skim milk protected against alpha-toxin damage to a greater extent than milk whey. Serum from an adult animal was more protective than was fetal serum. Milk fat and serum albumin had no protective effect. Divalent calcium and Mg2+ were more effective inhibitors of mammary epithelial cell damage caused by alpha-toxin than of damage attributable to M60 culture supernatant. Divalent calcium and Mg2+ at concentrations similar to those of free Ca2+ and Mg2+ in normal bovine milk decreased cytotoxic damage attributable to alpha-toxin. However, concentrations similar to those of total Ca2+ and Mg2+ in normal milk were required to decrease cell damage caused by M60 culture supernatant. The alpha-toxin-negative mutant was less cytotoxic than the M60 parent strain. CONCLUSIONS Casein, as well as Ca2+ and Mg2+ in bovine milk, inhibit the cytotoxic effect of S aureus on mammary epithelial cells.
<reponame>linkall-labs/vance<filename>pkg/k8s/httpscaledobject_keeper.go package k8s import ( kedahttp "github.com/kedacore/http-add-on/operator/api/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func CreateHttpScaledObject(nameSpace, name, host string, port int32) *kedahttp.HTTPScaledObject { httpScaledObject := &kedahttp.HTTPScaledObject{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: nameSpace, }, Spec: kedahttp.HTTPScaledObjectSpec{ Host: host, ScaleTargetRef: &kedahttp.ScaleTargetRef{ Deployment: name, Service: name, Port: port, }, }, } return httpScaledObject }
Holocaust survivor and restaurateur Avram Zeleznikow dies aged 89 Updated Avram Zeleznikow, a Holocaust survivor and founder of Melbourne's famous Scheherazade restaurant, has died aged 89. Zeleznikow was a partisan fighter in Poland during World War Two. He relocated to Australia in the 1950s and established the Scheherazade restaurant on Acland Street in St Kilda. The restaurant became a popular meeting place for many people, including Holocaust survivors. Zeleznikow's son John says his father will be remembered by many people as a resilient and caring man. "He did not run the restaurant to make a profit, he ran the restaurant to help people," he said. "There were often a large number of people who would get free meals because if you couldn't pay he would still provide the service." Topics: death, religion-and-beliefs, hospitality, st-kilda-3182, melbourne-3000, vic, australia First posted
// Build will build a stanza input operator. func (c *InputConfig) Build(context operator.BuildContext) ([]operator.Operator, error) { inputOperator, err := c.InputConfig.Build(context) if err != nil { return nil, err } receiver := make(logger.Receiver, c.BufferSize) context.Logger.AddReceiver(receiver) input := &Input{ InputOperator: inputOperator, receiver: receiver, } return []operator.Operator{input}, nil }
def rollback(self): pending_commits = self._get_pending_commits() if pending_commits: if pending_commits.get(self.config_session): commands = [ "configure session {} abort".format(self.config_session), "write memory", ] else: msg = "Current config session not found as pending commit-confirm" raise CommitError(msg) else: commands = ["configure replace flash:rollback-0", "write memory"] self.device.run_commands(commands) self.config_session = None
<reponame>connorskees/pdf<gh_stars>1-10 use std::{ borrow::Borrow, collections::{BTreeMap, HashMap}, convert::TryInto, }; use crate::{ font::Glyph, geometry::{Outline, Path, Point}, postscript::GraphicsOperator, }; use super::{ decode::decrypt_charstring, font::{Encoding, Type1PostscriptFont}, object::{PostScriptDictionary, PostScriptObject, PostScriptString, Procedure}, PostScriptError, PostScriptResult, PostscriptInterpreter, }; #[derive(Debug)] pub(crate) struct CharString(Vec<CharStringElement>); #[derive(Debug)] struct CharStringStack { stack: [f32; 24], end: u8, } impl CharStringStack { pub fn new() -> Self { Self { // we initialize all values to zero, but zero is not used as a // sentinel value stack: [0.0; 24], end: 0, } } pub fn pop(&mut self) -> PostScriptResult<f32> { if self.end == 0 { return Err(PostScriptError::StackUnderflow); } self.end -= 1; Ok(self.stack[self.end as usize]) } pub fn pop_front(&mut self) -> PostScriptResult<f32> { if self.end == 0 { return Err(PostScriptError::StackUnderflow); } self.end -= 1; let v = self.stack[0]; self.stack.rotate_left(1); Ok(v) } pub fn push(&mut self, n: f32) -> PostScriptResult<()> { if self.end >= 24 { return Err(PostScriptError::StackOverflow); } self.stack[self.end as usize] = n; self.end += 1; Ok(()) } pub fn is_empty(&self) -> bool { self.end == 0 } pub fn clear(&mut self) { self.end = 0; } } #[derive(Debug, Clone, Copy)] enum CharStringElement { Int(i32), Op(GraphicsOperator), } impl CharString { pub fn parse(b: &[u8]) -> PostScriptResult<Self> { let mut b = decrypt_charstring(b); if b.get(..4) == Some(&[0, 0, 0, 0]) { b = b[4..].to_vec(); } let mut i = 0; let mut elems = Vec::new(); while i < b.len() { let byte = b[i]; i += 1; match byte { v @ 0..=31 => match v { // y dy hstem (1) 1 => elems.push(CharStringElement::Op(GraphicsOperator::HorizontalStem)), // x dx vstem (3) 3 => elems.push(CharStringElement::Op(GraphicsOperator::VerticalStem)), // dy vmoveto (4) 4 => elems.push(CharStringElement::Op(GraphicsOperator::VerticalMoveTo)), // dx dy rlineto (5) 5 => elems.push(CharStringElement::Op(GraphicsOperator::RelativeLineTo)), // dx hlineto (6) 6 => elems.push(CharStringElement::Op(GraphicsOperator::HorizontalLineTo)), // dy vlineto (7) 7 => elems.push(CharStringElement::Op(GraphicsOperator::VerticalLineTo)), // dx1 dy1 dx2 dy2 dx3 dy3 rrcurveto (8) 8 => elems.push(CharStringElement::Op( GraphicsOperator::RelativeRelativeCurveTo, )), 9 => elems.push(CharStringElement::Op(GraphicsOperator::ClosePath)), 10 => elems.push(CharStringElement::Op(GraphicsOperator::CallSubroutine)), 11 => elems.push(CharStringElement::Op(GraphicsOperator::Return)), 12 => { match b[i] { 0 => elems.push(CharStringElement::Op(GraphicsOperator::DotSection)), 1 => elems.push(CharStringElement::Op(GraphicsOperator::VerticalStem3)), 2 => { elems.push(CharStringElement::Op(GraphicsOperator::HorizontalStem3)) } 6 => elems.push(CharStringElement::Op( GraphicsOperator::StandardEncodingAccentedCharacter, )), 7 => elems .push(CharStringElement::Op(GraphicsOperator::SideBearingWidth)), 12 => elems.push(CharStringElement::Op(GraphicsOperator::Div)), 16 => elems .push(CharStringElement::Op(GraphicsOperator::CallOtherSubroutine)), 17 => elems.push(CharStringElement::Op(GraphicsOperator::Pop)), 33 => { elems.push(CharStringElement::Op(GraphicsOperator::SetCurrentPoint)) } v => todo!("INVALID OP CODE: 12 {}", v), } i += 1; } 13 => { elems.push(CharStringElement::Op( GraphicsOperator::HorizontalSideBearingWidth, )); } 14 => elems.push(CharStringElement::Op(GraphicsOperator::EndChar)), 21 => elems.push(CharStringElement::Op(GraphicsOperator::RelativeMoveTo)), 22 => elems.push(CharStringElement::Op(GraphicsOperator::HorizontalMoveTo)), 30 => elems.push(CharStringElement::Op( GraphicsOperator::VerticalHorizontalCurveTo, )), 31 => elems.push(CharStringElement::Op( GraphicsOperator::HorizontalVerticalCurveTo, )), v => todo!("INVALID OP CODE: {}", v), }, // A charstring byte containing a value, v, between 32 and // 246 inclusive, indicates the integer v − 139. Thus, the // integer values from −107 through 107 inclusive may be // encoded in a single byte v @ 32..=246 => elems.push(CharStringElement::Int(v as i32 - 139)), // A charstring byte containing a value, v, between 247 and // 250 inclusive, indicates an integer involving the next byte, // w, according to the formula: // // [(v − 247) × 256] + w + 108 // // Thus, the integer values between 108 and 1131 inclusive // can be encoded in 2 bytes in this manner v @ 247..=250 => { let w = b[i] as i32; let int = ((v as i32 - 247) * 256) + w + 108; i += 1; elems.push(CharStringElement::Int(int)); } // A charstring byte containing a value, v, between 251 and // 254 inclusive, indicates an integer involving the next // byte, w, according to the formula: // // − [(v − 251) × 256] − w − 108 // // Thus, the integer values between −1131 and −108 inclusive // can be encoded in 2 bytes in this manner v @ 251..=254 => { let w = b[i] as i32; let int = -((v as i32 - 251) * 256) - w - 108; i += 1; elems.push(CharStringElement::Int(int)); } // Finally, if the charstring byte contains the value 255, // the next four bytes indicate a two’s complement signed integer. // The first of these four bytes contains the highest order // bits, the second byte contains the next higher order bits // and the fourth byte contains the lowest order bits. Thus, // any 32-bit signed integer may be encoded in 5 bytes in this // manner (the 255 byte plus 4 more bytes) 255 => { let bytes = &b[i..(i + 4)]; i += 5; let int = i32::from_be_bytes(bytes.try_into().unwrap()); elems.push(CharStringElement::Int(int)); } } } Ok(Self(elems)) } } #[derive(Debug)] pub(crate) struct CharStrings(HashMap<PostScriptString, CharString>); impl CharStrings { pub(super) fn from_dict( dict: PostScriptDictionary, interpreter: &mut PostscriptInterpreter, ) -> PostScriptResult<Self> { let mut char_strings = HashMap::new(); for (key, value) in dict.into_iter() { let char_string = match value { PostScriptObject::String(s) => { CharString::parse(interpreter.get_str(s).clone().as_bytes())? } _ => return Err(PostScriptError::TypeCheck), }; char_strings.insert(key, char_string); } Ok(Self(char_strings)) } pub(crate) fn from_string(&self, s: &PostScriptString) -> Option<&CharString> { self.0.get(s).or_else(|| { self.0 .get(&PostScriptString::from_bytes(b".notdef".to_vec())) }) } pub(crate) fn is_codepoint_defined(&self, c: u8) -> bool { self.0.contains_key(&PostScriptString::from_bytes(vec![c])) } } pub(crate) struct CharStringPainter<'a> { outline: Outline, width_vector: Point, current_path: Path, has_current_point: bool, subroutines: &'a [CharString], other_subroutines: &'a [Procedure], operand_stack: CharStringStack, interpreter: PostscriptInterpreter<'a>, encoding: &'a Encoding, char_strings: &'a CharStrings, gylph_cache: BTreeMap<u32, Glyph>, } impl<'a> CharStringPainter<'a> { pub fn new(font: &'a Type1PostscriptFont) -> Self { Self { outline: Outline::empty(), width_vector: Point::new(0.0, 0.0), current_path: Path::new(Point::new(0.0, 0.0)), has_current_point: false, subroutines: font.private.subroutines.as_deref().unwrap_or(&[]), other_subroutines: font.private.other_subroutines.as_deref().unwrap_or(&[]), encoding: &font.encoding, char_strings: &font.char_strings, operand_stack: CharStringStack::new(), interpreter: PostscriptInterpreter::new(&[]), gylph_cache: BTreeMap::new(), } } fn reinit(&mut self) { self.current_path = Path::new(Point::new(0.0, 0.0)); self.outline = Outline::empty(); self.width_vector = Point::new(0.0, 0.0); } pub fn evaluate(&mut self, char_code: u32) -> PostScriptResult<Glyph> { if let Some(glyph) = self.gylph_cache.get(&char_code) { return Ok(glyph.clone()); } self.reinit(); let charstring_name = self.encoding.get(char_code); if let Some(charstring) = self.char_strings.from_string(charstring_name.borrow()) { let glyph = self.evaluate_as_subroutine(charstring)?; self.gylph_cache.insert(char_code, glyph.clone()); Ok(glyph) } else { Ok(Glyph::empty()) } } fn evaluate_as_subroutine(&mut self, c: &CharString) -> PostScriptResult<Glyph> { for &elem in &c.0 { match elem { CharStringElement::Int(n) => self.operand_stack.push(n as f32)?, CharStringElement::Op(GraphicsOperator::HorizontalStem) => { let y = self.operand_stack.pop_front()?; let dy = self.operand_stack.pop_front()?; self.horizontal_stem(y, dy); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::VerticalStem) => { let x = self.operand_stack.pop_front()?; let dx = self.operand_stack.pop_front()?; self.vertical_stem(x, dx); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::VerticalMoveTo) => { let dy = self.operand_stack.pop_front()?; self.operand_stack.clear(); self.current_path.relative_move_to(0.0, dy); } CharStringElement::Op(GraphicsOperator::RelativeLineTo) => { let dx = self.operand_stack.pop_front()?; let dy = self.operand_stack.pop_front()?; self.operand_stack.clear(); self.current_path.relative_line_to(dx, dy); } CharStringElement::Op(GraphicsOperator::HorizontalLineTo) => { let dx = self.operand_stack.pop_front()?; self.horizontal_line_to(dx); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::VerticalLineTo) => { let dy = self.operand_stack.pop_front()?; self.vertical_line_to(dy); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::RelativeRelativeCurveTo) => { let dx1 = self.operand_stack.pop_front()?; let dy1 = self.operand_stack.pop_front()?; let dx2 = self.operand_stack.pop_front()?; let dy2 = self.operand_stack.pop_front()?; let dx3 = self.operand_stack.pop_front()?; let dy3 = self.operand_stack.pop_front()?; self.relative_relative_curve_to(dx1, dy1, dx2, dy2, dx3, dy3); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::ClosePath) => self.close_path(), CharStringElement::Op(GraphicsOperator::CallSubroutine) => { let subr_number = self.operand_stack.pop()? as usize; self.call_subroutine(subr_number)?; } CharStringElement::Op(GraphicsOperator::Return) => break, CharStringElement::Op(GraphicsOperator::DotSection) => todo!(), CharStringElement::Op(GraphicsOperator::VerticalStem3) => { let x0 = self.operand_stack.pop_front()?; let dx0 = self.operand_stack.pop_front()?; let x1 = self.operand_stack.pop_front()?; let dx1 = self.operand_stack.pop_front()?; let x2 = self.operand_stack.pop_front()?; let dx2 = self.operand_stack.pop_front()?; self.operand_stack.clear(); self.vertical_stem3(x0, dx0, x1, dx1, x2, dx2); } CharStringElement::Op(GraphicsOperator::HorizontalStem3) => { let y0 = self.operand_stack.pop_front()?; let dy0 = self.operand_stack.pop_front()?; let y1 = self.operand_stack.pop_front()?; let dy1 = self.operand_stack.pop_front()?; let y2 = self.operand_stack.pop_front()?; let dy2 = self.operand_stack.pop_front()?; self.operand_stack.clear(); self.horizontal_stem3(y0, dy0, y1, dy1, y2, dy2); } #[allow(unused)] CharStringElement::Op(GraphicsOperator::StandardEncodingAccentedCharacter) => { let asb = self.operand_stack.pop_front()?; let adx = self.operand_stack.pop_front()?; let ady = self.operand_stack.pop_front()?; let bchar = self.operand_stack.pop_front()?; let achar = self.operand_stack.pop_front()?; self.operand_stack.clear(); todo!() } #[allow(unused)] CharStringElement::Op(GraphicsOperator::SideBearingWidth) => { let sbx = self.operand_stack.pop_front()?; let sby = self.operand_stack.pop_front()?; let wx = self.operand_stack.pop_front()?; let wy = self.operand_stack.pop_front()?; self.operand_stack.clear(); todo!() } CharStringElement::Op(GraphicsOperator::Div) => { let num1 = self.operand_stack.stack[0]; let num2 = self.operand_stack.stack[1]; self.operand_stack.push(num1 / num2)?; } CharStringElement::Op(GraphicsOperator::CallOtherSubroutine) => { let other_subr_number = self.operand_stack.pop()?; let num_of_args = self.operand_stack.pop()?; let mut args = Vec::new(); for _ in 0..(num_of_args as u32) { args.push(self.operand_stack.pop()?); } self.call_other_subroutine(other_subr_number as usize, args)?; } CharStringElement::Op(GraphicsOperator::Pop) => match self.interpreter.pop()? { PostScriptObject::Float(n) => self.operand_stack.push(n)?, PostScriptObject::Int(n) => self.operand_stack.push(n as f32)?, _ => todo!(), }, CharStringElement::Op(GraphicsOperator::SetCurrentPoint) => todo!(), CharStringElement::Op(GraphicsOperator::HorizontalSideBearingWidth) => { let side_bearing_x_coord = self.operand_stack.pop_front()?; let width_vector_x_coord = self.operand_stack.pop_front()?; self.hsbw(side_bearing_x_coord, width_vector_x_coord); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::EndChar) => { // todo: rest of this operator if !self.current_path.subpaths.is_empty() { self.outline.paths.push(self.current_path.clone()); } break; } CharStringElement::Op(GraphicsOperator::RelativeMoveTo) => { let dx = self.operand_stack.pop_front()?; let dy = self.operand_stack.pop_front()?; self.relative_move_to(dx, dy); self.operand_stack.clear(); } #[allow(unused)] CharStringElement::Op(GraphicsOperator::HorizontalMoveTo) => { let dx = self.operand_stack.pop_front()?; self.operand_stack.clear(); todo!() } CharStringElement::Op(GraphicsOperator::VerticalHorizontalCurveTo) => { let dy1 = self.operand_stack.pop_front()?; let dx2 = self.operand_stack.pop_front()?; let dy2 = self.operand_stack.pop_front()?; let dx3 = self.operand_stack.pop_front()?; self.vertical_horizontal_curve_to(dy1, dx2, dy2, dx3); self.operand_stack.clear(); } CharStringElement::Op(GraphicsOperator::HorizontalVerticalCurveTo) => { let dx1 = self.operand_stack.pop_front()?; let dx2 = self.operand_stack.pop_front()?; let dy2 = self.operand_stack.pop_front()?; let dy3 = self.operand_stack.pop_front()?; self.horizontal_vertical_curve_to(dx1, dx2, dy2, dy3); self.operand_stack.clear(); } } } assert!(self.operand_stack.is_empty(), "{:?}", self.operand_stack); Ok(Glyph { outline: self.outline.clone(), width_vector: self.width_vector, }) } fn hsbw(&mut self, side_bearing_x_coord: f32, width_vector_x_coord: f32) { self.current_path = Path::new(Point::new(side_bearing_x_coord, 0.0)); self.width_vector = Point::new(width_vector_x_coord, 0.0); } #[allow(unused)] fn horizontal_stem(&mut self, y: f32, dy: f32) {} #[allow(unused)] fn vertical_stem(&mut self, x: f32, dx: f32) {} #[allow(unused)] fn horizontal_stem3(&mut self, y0: f32, dy0: f32, y1: f32, dy1: f32, y2: f32, dy2: f32) {} #[allow(unused)] fn vertical_stem3(&mut self, x0: f32, dx0: f32, x1: f32, dx1: f32, x2: f32, dx2: f32) {} fn call_subroutine(&mut self, subr_number: usize) -> PostScriptResult<()> { match subr_number { 0..=3 => todo!(), _ => { let subr = &self.subroutines[subr_number]; self.evaluate_as_subroutine(subr)?; } } Ok(()) } fn call_other_subroutine( &mut self, other_subr_number: usize, args: Vec<f32>, ) -> PostScriptResult<()> { match other_subr_number { 0..=3 => { let subr = &self.other_subroutines[other_subr_number]; for arg in args { self.interpreter.push(PostScriptObject::Float(arg)); } self.interpreter.execute_procedure(subr.clone()).unwrap(); } _ => todo!("use of reserved other subroutine idx"), } Ok(()) } fn relative_line_to(&mut self, dx: f32, dy: f32) { self.current_path.relative_line_to(dx, dy); } fn horizontal_vertical_curve_to(&mut self, dx1: f32, dx2: f32, dy2: f32, dy3: f32) { self.relative_relative_curve_to(dx1, 0.0, dx2, dy2, 0.0, dy3) } fn vertical_horizontal_curve_to(&mut self, dy1: f32, dx2: f32, dy2: f32, dx3: f32) { self.relative_relative_curve_to(0.0, dy1, dx2, dy2, dx3, 0.0) } fn vertical_line_to(&mut self, dy: f32) { self.current_path.relative_line_to(0.0, dy); } fn close_path(&mut self) { let current_point = self.current_path.current_point; self.current_path.close_path(); self.outline.paths.push(self.current_path.clone()); self.current_path = Path::new(current_point); } fn relative_move_to(&mut self, dx: f32, dy: f32) { self.current_path.relative_move_to(dx, dy); } fn relative_relative_curve_to( &mut self, dx1: f32, dy1: f32, dx2: f32, dy2: f32, dx3: f32, dy3: f32, ) { let current_point = self.current_path.current_point; let first_control_point = Point::new(current_point.x + dx1, current_point.y + dy1); let second_control_point = Point::new(current_point.x + dx1 + dx2, current_point.y + dy1 + dy2); let end = Point::new( current_point.x + dx1 + dx2 + dx3, current_point.y + dy1 + dy2 + dy3, ); self.current_path .cubic_curve_to(first_control_point, second_control_point, end); } fn horizontal_line_to(&mut self, dx: f32) { self.current_path.relative_line_to(dx, 0.0); } }
/** * Check if a zval is equal than a long value */ int phalcon_is_equal_long(zval *op1, zend_long op2) { zval op2_zval = {}; ZVAL_LONG(&op2_zval, op2); return phalcon_is_equal(op1, &op2_zval); }
#ifndef MOLTAROS_RTC_H #define MOLTAROS_RTC_H #include <stdint.h> /* Driver to interface with the system's Real-Time Clock, allowing the retrieval of date and time. */ void rtc_init(); uint8_t rtc_get_second(); uint8_t rtc_get_minute(); uint8_t rtc_get_hour(); uint8_t rtc_get_day(); uint8_t rtc_get_month(); uint8_t rtc_get_year(); // Print time void rtc_print(); #endif /* endif MOLTAROS_RTC_H */
<reponame>arnomoonens/Mussy-Robot # -*- coding: utf-8 -*- """ Created on Tue Nov 08 13:18:15 2016 @author: Greta """ from sklearn.svm import SVC import numpy from sklearn.externals import joblib from sklearn.cross_validation import cross_val_score, KFold from scipy.stats import sem def evaluate_cross_validation(clf, X, y, K): # create a k-fold cross validation iterator cv = KFold(len(y), K, shuffle=True, random_state=0) # by default the score used is the one returned by score method of the estimator (accuracy) scores = cross_val_score(clf, X, y, cv=cv) print (scores) print ("Mean score: {0:.3f} (+/-{1:.3f})".format(numpy.mean(scores), sem(scores))) def training(data): svc_1 = SVC(kernel='linear') #we create the target vector of -1 for sad images, 0 for normal, #and 1 for happy images, the data is composed by 15 sad image after 15 happy image and after 15 normal image zero=[int(i) for i in numpy.zeros(15)] one=[int(i) for i in numpy.ones(15)] minus1=[int(i) for i in numpy.repeat(-1,15)] target=numpy.concatenate((minus1,one,zero,),axis=0) #we test if the classifier work correctly with CROSS-VALIDATION #5 fold cross validation from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.20, random_state=0) from sklearn import neighbors n_neighbors =3 for weights in ['uniform', 'distance']: # we create an instance of Neighbours Classifier and fit the data. KNeigh = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) KNeigh.fit(X_train,y_train) print(KNeigh.predict(X_test)) print(y_test) #evaluate_cross_validation(KNeigh, X_train, y_train, 10) #svc is better!!! svc_1.fit(X_train,y_train) evaluate_cross_validation(svc_1, X_train, y_train, 10) joblib.dump(svc_1,'svc_1.pkl')
#include <vector> #include <deque> #include <queue> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <list> #include <numeric> #include <algorithm> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <cstdint> #include <functional> #include <array> #include <valarray> #include <iomanip> #include <cassert> #include <memory> #include <complex> #include <regex> using namespace std; #include <algorithm> #include <inttypes.h> #include <iostream> // From algo/io/baseio.hpp template<typename T> T read() { T res; std::cin >> res; return res; } template<typename T> void print(const T& t) { std::cout << t; } #ifndef LOCAL_PC #define DEFINE_SIMPLE_READ_AND_PRINT(TYPE_NAME, FORMAT) \ template<> \ TYPE_NAME read<TYPE_NAME>() { \ TYPE_NAME res; \ int cnt = scanf(FORMAT, &res); \ return res; \ }\ \ template<> \ void print<TYPE_NAME>(const TYPE_NAME& t) { \ printf(FORMAT, t); \ }\ DEFINE_SIMPLE_READ_AND_PRINT(int, "%d"); DEFINE_SIMPLE_READ_AND_PRINT(unsigned int, "%u"); DEFINE_SIMPLE_READ_AND_PRINT(int64_t, "%lld"); DEFINE_SIMPLE_READ_AND_PRINT(float, "%f"); DEFINE_SIMPLE_READ_AND_PRINT(double, "%lf"); DEFINE_SIMPLE_READ_AND_PRINT(char, "%c"); #endif // From iter/range.h // Range-based style iteration helpers. // // * range(end) // Iterates over [0, end), e.g.: // ` for (auto i : range(5)) { // ` print(i); // ` } // prints "0 1 2 3 4" // // * range(begin, end) // Iterates over [begin, end), e.g.: // ` for (auto i : range(5, 10)) { // ` print(i); // ` } // prints "5 6 7 8 9" namespace internal { template<typename ValueT> class IterableRange { public: class iterator { public: iterator(ValueT v__) : v_(v__) {} iterator& operator++() { ++v_; return *this; } bool operator==(iterator rhs) const { return v_ == rhs.v_; } bool operator!=(iterator rhs) const { return v_ != rhs.v_; } ValueT operator*() const { return v_; } ValueT operator->() const { return v_; } private: ValueT v_ = {}; }; IterableRange(ValueT begin__, ValueT end__) : begin_value_(std::min(begin__, end__)), end_value_(end__) {} iterator begin() const { return {begin_value_}; } iterator end() const { return {end_value_}; } private: ValueT begin_value_ = {}; ValueT end_value_ = {}; }; } // namespace internal template<typename ValueT> internal::IterableRange<ValueT> range(ValueT end) { return {{}, end}; } template<typename ValueT> internal::IterableRange<ValueT> range(ValueT begin, ValueT end) { return {begin, end}; } // From Solvers/11xx/1102/Solver1102D.cpp using namespace std; // Solution for Codeforces problem http://codeforces.com/contest/1102/problem/D class Solver1102D { public: void run(); }; void Solver1102D::run() { auto n = read<int>(); auto k = n / 3; auto seq = read<string>(); array<int, 3> counts = {0, 0, 0}; for (auto c: seq) counts[c - '0']++; int r = 0; int maxM = 0; vector<int> diffs(3); for (int i : range(3)) diffs[i] = k - counts[i]; for (int i : range(3)) { if (auto d = abs(diffs[i]); d > maxM) { maxM = d; r = i; } } vector<int> opts; for (int i : range(3)) if (i != r) opts.push_back(i); int p = opts[0]; int q = opts[1]; struct Change { int from; int to; int howMany; }; auto changes = (diffs[r] > 0) ? vector<Change>{{p, r, -diffs[p]}, {q, r, -diffs[q]}} : vector<Change>{{r, p, diffs[p]}, {r, q, diffs[q]}}; if (changes[0].from < changes[0].to && changes[1].from < changes[1].to) { if (changes[1].to > changes[0].to) swap(changes[0], changes[1]); } if (changes[0].from > changes[0].to && changes[1].from > changes[1].to) { if (changes[1].to < changes[0].to) swap(changes[0], changes[1]); } for (auto ch: changes) { // cerr << ch.from << " --> " << ch.to << " (" << ch.howMany << ")\n"; if (ch.to < ch.from) { for (auto it = begin(seq); it != end(seq); ++it) { if (*it == '0' + ch.from && ch.howMany > 0) { *it = '0' + ch.to; ch.howMany--; } } } else { for (auto it = rbegin(seq); it != rend(seq); ++it) { if (*it == '0' + ch.from && ch.howMany > 0) { *it = '0' + ch.to; ch.howMany--; } } } } cout << seq; } int main() { Solver1102D solver; solver.run(); }
<gh_stars>100-1000 import { Dto, DtoAttr } from "@batch-flask/core"; export class ContainerRegistryDto extends Dto<ContainerRegistryDto> { @DtoAttr() public username: string; @DtoAttr() public password: string; @DtoAttr() public registryServer: string; }
package webtests.seleniumeasy.pageobjects; import net.thucydides.core.annotations.DefaultUrl; @DefaultUrl("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html") public class MultipleRadioButtonForm extends SeleniumEasyForm { public void selectGender(String gender) { inRadioButtonGroup("gender").selectByValue(gender); } public void selectAgeGroup(String ageGroup) { inRadioButtonGroup("ageGroup").selectByValue(ageGroup); } public void getValues() { $(FormButton.withLabel("Get values")).click(); } }
/** * Makes an array clone * * @param members array to be cloned * @return clone */ private String[] copyover(Member[] members) { assert members != null; ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < members.length; i++) if (members[i] != null && !inactivityTable[i]) { list.add(members[i].fullname); } return list.toArray(new String[0]); }
Multiwavelength Transmission Spectroscopy Revisited for the Characterization of the Protein and Polystyrene Nanoparticle Mixtures Multiwavelength Transmission (MWT) UV-Vis-NIR spectroscopy, an effective technique often underutilized for the characterization of processes involving particulates, such as protein aggregation, is systematically explored using bovine serum albumin and a set of NIST-traceable particle size (PS) standards having certified particle diameters over the nominal size range of 30 to 100 nm. The PS standards are used as surrogates for protein aggregates and other contaminants such as oils and microbubbles. Therefore, the standards can be used to quantitatively modify the optical properties of protein solutions and thus observe the effect of the presence of aggregates and other particulates on their wavelength-dependent transmission spectra. The experimental results demonstrate that the changes induced in the optical density spectra of proteins due to the presence of PS particles are detectable and consistent with the expectations set by light scattering theory. It is demonstrated that the size and relative concentrations of the particle populations present in the protein samples can be quantified. Because of the considerable dynamic range of MWT UV-Vis-NIR spectroscopy for particle analysis and its real-time measurement capabilities, this type of spectroscopy can be effectively used for the characterization of protein aggregates and for the continuous real-time monitoring of aggregation processes and for the identification and quantification of contaminants in protein-based products.
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import logging from indra.util import read_unicode_csv logger = logging.getLogger(__name__) from protmapper.uniprot_client import * def _build_uniprot_subcell_loc(): fname = os.path.dirname(os.path.abspath(__file__)) +\ '/../resources/uniprot_subcell_loc.tsv' csv_rows = read_unicode_csv(fname, delimiter='\t') # Skip the header row up_to_go = {} for row in csv_rows: upid = row[0] goid = row[1] up_to_go[upid] = goid return up_to_go uniprot_subcell_loc = _build_uniprot_subcell_loc()
West Ham could move for Oriol Romeu (Picture: Getty Images) West Ham are considering a move for out-of-favour Chelsea midfielder Oriol Romeu. The former Barcelona starlet is set to be surplus to requirements at Stamford Bridge this summer and Sam Allardyce is reportedly considering making a bid. Romeu spent last season on-loan at Valencia where he showed flashes of the ability that convinced Chelsea to buy him, but he is unlikely to get a look in next term. Romeu has spent this season on-loan at Valencia (Picture: Getty) West Ham are looking to strengthen their midfield options after a dismal end to last season, which saw supporters turn on manager Allardyce and his coaching staff. A tough tackling and technically excellent defending midfielder, Romeu could be a base for the Hammers to build on next term, as they aim for a more attractive brand of football. It’s not yet clear whether Romeu would fancy staying in the Premier League, having already admitted his desire to return to Valencia, but no offers have arrived for the player yet. MORE: PSG set to make last-ditch Eden Hazard bid
<reponame>haibowen/AndroidStudy package com.amaze.filemanager.database; import android.support.annotation.NonNull; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.amaze.filemanager.filesystem.ssh.SshClientUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(AndroidJUnit4.class) public class UtilsHandlerTest { private UtilsHandler utilsHandler; @Before public void setUp(){ utilsHandler = new UtilsHandler(InstrumentationRegistry.getTargetContext()); utilsHandler.onCreate(utilsHandler.getWritableDatabase()); utilsHandler.getWritableDatabase().execSQL("DELETE FROM sftp;"); } @Test public void testEncodeEncryptUri1(){ performTest("ssh://test:testP@[email protected]:5460"); } @Test public void testEncodeEncryptUri2(){ performTest("ssh://test:testP@##[email protected]:22"); } @Test public void testEncodeEncryptUri3(){ performTest("ssh://[email protected]:testP@[email protected]:22"); } @Test public void testEncodeEncryptUri4(){ performTest("ssh://test@example.<EMAIL>:testP@ssw0##[email protected]:22"); } private void performTest(@NonNull final String origPath){ String encryptedPath = SshClientUtils.encryptSshPathAsNecessary(origPath); utilsHandler.addSsh("Test", encryptedPath, "fc00:e968:6179::de52:7100:88:99:aa:bb:cc:dd:ee:ff", null, null); List<String[]> result = utilsHandler.getSftpList(); assertEquals(1, result.size()); assertEquals("Test", result.get(0)[0]); assertEquals(origPath, result.get(0)[1]); assertEquals("00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff", utilsHandler.getSshHostKey(origPath)); } }
// If goal has been reached build plan std::vector<geometry_msgs::PoseStamped> RRTPlannerHelper::build_plan( std::vector<qTree> _treeGraph) { ROS_INFO("Building Plan"); _plan.clear(); qTree qAdd = _treeGraph.back(); while (qAdd.myIndex != 0) { _plan.insert(_plan.begin(), qAdd.q); double nearI = qAdd.nearIndex; qAdd = _treeGraph[nearI]; } _plan.insert(_plan.begin(), _start); for (int i = 0; i < _plan.size(); i++) { map_rviz(_plan[i].pose.position.x, _plan[i].pose.position.y); } return _plan; }
Samsung’s Galaxy S III is the Android smartphone to beat, the first reviewers of the phones concluded, as the phone arrives in the U.S. on AT&T and Sprint to boot. All major carriers have signed up to sell the S III and, this time around, you won’t get any silly names or slightly changed designs--the phone is set to look exactly the same for AT&T, Verizon, Sprint, and T-Mobile aside from carrier branding on the back. [Read PCWorld's Full Review: Samsung Galaxy S III: Your Next Android Phone] There are however two differences between the U.S. variant and the international sibling: The quad-core processor has been swapped for a dual-core 1.5GHz chip, but the RAM has been bumped from 1GB to 2GB. The other specs include a 4.8-inch screen with a resolution of 1280 pixels by 720 pixels, an 8MP camera with 1080p video-capture capability, and the Android 4.0 operating system on board and topped with Samsung’s TouchWiz interface. Prices start at $200 with a two-year contract for the 16GB model. In PCWorld’s review of the Samsung Galaxy S III, Ginny Mies found the large display brighter and more vivid than on the Galaxy Nexus, while for performance, the S III was only topped by the LG Optimus 4X HD, which has a quad-core NVidia Tegra 3 processor. Mies found the camera to be very good too, concluding the Galaxy S III lives up to the hype. “At its core, the Galaxy S III is an excellent phone, and Samsung did the right thing in making it uniform across the multiple carriers,” she wrote. Complicated to Use? Walt Mossberg reviewing for All Things D agrees: “The Galaxy S III is a solid, capable phone. But its most important feature may be ubiquity.” Mossberg brings up an interesting point: “The Galaxy S III lacks any game-changing capabilities and is instead packed with a dizzying array of minor new tricks that users will turn to frequently. There are so many of these that it can take hours to learn and configure them. I had the strong impression Samsung’s designers failed to focus and just threw in as many technical twists as they could, some of which didn’t work very well.” David Pogue at New York Times was also impressed with the Galaxy S III, but noted “with great flexibility comes great complexity. The phone bombards you with warnings and disclaimers--sometimes upside-down. You really need a Learning Annex course to master this thing.” Wired’s Nathan Olivarez-Giles was less impressed with the phone though, saying “simply doesn’t feel like a finished product. It could use more polish, more thought, and a more elegant user experience.” He also picks on Samsung’s TouchWiz software, which “includes a lot of half-baked features that aim for innovation but miss the mark--sharing apps in particular. Styling is boring, and not exciting enough for a flagship phone.” Vlad Savov at The Verge wrote the “Galaxy S III is a technological triumph. Not at first sight, perhaps, but Samsung has done the overwhelming majority of things right. The camera is easily the best I’ve used on an Android device, the processor claims the title of benchmarking champion, and the customizations layered on top of Ice Cream Sandwich are mostly unobtrusive and sometimes even helpful.” He does, however. note “the extra-large size of this phone, even with its great ergonomics, may prove to be a stumbling block for those who can’t comfortably fit a 4.8-inch handset into their daily routine.” USA Today’s Ed Baig couldn’t fault the S III besides the lacking S Voice feature, which doesn’t work as smooth as Siri on the iPhone. “So is it an iPhone killer?” asks Hayley Tsukayama at the Washington Post. “Let’s call it a worthy contender. It’s not worth breaking your current contract over, but if you’re in the market for a new, top-of-the-line Android phone then [the S III] should be a top consideration.” Follow Daniel Ionescu and Today @ PCWorld on Twitter
<reponame>romneycf/grannys-game export default function evenOdd(n: number) { if (n % 2 === 0) return true; return false; }
. International cooperation in health is a critical input for national development. Available resources in the health sector are scarce and are frequently badly used. For these reasons national and international efforts are required to reorient the delivery of health services. Many of the social and economic problems of the 1980s still subsist, and even though outstanding political changes are evidenced, the war situation unbalanced the global order. Poverty affects almost a quarter of the human population. It is necessary to increase the resources appointed to the social sector, particularly those devoted to health and nutrition programmes. Technical exchange between countries has increased considerably since its origins at the beginning of the century. The present international cooperation in health is based on the analysis of the countries health situation and health services within the global socio-economic and political framework; it concentrates efforts around social and epidemiological priorities; considers man as central axle for development and encourages social participation in health. International technical cooperation is also giving increasing attention to environmental problems, rising new pathologies, to the promotion of scientific research and to the development of adequate technology for each national situation.
def is_global(wire): return bool(global_entry_re.match(wire) or global_left_right_re.match(wire) or global_up_down_re.match(wire) or global_branch_re.match(wire) or hfsn_entry_re.match(wire) or hfsn_left_right_re.match(wire) or hfsn_l2r_re.match(wire) or hfsn_up_down_re.match(wire) or hfsn_branch_re.match(wire) or center_mux_glb_out_re.match(wire) or center_mux_ebrg_out_re.match(wire) or cib_out_to_hfsn_re.match(wire) or cib_out_to_glb_re.match(wire) or cib_out_to_eclk_re.match(wire) or eclk_out_re.match(wire) or pll_out_re.match(wire) or clock_pin_re.match(wire) or dcc_sig_re.match(wire) or dcm_sig_re.match(wire) or eclkbridge_sig_re.match(wire) or osc_clk_re.match(wire) or sed_clk_re.match(wire) or pll_clk_re.match(wire) or pg_re.match(wire) or inrd_re.match(wire) or lvds_re.match(wire) or ddrclkpol_re.match(wire) or dqsr90_re.match(wire) or dqsw90_re.match(wire))
<gh_stars>0 import * as React from "react"; export type Props = {}; const CornerIndicator: React.FC = () => <th className="Spreadsheet__header" />; export default CornerIndicator;
def line(brief, verbose): cmd = "consutil show" + (" -b" if brief else "") run_command(cmd, display_cmd=verbose) return
/* * Copyright (C) 2019 Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ package com.intel.kms.saml.jaxrs; import com.intel.dcsg.cpg.io.UUID; import com.intel.dcsg.cpg.validation.ValidationUtil; import com.intel.dcsg.cpg.x509.X509Util; import com.intel.kms.saml.api.Certificate; import com.intel.kms.saml.api.CertificateCollection; import com.intel.kms.saml.api.CertificateFilterCriteria; import com.intel.kms.saml.api.CertificateLocator; import com.intel.mtwilson.jaxrs2.NoLinks; import com.intel.mtwilson.jaxrs2.mediatype.CryptoMediaType; import com.intel.mtwilson.jaxrs2.server.resource.AbstractCertificateJsonapiResource; import com.intel.mtwilson.launcher.ws.ext.V2; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; /** * * @author jbuhacoff */ @V2 @Path("/saml-certificates") public class SamlCertificates extends AbstractCertificateJsonapiResource<Certificate, CertificateCollection, CertificateFilterCriteria, NoLinks<Certificate>, CertificateLocator> { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SamlCertificates.class); private SamlCertificateRepository repository; public SamlCertificates() { try { repository = new SamlCertificateRepository(); } catch(Exception e) { log.error("SamlCertificateRepository not available", e); } } @Override protected CertificateCollection createEmptyCollection() { return new CertificateCollection(); } @Override protected SamlCertificateRepository getRepository() { if( repository == null ) { throw new IllegalStateException("Repository not available"); } return repository; } @Override @GET public CertificateCollection searchCollection(@BeanParam CertificateFilterCriteria selector) { try { ValidationUtil.validate(selector); CertificateCollection collection = getRepository().search(selector); List<Certificate> documents = collection.getDocuments(); for(Certificate document : documents) { // the href should really be to the json (no suffix) document... we should use a link for the cert format document.getMeta().put("href", String.format("/v1/saml-certificates/%s.crt", document.getId().toString())); // XXX TODO: because we're overriding search method from superclass, we cant get new parameter context httprequest and find our base url... hard-coding /v1 here is not good. } return collection; } catch(Exception e) { log.error("Search on SAML certificates failed", e); CertificateCollection collection = new CertificateCollection(); collection.getMeta().put("error", "unable to perform the search; check filter criteria"); return collection; } } @POST @Consumes({CryptoMediaType.APPLICATION_PKIX_CERT}) @Produces({MediaType.APPLICATION_JSON}) public Certificate createOneX509CertificateDER(byte[] certificateBytes) { try { X509Certificate certificate = X509Util.decodeDerCertificate(certificateBytes); Certificate item = new Certificate(); item.setId(new UUID()); item.setCertificate(certificate.getEncoded()); getRepository().create(item); return item; } catch(CertificateException e) { throw new WebApplicationException(Status.BAD_REQUEST); // input error } } @POST @Consumes({CryptoMediaType.APPLICATION_X_PEM_FILE}) @Produces({MediaType.APPLICATION_JSON}) public Certificate createOneX509CertificatePEM(String certificatePem) { try { X509Certificate certificate = X509Util.decodePemCertificate(certificatePem); Certificate item = new Certificate(); item.setId(new UUID()); item.setCertificate(certificate.getEncoded()); getRepository().create(item); return item; } catch(CertificateException e) { throw new WebApplicationException(Status.BAD_REQUEST); // input error } } }
def _fsck_ext(device): msgs = { 0: "No errors", 1: "Filesystem errors corrected", 2: "System should be rebooted", 4: "Filesystem errors left uncorrected", 8: "Operational error", 16: "Usage or syntax error", 32: "Fsck canceled by user request", 128: "Shared-library error", } return msgs.get( __salt__["cmd.run_all"]("fsck -f -n {}".format(device))["retcode"], "Unknown error", )
// GetPulls is a function handler that retrieves a set of PR's from the DB and writes them with the http.ResponseWriter func (wrap *Wrapper) GetPulls(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) repoID, err := strconv.Atoi(vars["repoID"]) if err != nil { panic(err) } var pulls []Pull err = wrap.db.Model(&pulls). Where("pull.repo_id = ?", repoID). Apply(orm.Pagination(r.URL.Query())). Select() if err != nil { panic(err) } wg := &sync.WaitGroup{} pLen := len(pulls) ePulls := make([]*exports.Pull, pLen) wg.Add(pLen) for idx, pull := range pulls { go func(idx int, pull Pull) { defer wg.Done() var uPull unmarshalling.Pull pullBytes := []byte(pull.Data) err = json.Unmarshal(pullBytes, &uPull) if err != nil { panic(err) } var ePull exports.Pull copier.Copy(&ePull, &uPull) eComments := wrap.buildExportedComments(&pull) ePull.Comments = eComments ePulls[idx] = &ePull }(idx, pull) } wg.Wait() addResponseHeaders(w) if err := jsonapi.MarshalPayload(w, ePulls); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
. In the present paper we have shown that JB6 and PDV murine skin carcinoma cells, as well as previously described sarcoma B6-4 cells, can revert to a nontumor phenotype. Revertant carcinoma clones could not grow in soft agar conditions and like sarcoma revertants acquired dependence on peptide growth factors, and exhibited a reduced expression of c-jun. Spontaneous revertants were shown to be instable. They could revert back to a transformed phenotype in 1-5 months of in vitro passaging. Being inoculated in syngeneic animals, these transformed cells show a recurrence in 2-5 months, similar to that of a dormant metastasis. Thus, dormant revertant cells are believed to be included in many tumors of different origin. So, spontaneous reversions of tumor cells may play an important role in the dormant metastatic process. The cause of these frequent spontaneous transient reversions and revertant instability appears to be of epigenetic nature. Causes and mechanisms of cell transformations and reversions remain to be clarified.
use borsh::{BorshDeserialize, BorshSerialize}; use sha2::{Digest, Sha256}; use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, sysvar::{clock::Clock, Sysvar}, }; use std::collections::hash_map::DefaultHasher; use std::convert::TryFrom; use std::hash::{Hash, Hasher}; #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct Command { pub counter: u32, } /// Define the type of state stored in accounts #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct GreetingAccount { /// number of greetings pub counter: u32, pub random: u32, } use switchboard_program::VrfAccount; fn my_hash<T>(obj: T) -> u64 where T: Hash, { let mut hasher = DefaultHasher::new(); obj.hash(&mut hasher); hasher.finish() } // Declare and export the program's entrypoint entrypoint!(process_instruction); // yorkid account public key: <KEY>, program id: DW6HET1JQjkMsszJK1pXdJWhs6enSYBgyMXq9zz4qtzP // york url https://explorer.solana.com/address/DW6HET1JQjkMsszJK1pXdJWhs6enSYBgyMXq9zz4qtzP?cluster=devnet // Program entrypoint's implementation pub fn process_instruction( program_id: &Pubkey, // Public key of the account the hello world program was loaded into accounts: &[AccountInfo], // The account to say hello to instruction_data: &[u8], // Ignored, all helloworld instructions are hellos ) -> ProgramResult { let mut instruction_data_mut = instruction_data; msg!("Hello World Rust program entrypoint"); let command = Command::deserialize(&mut instruction_data_mut)?; msg!("york000"); msg!("{:?}", command.counter); msg!("york0"); // Iterating accounts is safer then indexing let accounts_iter = &mut accounts.iter(); msg!("york01123"); // Get the clock sysvar via syscall msg!("york019999"); let clock_via_sysvar = Clock::get()?; // msg!("york01"); // Or deserialize the account into a clock struct // let clock_sysvar_info = next_account_info(accounts_iter)?; // msg!("york02"); // let clock_via_account = Clock::from_account_info(clock_sysvar_info)?; // Both produce the same sysvar // assert_eq!(clock_via_sysvar, clock_via_account); // Note: `format!` can be very expensive, use cautiously msg!("york3"); msg!("{:?}", clock_via_sysvar.unix_timestamp); msg!("york3123"); msg!("{:?}", clock_via_sysvar.slot); msg!("york1"); // msg!( // "{:x}", // Sha256::digest(clock_via_sysvar.unix_timestamp.to_string().as_bytes()) // ); let u32_slot = u32::try_from(clock_via_sysvar.slot).unwrap(); let u64_command_counter = u64::try_from(command.counter).unwrap(); let u64_ans = (my_hash(u32_slot) % u64_command_counter) + 1; let ans = u32::try_from(u64_ans).unwrap(); msg!("york145678"); msg!("{:?}", u32_slot); msg!("york2"); msg!("{:?}", my_hash(u32_slot)); msg!("york222223"); msg!("{:?}", u64_ans); msg!("york233333"); msg!("{:?}", ans); msg!("york5555"); // msg!("{:?}", clock_via_account); // Get the account to say hello to let account = next_account_info(accounts_iter)?; // The account must be owned by the program in order to modify its data if account.owner != program_id { msg!("Greeted account does not have the correct program id"); return Err(ProgramError::IncorrectProgramId); } // Increment and store the number of times the account has been greeted let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?; greeting_account.counter += 1; greeting_account.random = ans; greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?; msg!("Greeted {} time(s)!", greeting_account.counter); Ok(()) } // Sanity tests #[cfg(test)] mod test { use super::*; use solana_program::clock::Epoch; use std::mem; #[test] fn test_sanity() { let program_id = Pubkey::default(); let key = Pubkey::default(); let mut lamports = 0; let mut data = vec![0; mem::size_of::<u32>()]; let owner = Pubkey::default(); let account = AccountInfo::new( &key, false, true, &mut lamports, &mut data, &owner, false, Epoch::default(), ); let instruction_data: Vec<u8> = Vec::new(); let accounts = vec![account]; assert_eq!( GreetingAccount::try_from_slice(&accounts[0].data.borrow()) .unwrap() .counter, 0 ); process_instruction(&program_id, &accounts, &instruction_data).unwrap(); assert_eq!( GreetingAccount::try_from_slice(&accounts[0].data.borrow()) .unwrap() .counter, 1 ); process_instruction(&program_id, &accounts, &instruction_data).unwrap(); assert_eq!( GreetingAccount::try_from_slice(&accounts[0].data.borrow()) .unwrap() .counter, 2 ); } }
// WriteTo implements io.WriterTo func (p *Conn) WriteTo(w io.Writer) (int64, error) { p.once.Do(func() { p.readErr = p.readHeader() }) if p.readErr != nil { return 0, p.readErr } return p.bufReader.WriteTo(w) }
<reponame>sabasayer/enterprise<gh_stars>0 import { EnterpriseApiHelper } from '../enterprise-api.helper'; describe("Enterprise Api Helper ", () => { global.window = Object.create(window); Object.defineProperty(window, 'location', { value: { host: 'test.com' } }); it("should convert data to query string", async () => { const data = { name: 'salih', age: 2 }; const url: string = '//my-site.com/'; const convertedUrl = EnterpriseApiHelper.createUrl(url, data); expect(convertedUrl).toBe('//my-site.com/?name=salih&age=2'); }) it("should ensure last character to be slash", () => { const result = EnterpriseApiHelper.ensureLastCharacterToBeSlash('//test.com'); expect(result).toBe('//test.com/') }) it("should get hostname from end points", () => { const result = EnterpriseApiHelper .getHostNameFromEndPoints({ 'asd.com': 'forest.com', 'test.com': 'wololo.com' }); expect(result).toBe('wololo.com') }) it("should create base url from baseUrl", () => { const result = EnterpriseApiHelper.createBaseUrl({ baseUrl: 'https://test.com' }); expect(result).toBe('https://test.com/') }) it("should create base url from host, protocol, prefix", () => { const result = EnterpriseApiHelper.createBaseUrl({ protocol: 'http', hostName: 'test.com', prefix: 'json' }); expect(result).toBe('http://test.com/json/') }) it("should create base url with end points", () => { const result = EnterpriseApiHelper.createBaseUrl({ endpoints: { 'test.com': 'testoloji.com' }, languagePrefix: 'en-us' }) expect(result).toBe('//testoloji.com/en-us/') }) it("should create unique key", () => { const key = EnterpriseApiHelper.createUniqueKey('https://test.com', { id: 1 }); expect(key).toBe('2_https://test.com_{"id":1}') }) it("should create cancel token",()=>{ const token = EnterpriseApiHelper.createCancelToken(); expect(token.cancel).toBeDefined() }) })
def forward(self, query, key, value, mask=None): n_batch = query.size(0) q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k) k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k) v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k) q = q.transpose(1, 2) k = k.transpose(1, 2) v = v.transpose(1, 2) dim = v.size(-1) (q, k) = map(lambda x: x * (dim ** -0.25), (q, k)) q = q.softmax(dim=-1) k = k.softmax(dim=-2) context_einsum_eq = 'bhnd,bhne->bhde' context = torch.einsum(context_einsum_eq, k, v) attn_einsum_eq = 'bhnd,bhde->bhne' x = torch.einsum(attn_einsum_eq, q, context) x = ( x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k) ) return self.linear_out(x)
The ironclad CSS Georgia was scuttled by its crew in 1864. Now the civil war wreck is to be raised and preserved to improve access to the port of Savannah The US navy is preparing to send one if its premier diving teams to Georgia, to help salvage a Confederate warship from the depths of the Savannah river. Before it ever fired a shot, the 1,200-ton ironclad CSS Georgia was scuttled by its own crew to prevent its capture by General William Tecumseh Sherman when his Union army took Savannah in December 1864. Today, it is considered a captured enemy vessel and is property of the US navy. The shipwreck is being removed as part of a $703m project to deepen the river channel so larger cargo ships can reach the port of Savannah. Before the harbour can be deepened, the CSS Georgia has to be raised. After years of planning, archaeologists began tagging and recording the locations of thousands of pieces from the shipwreck in January. They have been able to bring smaller artefacts to the surface, but the navy is being called in to raise the 120ft-long ship’s larger sections and weapons. Navy divers are scheduled to arrive at the site near downtown Savannah about 100 yards from the shore on 1 June. The navy divers assigned to the project are from the same unit that has participated in some of the military’s highest-profile salvage operations. That includes the civil war ironclad USS Monitor, TWA Flight 800, Swiss Air Flight 111, as well as the space shuttles Challenger and Columbia. Divers from the Virginia Beach-based Mobile Diving Salvage Unit 2 also provided damage assessments and repairs on the USS Cole following the terrorist attack on it in Yemen in 2000 and pulled up wreckage from an F-16 that crashed off the eastern shore of Virginia in 2013. In Georgia, navy divers will pull up parts of the ship’s armor systems, steam engine components and small structure pieces. They will eventually be sent to one of the US Naval History and Heritage Command’s repositories and Conservation Research Laboratory at Texas A&M University in College Station, Texas. “The desire to maintain the ship in somewhat of a conservable state is one of the primary concerns. That’s a little bit different from typical salvage. Oftentimes, aside from human remains or things like a flight data recorder, it’s simply object recovery. It’s bringing it up safely and disposing of it. Whereas these artefacts will be preserved for future generations,” said Chief Warrant Officer Jason Potts, the on-scene commander for the CSS Georgia operation. The weapons, which include four cannons and about 50 projectiles that are either rifle shells or cannon balls, will be handled by explosive ordnance disposal technicians from Kings Bay, Georgia. Potts said the weapons systems would be removed first, then divers would focus on the propeller and main shaft, portions of its steam machinery and large portions of the ship’s armoured encasement. The armor for the ship, which was anchored off Fort Jackson as a floating gun battery, was made out of railroad iron. Archaeologists will still make sure there are no other remnants remaining after the navy divers leave at the end of July. Work to preserve and catalogue all of the individual artefacts is expected to take another year or more.
<reponame>q4a/fonline<filename>Source/Common/ApplicationHeadless.cpp<gh_stars>100-1000 // __________ ___ ______ _ // / ____/ __ \____ / (_)___ ___ / ____/___ ____ _(_)___ ___ // / /_ / / / / __ \/ / / __ \/ _ \ / __/ / __ \/ __ `/ / __ \/ _ \ // / __/ / /_/ / / / / / / / / / __/ / /___/ / / / /_/ / / / / / __/ // /_/ \____/_/ /_/_/_/_/ /_/\___/ /_____/_/ /_/\__, /_/_/ /_/\___/ // /____/ // FOnline Engine // https://fonline.ru // https://github.com/cvet/fonline // // MIT License // // Copyright (c) 2006 - present, <NAME> aka cvet <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Todo: move different renderers to separate modules #include "Application.h" #include "DiskFileSystem.h" #include "Log.h" #include "StringUtils.h" #include "WinApi-Include.h" Application* App; #if FO_WINDOWS && FO_DEBUG static _CrtMemState CrtMemState; #endif const uint Application::AppRender::MAX_ATLAS_WIDTH = 1024; const uint Application::AppRender::MAX_ATLAS_HEIGHT = 1024; const uint Application::AppRender::MAX_BONES = 32; const int Application::AppAudio::AUDIO_FORMAT_U8 = 0; const int Application::AppAudio::AUDIO_FORMAT_S16 = 1; struct RenderTexture::Impl { virtual ~Impl() = default; }; RenderTexture::~RenderTexture() { } struct RenderEffect::Impl { virtual ~Impl() = default; }; RenderEffect::~RenderEffect() { } auto RenderEffect::IsSame(string_view name, string_view defines) const -> bool { return _str(name).compareIgnoreCase(_effectName) && defines == _effectDefines; } auto RenderEffect::CanBatch(const RenderEffect* other) const -> bool { return false; } struct RenderMesh::Impl { virtual ~Impl() = default; }; RenderMesh::~RenderMesh() { } void InitApplication(GlobalSettings& settings) { // Ensure that we call init only once static std::once_flag once; auto first_call = false; std::call_once(once, [&first_call] { first_call = true; }); if (!first_call) { throw AppInitException("Application::Init must be called only once"); } App = new Application(settings); } Application::Application(GlobalSettings& settings) { // Skip SDL allocations from profiling #if FO_WINDOWS && FO_DEBUG ::_CrtMemCheckpoint(&CrtMemState); #endif } #if FO_IOS void Application::SetMainLoopCallback(void (*callback)(void*)) { } #endif void Application::BeginFrame() { _onFrameBeginDispatcher(); } void Application::EndFrame() { _onFrameEndDispatcher(); } auto Application::AppWindow::GetSize() const -> tuple<int, int> { auto w = 1000; auto h = 1000; return {w, h}; } void Application::AppWindow::SetSize(int w, int h) { } auto Application::AppWindow::GetPosition() const -> tuple<int, int> { auto x = 0; auto y = 0; return {x, y}; } void Application::AppWindow::SetPosition(int x, int y) { } auto Application::AppWindow::GetMousePosition() const -> tuple<int, int> { auto x = 100; auto y = 100; return {x, y}; } void Application::AppWindow::SetMousePosition(int x, int y) { } auto Application::AppWindow::IsFocused() const -> bool { return true; } void Application::AppWindow::Minimize() { } auto Application::AppWindow::IsFullscreen() const -> bool { return false; } auto Application::AppWindow::ToggleFullscreen(bool enable) -> bool { NON_CONST_METHOD_HINT(); return false; } void Application::AppWindow::Blink() { } void Application::AppWindow::AlwaysOnTop(bool enable) { } auto Application::AppRender::CreateTexture(uint width, uint height, bool linear_filtered, bool with_depth) -> RenderTexture* { NON_CONST_METHOD_HINT(); return nullptr; } auto Application::AppRender::GetTexturePixel(RenderTexture* tex, int x, int y) const -> uint { return 0; } auto Application::AppRender::GetTextureRegion(RenderTexture* tex, int x, int y, uint w, uint h) const -> vector<uint> { RUNTIME_ASSERT(w && h); const auto size = w * h; vector<uint> result(size); return result; } void Application::AppRender::UpdateTextureRegion(RenderTexture* tex, const IRect& r, const uint* data) { } void Application::AppRender::SetRenderTarget(RenderTexture* tex) { } auto Application::AppRender::GetRenderTarget() -> RenderTexture* { return nullptr; } void Application::AppRender::ClearRenderTarget(uint color) { } void Application::AppRender::ClearRenderTargetDepth() { } void Application::AppRender::EnableScissor(int x, int y, uint w, uint h) { } void Application::AppRender::DisableScissor() { } auto Application::AppRender::CreateEffect(string_view /*name*/, string_view /*defines*/, const RenderEffectLoader & /*file_loader*/) -> RenderEffect* { return nullptr; } void Application::AppRender::DrawQuads(const Vertex2DVec& vbuf, const vector<ushort>& ibuf, uint pos, RenderEffect* effect, RenderTexture* tex) { } void Application::AppRender::DrawPrimitive(const Vertex2DVec& /*vbuf*/, const vector<ushort>& /*ibuf*/, RenderEffect* /*effect*/, RenderPrimitiveType /*prim*/) { } void Application::AppRender::DrawMesh(RenderMesh* mesh, RenderEffect* /*effect*/) { } auto Application::AppInput::PollEvent(InputEvent& event) -> bool { return false; } void Application::AppInput::PushEvent(const InputEvent& event) { } void Application::AppInput::SetClipboardText(string_view text) { } auto Application::AppInput::GetClipboardText() -> string { return string(); } auto Application::AppAudio::IsEnabled() -> bool { return false; } auto Application::AppAudio::GetStreamSize() -> uint { RUNTIME_ASSERT(IsEnabled()); return 0u; } auto Application::AppAudio::GetSilence() -> uchar { RUNTIME_ASSERT(IsEnabled()); return 0u; } void Application::AppAudio::SetSource(AudioStreamCallback stream_callback) { RUNTIME_ASSERT(IsEnabled()); } auto Application::AppAudio::ConvertAudio(int format, int channels, int rate, vector<uchar>& buf) -> bool { RUNTIME_ASSERT(IsEnabled()); return true; } void Application::AppAudio::MixAudio(uchar* output, uchar* buf, int volume) { RUNTIME_ASSERT(IsEnabled()); } void Application::AppAudio::LockDevice() { RUNTIME_ASSERT(IsEnabled()); } void Application::AppAudio::UnlockDevice() { RUNTIME_ASSERT(IsEnabled()); } void MessageBox::ShowErrorMessage(string_view title, string_view message, string_view traceback) { }
<gh_stars>1-10 //----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 <NAME> // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once namespace s3d { namespace OpenCV_Bridge { inline cv::Rect ToCVRect(const Rect& rect) { return{ rect.x, rect.y, rect.w, rect.h }; } inline cv::Mat GetMatView(Image& image) { return{ cv::Size{ image.width(), image.height() }, CV_8UC4, image.dataAsUint8(), image.stride() }; } inline constexpr int32 ConvertBorderType(const BorderType borderType) noexcept { switch (borderType) { case BorderType::Replicate: return cv::BORDER_REPLICATE; //case BorderType::Wrap: // return cv::BORDER_WRAP; case BorderType::Reflect: return cv::BORDER_REFLECT; case BorderType::Reflect_101: return cv::BORDER_REFLECT101; default: return cv::BORDER_DEFAULT; } } } }
There is no biological requirement for cow's milk. It is nature's perfect food, but only if you are a calf. The evidence of its benefits is overstated, and the evidence of its harm to human populations is increasing. The white-mustached celebrities paid by the Dairy Council promote the wonders of milk in their "Got Milk" ads. Scientists are increasingly asking, "Got Proof?" Our government still hasn't caught on, in part because of the huge dairy lobby driving nutrition guidelines. When I once lamented to Senator Harkin that all we wanted to do was to make science into policy, he cocked his head and with a wry smile and said, "that would make too much sense." And the media is also influenced heavily by advertising dollars. Once, when I was on Martha Stewart's television show, the dairy lobby sponsored the episode, and her trainer was forced to mouth the talking points of the Dairy Council touting milk as a fabulous sports drink. Studies may show some benefit, but studies funded by the food industry show positive benefits eight times more than independently-funded studies. In a new editorial by two of the nation's leading nutrition scientists from Harvard, Dr. David Ludwig and Dr. Walter Willett, in JAMA Pediatrics, our old assumptions about milk are being called into question. Perhaps it doesn't help you grow strong bones, and it may increase the risk of cancer and promote weight gain. It is bad enough that the dairy industry recently petitioned the FDA to sneak artificial sweeteners into chocolate milk. They want their "shake and eat it, too" by pushing milkshake-like flavored milk drinks into schools as a "healthier" option, even though they have 30 grams of sugar per cup. By cutting the sugar and adding artificial sweeteners to low-fat or non-fat milk drinks, the idea is that they would be healthier. Except for the fact that recent studies have found that one diet drink a week increases your risk of Type 2 diabetes by 33 percent and a large diet drink increases the risk by 66 percent. What about low-fat milk or non-fat milk? These are the healthier options, right? Wrong. Ludwig and Willett note that there is scant evidence that fat makes you fat, despite this commonly-held mistaken belief. Reducing fat in milk reduces its ability to satisfy the appetite (which fat does) and can promote overeating and hunger. Often, the fat in the diet is replaced with sugar and refined carbohydrates, which clearly has been shown to promote obesity and Type 2 diabetes. Studies show that reducing fat in the diet, which parallels an increase in starch and refined carbohydrates in the diet, not only increases hunger but also may actually slow metabolism. In one study, Dr. Ludwig found that those who ate a low fat, higher glycemic diet burned 300 calories less a day that those who ate an identical calorie diet that was higher in fat and lower in glycemic load. For those who ate the higher fat, lower glycemic diet, that's like exercising an extra hour a day without doing anything! More concerning still is that, in studies of kids and adults, those who consumed low-fat milk products gained more weight than those who ate the full-fat, whole milk products. They seemed to increase their overall intake of food because it just wasn't as satisfying as the real thing. In fact, those who drank the most milk overall gained the most weight. It makes logical sense. Milk is designed to quickly turn a little calf into a big cow and contains over 60 different hormones, most designed to boost growth. But shouldn't we stick to low-fat milk to reduce our intake of saturated fat? The fact is that, while your LDL or bad cholesterol goes down by reducing saturated fat in the diet, the protective cholesterol, HDL, actually goes up by eating saturated fat improving the ratio of total to HDL cholesterol, which is the most important marker of your risk of heart disease. Switching out saturated fat for carbohydrates actually increased the risk of heart attack in a 12-year study of 53,544 adults. In fact, the whole story of the evil of saturated fats is in great debate. The evidence for linkage to heart disease turns out to be pretty weak indeed. If you ate only whole foods, fruits, vegetables, beans, nuts, seeds, and whole grains (not whole grain flour), you might be better off overall (although a recent scientific review of saturated fat dismissed the very notion that is it bad for you). But sadly, that is not what most Americans do when they switch to low fat. The sad thing is that many schools and "healthy" beverage guidelines encourage the idea that flavored milk is better than soda and that getting kids to drink more milk by any means is a good idea. This is dangerously misguided. There are 27 grams of sugar in 8 ounces of Coca Cola and a whopping 30 grams of sugar in 8 ounces of Nestlé Chocolate Milk. Sugar is sugar, and drives obesity and diabetes. It is not a good way to get kids to drink milk. But that begs the bigger question. Do kids need milk? Is milk necessary for healthy bones and preventing osteoporosis? The data are clear, but our government polices don't reflect the science. Dairy and milk products do not promote healthy bones. In a large meta-analysis, milk did not reduce risk of fractures. Other studies have shown it can increase fracture rates. And the countries with the lowest milk consumption have the lowest risk of osteoporosis and fractures. Calcium is not all it's cracked up to be. Studies show that higher calcium intakes are actually associated with higher risk of fracture. Milk may not grow strong bones, but it does seem to grow cancer cells. Milk increases the hormone called IGF-1 or insulin-like growth factor, one that is like Miracle-Gro for cancer cells. Dairy products have been linked to prostate cancer. And cows are milked while pregnant (yes, even organic cows), filling milk with loads of reproductive and potentially cancer-causing hormones. There are other problems with milk, too. It increases the risk of Type 1 diabetes. Dairy is a well-known cause of acne. And of course, dairy causes millions around the world (75 percent of the population) to suffer digestive distress because of lactose intolerance. It causes intestinal bleeding in 40 percent of infants, leading to iron deficiency. Allergy, asthma, and eczema all may be triggered by dairy consumption. The US Department of Agriculture's new My Plate initiative recommends three cups a day of milk for everyone! If you are 2 to 9 years old, you get away with only 2 to 2.5 cups. And the "key consumer message" is to switch to 1 percent or non-fat versions. There is absolutely no biological requirement for milk, and the evidence for low-fat milk is lacking, along with the bone benefits. The dairy lobby has its tentacles deep in the U.S. Department of Agriculture. One scientist friend who advises the government on food policy confided to me that when he protested that there was no evidence for the government's recommendations that we all drink three glasses of milk a day and that, in fact, it may be harmful, he was patronized with a "yes, we know, but the dairy lobby makes it difficult to make science into policy." Let's just forget the science and spend taxpayer's dollars to promote foods that we know are harmful, because money runs politics. To heck with the health of our citizens. Bottom line: Milk is not nature's perfect food unless you are a calf and should not be consumed in large quantities by most people, because it can promote weight gain, cancer, and even cause osteoporosis. Write to your congressmen to encourage them to support changes to our food and farm bill policies that shape our nutritional guidelines and make them evidence based. The answer to the question, "Got Proof?" Heck no! Now I'd like to hear from you... Do you think we need to drink milk to be healthy? Do you agree that getting kids to drink more milk is a good idea? Have you recently cut dairy from your diet, and if so, do you feel better? What are some good dairy alternatives that you've discovered? To your good health, Mark Hyman, M.D. For more by Mark Hyman, M.D., click here.
/** * <p>Return the head element for the most recently retrieved page. * If there is no such element, return <code>null</code>.</p> */ protected HtmlHead head() throws Exception { Iterator elements = page.getChildElements().iterator(); while (elements.hasNext()) { HtmlElement element = (HtmlElement) elements.next(); if (element instanceof HtmlHead) { return ((HtmlHead) element); } } return (null); }
Teledentistry as an Effective Tool for the Communication Improvement between Dentists and Patients: An Overview Teledentistry is an online dental care service that allows patients and dentists to meet in real time, safely, without being at the same location. During the COVID-19 pandemic, real-time videoconferencing has gained popularity in the field of teledentistry, with numerous benefits for both patients and dentists. Online consultations can minimize costs, maximize time, and provide more convenient care options for both patients and dentists. When practicing teledentistry, a dentist must establish a good doctor–patient relationship. Dentists must ensure that the telecommunication solution that they choose meets their clinical requirements and complies with privacy laws. Dentists should provide adequate information to patients about the limitations, advantages, and disadvantages that may occur during online consultation. Dentists must follow guidelines and procedures regarding informed consent, patient details, personal communications, and consultancies’ privacy and confidentiality. The patient should be aware of the limitations of teledentistry, and dentists will provide the best advice possible in the absence of a face-to-face consultation. This article discusses how teledentistry could be an effective tool for dentists and patients. Introduction With the era of technology and telecommunication, the healthcare system is changing rapidly. Several telecommunications systems have been implemented for hospitals and, with the passage of time, a new term for it has emerged, namely "telemedicine" . As a branch of telehealth, telemedicine employs communications networks from one regional area to another to deliver healthcare facilities and medical education, especially to solve problems such as unequal access and a lack of infrastructure and human resources . Teledentistry is a subfield of telehealth, along with telemedicine, that focuses on dentistry, derived from interactive tools, telecommunications, and dentistry combinations . Teledentistry uses information technology to facilitate remote dental care, advice, education, or treatment rather than direct face-to-face communication with patients . The first study on teledentistry was conducted in 1994. It was conducted by the US Army as part of the US Army's Total Dental Access Project . Cook et al. defined the term teledentistry in 1997, as "the practice of diagnosing and providing treatment advice over a distance using video-conferencing technology" (Figure 1). It can be used as a service modality in three primary ways . These include the following: (i) consultations among dentists-for example, a general dentist and a specialist dentist can exchange patient photos and records, followed by a review and treatment planning discussion; (ii) a real-time face-to-face video conference consultation between a general dentist or specialist and a patient or family member in a distant, remote location; (iii) remote patient monitoring, collecting data in real time and transmitting them to the dentist in a remote location for examination and action as required . It also assists in providing patients with basic knowledge about dental healthcare and improving patients' healthcare facilities . This facilitates the efficient exchange of information and knowledge between the patient and the doctor and among different specialists to achieve better treatment planning and outcomes . Most dentists or specialists prefer synchronous or real-time videoconferencing with the patient through teledentistry systems . In the healthcare system, real-time interactive consultations are now integrated . Several studies have indicated that real-time video consultations play an important role in the healthcare setting and, in these cases, they also demonstrate advantages over simple mobile consultations . Recent studies showed that video consultations were thought to be useful for general practitioners but perhaps more suitable for particular groups of patients . The demand for online video consultation is likely to increase, but it is essential to improve the technical infrastructure and to select cases . Therefore, real-time interactive video consultation is the most authentic means of communicating with patients and conducting a teledentistry examination. During online consultation, a dentist must establish a doctor-patient relationship with the patient. When establishing relationships between dentist and patient, it is crucial to maintain the proper guidelines or recommendations for online consultation from both sides. In this article, we discuss how teledentistry could be an effective solution for dentists and patients. It can be used as a service modality in three primary ways . These include the following: (i) consultations among dentists-for example, a general dentist and a specialist dentist can exchange patient photos and records, followed by a review and treatment planning discussion; (ii) a real-time face-to-face video conference consultation between a general dentist or specialist and a patient or family member in a distant, remote location; (iii) remote patient monitoring, collecting data in real time and transmitting them to the dentist in a remote location for examination and action as required . It also assists in providing patients with basic knowledge about dental healthcare and improving patients' healthcare facilities . This facilitates the efficient exchange of information and knowledge between the patient and the doctor and among different specialists to achieve better treatment planning and outcomes . Most dentists or specialists prefer synchronous or real-time videoconferencing with the patient through teledentistry systems . In the healthcare system, real-time interactive consultations are now integrated . Several studies have indicated that real-time video consultations play an important role in the healthcare setting and, in these cases, they also demonstrate advantages over simple mobile consultations . Recent studies showed that video consultations were thought to be useful for general practitioners but perhaps more suitable for particular groups of patients . The demand for online video consultation is likely to increase, but it is essential to improve the technical infrastructure and to select cases . Therefore, real-time interactive video consultation is the most authentic means of communicating with patients and conducting a teledentistry examination. During online consultation, a Technologies Used in Teledentistry Information and communication technology (ICT) is being developed day by day. Teledentistry can help in oral healthcare almost in every corner of the world. It connects the patient, dentist, and specialist from the relevant fields, where exchanges and interactions are established for diagnosis and treatment. "Store-and-forward" and "real-time" are the two main types of interaction. "Store-and-forward" is commonly referred to as pre-recorded media or asynchronous systems, whereas real-time interactions are known as synchronous systems . Clinical information, including clinical images, can be gathered in a virtual storage place in the store-and-forward system, which can be further used as a diagnostic reference and treatment plan . Moreover, it can be a valuable tool in patient counseling, even if the patient is far from the consultation process . Dentists and specialist clinicians can easily exchange patient information, radiographic images, pathological images and laboratory findings, treatment modalities, and other information related to oral and general health status. They may seek help from a different specialist for their opinions and counseling. Usually, low-bandwidth internet is suitable for such kinds of systems. In real-time methods, a consultation can take place via video calling or conferencing between a dentist, specialist clinicians, and a patient. They can quickly review clinical and general information, medical history, radiographic images, and laboratory findings for diagnosis. This interactive approach allows real-time images and better understanding from the doctor's side to the patient's side . Remote patient management is a recent addition to this field. In this method, dentists or other clinical experts can obtain detailed information directly from patients' homes about their health conditions and easily send them to clinical centers. The main advantage of this method is that it reduces healthcare costs. Moreover, recently, mobile communication devices have gained attention in the field of public health education and promotion, especially cell phones and tablets. In Diagnosis The most significant aspect of teledentistry is its ability to minimize healthcare disparities, improve patients' access to professional advice, shorten the treatment duration without sacrificing quality, and drastically reduce waiting times . With the introduction of teledentistry into oral health services, patients might have easy access to diagnosis and management of their oral health concerns . One of the possible reasons for the delayed diagnosis of oral cancer is the improper diagnosis of oral lesions . In this regard, teledentistry aids in the early detection of malignant lesions, enabling faster measures for the treatment of oral cancer and enhancing the effectiveness and safety of the therapy by facilitating communication between dentists and clinical specialists. In addition, remote diagnosis can be a useful method for detecting oral lesions . Involving many specialists in the diagnostic process seems to be a promising approach for increasing the precision of remote diagnosis . In Oral and Maxillofacial Surgery Previous research has demonstrated that teledentistry can be an effective technique for the purposes of consultation, assessment of the patient, treatment planning, and follow-up care in maxillofacial surgery . Patients' and dental surgeons' acceptability regarding teledentistry performed through telephone appointments for different patient categories in maxillofacial surgical practice in comparison with the on-site evaluation was highly appreciated . This study also showed that most of the patients with conditions such as temporomandibular disorder, salivary gland disorders, head and neck cancer, and orthognathic surgery require further assessment owing to the difficulty of carrying out a standard "face-to-face" consultation. Other studies revealed the overall perspectives of both dentists and patients on teledentistry . They reported that teledentistry was generally well accepted by patients with trauma, whereas the lowest acceptance was found in patients with temporomandibular joint disorder. Concerning how dentists and clinicians perceive teledentistry, most of the dentists were happy with it. However, some of them expressed concern about its effectiveness because the inability to perform physical examinations can lead to an incomplete diagnosis. In Orthodontics Teledentistry is becoming more popular in orthodontics as a means to consult with and monitor patients without visiting dentists due to technological advancements. Virtual consultation and artificial intelligence (AI)-based treatment monitoring methods with photos or videos are currently the main forms of online communication technology used in orthodontics . Regarding initial orthodontic consultations, teledentistry can be particularly useful in evaluating treatment options and diagnosis plans, measuring calibration and orientation, and assessing functional appliances and removable appliances. Although teledentistry has not completely eradicated the need for in-person clinical care, most of the dentists and patients believe that online consultations or teledentistry are more convenient and cost-effective in orthodontic treatment . Minor orthodontic emergencies such as rubber ligature displacement, pain, and cheek irritation can be handled at home via teledentistry, reducing the need for in-person visits to the dental clinic . Nevertheless, many procedures that need direct access to the oral cavity cannot be performed by teledentistry, despite having unique advantages. For instance, an orthodontist may carry out a preliminary examination such as gathering data, installing brackets and bands, bonding and removing them, occlusal correction, and changing the wires . Teledentistry still has to address the issue regarding the conceptualization of data and information in order to maintain a level of quality equivalent to that of on-site orthodontic consultations . In Restorative Dentistry and Endodontics Endodontics is a highly sophisticated branch of dentistry that is handled by specialist dentists called endodontists. The provision of endodontic care to underprivileged patients is possible through the use of teledentistry. Teledentistry can be used to recognize root canal orifices from a distance, which tends to suggest that highly trained endodontists can help general dentists in the identification of root canal orifices by providing guidance and instruction over the telephone about the recognition of root canals . Teledentistry, which utilizes the internet as a communication medium, has proven to be effective in the diagnosis of periapical lesions of the anterior teeth . It has the dual benefit of lowering the costs associated with long-distance visits and increasing the accessibility of emergency assistance. In Pediatric Dentistry A child's overall health and well-being are significantly affected by their oral and dental health . Pediatric dentists can be given the chance to use technological developments in the information and telecommunications field to serve their patients and encourage better oral hygiene habits . For pediatric patients, preventive counseling can be given over the phone to initiate treatment regimens. Over the telephone or through email, dietary charts can be sent or provided in advance, and introducing patients to online dental hygiene resources is possible. A high-strength sodium fluoride toothpaste prescription might be administered by an online prescription system . Some pediatric patients could be sent to a specialist pediatric dentist for delayed tooth eruption or tooth exfoliation. In this regard, an initial video call for an evaluation of the condition of the oral cavity could be helpful in determining whether or not the patient needs to undergo further professional consideration. In addition, pediatric dentists and orthodontic specialists who wait for the shedding of the deciduous teeth before performing final treatment may find that teledentistry is an advantageous alternative. Other developmental problems such as neonatal or natal teeth and eruption cysts might all be monitored by teledentistry . One of the main benefits of teledentistry is that it eliminates the need for patients and parents to travel and leave their workplace or school in order to see a dentist in person . Nevertheless, the high expense of having a smartphone or computer means that some patients may be unable to use teledentistry. Informed Consent between Dentist and Patient Informed consent is an integral part of the relationship between doctors and patients in every medical field. Teledentistry should cover all aspects of the standard, conventional consent form; in addition, it should also inform the patient of the inherent risk of misdiagnosis and/or treatment due to the involvement of technological failure. Patients should be informed that, despite strong attempts to protect the confidentiality of the patient, their information must be transmitted electronically, and that the data can be intercepted. To prevent malpractice during treatment, the form should include the names of both the referring and consulting doctors, and the consulting doctor should obtain a copy of the consent document prior to establishing any form of patient interaction . Dental practitioners must follow guidelines and procedures for informed consent (verbal or written), patient details, personal communications, and consultancies' privacy and confidentiality. Dentist-Patient Relationships In the dentist-patient relationship, mutual trust is required when the dentist asks the patient to provide the necessary information and when the patient agrees to the dentist's treatment policy. Therefore, it is necessary to implement this based on mutual agreement. The agreement should include specific rules for implementing online consultation. However, there is a difference in medical knowledge between dentists and patients. Dentists must provide sufficient information to patients about the advantages of online consultation and the disadvantages that may occur. Therefore, it is necessary to obtain the consent of the patient thoroughly, and then the dentist should make appropriate decisions, including the applicability of online dental care . For this reason, online dental care is used only when there is already a direct relationship between the dentist and the patient. It is required that the same dentist should perform face-to-face online dental care in an appropriate combination ( Figure 2). prevent malpractice during treatment, the form should include the names of both the referring and consulting doctors, and the consulting doctor should obtain a copy of the consent document prior to establishing any form of patient interaction . Dental practitioners must follow guidelines and procedures for informed consent (verbal or written), patient details, personal communications, and consultancies' privacy and confidentiality. Dentist-Patient Relationships In the dentist-patient relationship, mutual trust is required when the dentist asks the patient to provide the necessary information and when the patient agrees to the dentist's treatment policy. Therefore, it is necessary to implement this based on mutual agreement. The agreement should include specific rules for implementing online consultation. However, there is a difference in medical knowledge between dentists and patients. Dentists must provide sufficient information to patients about the advantages of online consultation and the disadvantages that may occur. Therefore, it is necessary to obtain the consent of the patient thoroughly, and then the dentist should make appropriate decisions, including the applicability of online dental care . For this reason, online dental care is used only when there is already a direct relationship between the dentist and the patient. It is required that the same dentist should perform face-to-face online dental care in an appropriate combination (Figure 2). Benefits for Patients In case of emergency, a patient may contact the dentist directly from a remote location. This helps the dentist to evaluate the problem in detail, prior to prescribing any medicine, and thereby can save time, money, and prompt visits to a hospital or clinic. Consequently, there is less need for travel and a shorter wait time in dental offices. Teledentistry is also less costly than face-to-face dental care while also delivering a high-quality service. Furthermore, patients and their families may also select a dentist based on their criteria. This facilitates a second opinion from a dental specialist, who may be geographically far from the patient . Benefits for Patients In case of emergency, a patient may contact the dentist directly from a remote location. This helps the dentist to evaluate the problem in detail, prior to prescribing any medicine, and thereby can save time, money, and prompt visits to a hospital or clinic. Consequently, there is less need for travel and a shorter wait time in dental offices. Teledentistry is also less costly than face-to-face dental care while also delivering a high-quality service. Furthermore, patients and their families may also select a dentist based on their criteria. This facilitates a second opinion from a dental specialist, who may be geographically far from the patient . Benefits for Dentists Since patients do not have to visit the clinic as often, chair times will be reduced. Consultations with dentists could be virtual, and dentists may be able to deal with more patients per day. Patients do not need to attend follow-up visits after receiving treatment because the dentist may simply electronically communicate with the patient. Furthermore, dentists can quickly consult with a specialist if they need a second opinion, with the patient's consent. Another advantage for dentists is the ability to communicate with patients who live in remote areas . Responsibility of the Dentists In teledentistry, the dentists hold the main responsibility for the consultation performed online. For this reason, the dentist carefully judges whether sufficient information is obtained from the online consultation and the information can be used to make an appropriate diagnosis. When using teledentistry for dental consultations, a dentist's primary responsibility will be to diagnose a disease, develop treatment plans, determine the primary and preventive oral health services that could be provided to patients in their home communities, and expedite referral and follow-up for dental treatment when necessary . In addition, dentists take sufficient information security measures for information communication and the storage of patient information so that the patient's information will be safe. The dentist should consider every detail of the diagnosis and treatment process for the purpose of treatment, the prognosis of treatment, and further improvement of the diseased condition and complaints that remain unsolved after receiving the consultation, if any. These include (i) patient record acquisition, management, sharing, and storage; (ii) maintenance of the privacy and security of patient health information across the delivery system; (iii) equipment and technology to enable care at multiple endpoints. Responsibility of the Patients Patients might view any licenses or certifications demonstrating that a dentist has been properly trained and approved to provide online teledentistry consultations. Moreover, the patient can ask any questions that come to mind related to their current or previous oral issues. During online consultations, patients may ask questions, report symptoms, and discuss other information, including the ability to review a known problem or condition and upload photos as required . The dentist may wish to obtain additional information from the patient regarding the current oral problem. The patient should cooperate with the dentist by providing additional necessary information when required by the dentist. Limitations during Online Consultations Online consultations have limitations in diagnosing diseases and evaluating patient problems, especially in dentistry. Sometimes, clinicians may be the most significant impediment to implementation, being resistant to change due to various influencing factors, having concerns about the consistency of patient interactions, and being concerned about technological difficulties. The difficulty of assessing the dentition and soft tissue, especially in the posterior oral cavity, would be the utmost limitation of online consultations in this field. Image quality, internet accessibility, and patient considerations including the ability to connect to the software, provide real-time interactive video consultations, proper light arrangement, manual dexterity, and acquaintance with mobile/tablet devices should be taken into consideration. However, the ability to assess extraoral and intraoral swelling, grossly carious teeth, soft tissue lesions, mobile teeth, fractured prosthodontic work, and orthodontic emergencies is highly impractical through online consultation . Furthermore, a combination of the store-and-forward approach with real-time video can minimize the limitation of poor image quality. Moreover, clinical examinations are not possible, and video conferencing cannot provide an adequate definition to facilitate oral examination. In addition, special investigations that require direct patient contact and would aid in an accurate diagnosis are difficult to obtain in an online teledentistry consultation . Dentist-Patient Confidentiality The dentist-patient relationship is built to understand that any information shared by the patient with the dentist will not be shared without the patient's consent. Patients have a right to privacy, and they must provide the dentist with comprehensive health records to ensure safe care. Patients should expect to have access to important privacy information, such as who has access to their medical information, with whom their medical information is shared, why any medical information is shared with a third party, how to request copies of their personal information on file, and what medical and personal information is obtained. All of these are common questions that any reputable teledentistry service provider should answer. As a result, a teledentist must follow the guidelines that all doctors must follow regarding patient privacy. Dentists who use teledentistry must take every precaution to safeguard their system and the data that they transmit . Providing Accurate Information Online consultation provides less information about the patient's condition than face-to-face dental care. After correctly understanding the limitations of online consultation by such online dental care, the dentist will explain the advantages of online dental care/treatment and the disadvantages to the patient in advance. Communications with the patient should be appropriately conducted to avoid using technical and complicated terminology . Teledentistry during COVID-19 Teledentistry is an innovative approach to dentistry and access problems that does not require close contact with the dental professional. Dentistry has been slower than other healthcare areas in terms of communication and information technologies while providing dental care. The rapid adoption of teledentistry by the dental profession during the COVID-19 pandemic offers an excellent opportunity to investigate how teledentistry can be used in dental treatment in the long-term and short-term process, as well as providing a safe and secure environment in which to deliver high-quality care while minimizing the risk of infection. Dentists can use online teledentistry consultation to provide necessary advice, monitor a patient's condition more than once, and treat patients with emergency dental problems both during and after the COVID-19 pandemic. In the current situation, it will be essential for dental services to have access to a video consultation solution in order to provide a better triage service to those who need it more effectively. Using a video consultation service will aid in limiting patient contact during the COVID-19 outbreak's recovery and restoration phase, as well as in the future. This will allow practices to manage the backlog of patients currently unable to access dental care and prioritize those with acute therapy problems so that the return of routine dental care can be facilitated over time (Figure 3) . Acceptance of Teledentistry by Dentist and Patient Most dentists worldwide may find teledentistry to be a complex system and struggle on many points to adopt these new skills . Not only do they find it a technologically challenging procedure, but they are also fearful of making an incorrect diagnosis. Acceptance of Teledentistry by Dentist and Patient Most dentists worldwide may find teledentistry to be a complex system and struggle on many points to adopt these new skills . Not only do they find it a technologically challenging procedure, but they are also fearful of making an incorrect diagnosis. In some cases, the expanded level of cause and expense is also a matter of concern for the dentists. Poor internet connection, a lack of suitable technological devices and support, and inadequate training facilities are the limitations in this field . Furthermore, dentists are confronted by various challenges, such as scarce financial reimbursement, deficient guidelines, the inharmonious relationship between the organization of teledentistry with the healthcare service providers, a lack of coordination, lack of connection between the central and remote centers, and, lastly, the high costs of infrastructure . A lack of ability to perform tooth percussion and pulp vitality tests is an additional constraint. Accepting the expansion of teledentistry, it is necessary to address the challenges mentioned above. Therefore, dentists should receive sufficient training and develop their knowledge about the technology. Acknowledging the COVID-19 situation, dental healthcare providers should be trained regularly to face the obstacles of transmissible diseases and deal with any pandemic situation by implementing teledentistry. Nevertheless, adequate capitalization, research funds, and validation of teledentistry within the healthcare system should be necessary . Acceptance of teledentistry by the patient is fundamental to the success of this component. The patient may perceive that reduced communication with their dentists may occur due to a lack of face-to-face communication, which may lead them to feel anxious about the situation. With the broad expansion of telemedicine, teledentistry will gain more acceptance from patients day by day. Numerous studies have revealed that teledentistry is gradually becoming more recognized by both patients and dentists . Recommendations for Effective Online Teledentistry Consultation An online consultation is the act of examining a patient between a dentist and a patient via an information and communication device and recommending a dental clinic/hospital to see a dentist in real time in teledentistry. Encouragement of consultation with the minimum necessary diagnosis according to the individual patient's condition, such as selecting the appropriate dental specialized department, is important. Diagnosing specific diseases (if the diagnosis is adequately made), informing patients of the diagnosis, instructing them on the specific use of over-the-counter drugs, prescribing, etc., are all examples of online medical treatment that can also be performed via online teledentistry consultation. In addition, there are cases where follow-up or non-examination instructions are given to persons with symptoms that are clearly not enough to see a dentist or undergo dental treatment according to the patient's individual condition. General consultation recommendations that do not involve any judgment can be provided as remote health and consultations. Future Perspectives of Teledentistry Although teledentistry has been around since the 1990s, its significance was only recently recognized in the pandemic situation that developed worldwide. Since the pandemic is still ongoing, teledentistry will likely be around for a very long time. Patients who are unable to go outside due to health issues and must remain inside their homes can now obtain dental consultations and treatments with the simple press of a phone button, thanks to the advent of teledentistry. At the same time, elderly patients and those with physical disabilities or who are incarcerated for various reasons can benefit from the emergence of teledentistry, which allows dental care to be delivered remotely. Similarly, for patients living in rural and inaccessible areas, for whom the time to travel to and from the dental clinic is a major setback, teledentistry represents a promising solution. Taking into account that it has such widespread use, as well as the significant number of drawbacks, both for patients and dental specialists, it will only be utilized to an increasing degree in the future. The major innovation in this field is the availability of high-quality software programs that are reasonably priced and simple to use by both patients and professionals. Although its benefits have been addressed, teledentistry cannot be regarded as a substitute for traditional dental care; instead, it can only be considered an addition to conventional dentistry. However, it is safe to state that the intersection of dental and telecommunications is now well established and is expected to progress on a constructive path. This convergence of dentistry and telecommunications is the future of dentistry. Conclusions Currently, advanced medical equipment and instruments have made teledentistry a more convenient way to reach patients on a large scale by providing teleconsultation support at any time and place through internet-based media platforms. Campaigning for public awareness about various health issues and promulgating valuable information can be achieved with an extensive group of targeted patients with the assistance of this media platform, particularly in an emergency. Teledentistry has no alternative to provide a safer patient consultation by lessening the burden of clinics at times of crisis. Hence, teledentistry plays a vital role in serving patients with a dynamic management strategy and fulfills the needs of the patient's treatment in the best possible way. Conflicts of Interest: The authors declare no conflict of interest.
/** * Deletes all unitparameters and units for the units in the given profile. WARNING: These SQL * statements may be very slow to execute. Look at the plan here: 1. SQL to get all Units in a * profile 2. Iterate over all units in profile and delete parameters for each one. 3. SQL to * delete all units in a profile If you have 100000 units in a profile, then you will need to run * 100002 SQL statements. That is going to take a long time. */ public void deleteUnits(Profile profile) throws SQLException { Statement s = null; String sql = null; Map<String, Unit> unitMap = getUnits(profile.getUnittype(), profile, (Parameter) null, Integer.MAX_VALUE); Connection connection = null; boolean wasAutoCommit = false; try { connection = dataSource.getConnection(); wasAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); s = connection.createStatement(); int counter = 0; int upDeleted = 0; for (String unitId : unitMap.keySet()) { sql = "DELETE FROM unit_param WHERE unit_id = '" + unitId + "'"; upDeleted += s.executeUpdate(sql); if (counter > 0 && counter % 100 == 0) { connection.commit(); } counter++; } logger.info( "Deleted unit parameters for all units in for profile " + profile.getName() + "(" + upDeleted + " parameters deleted)"); sql = "DELETE FROM unit WHERE profile_id = " + profile.getId(); int rowsDeleted = s.executeUpdate(sql); logger.info( "Deleted all units in for profile " + profile.getName() + "(" + rowsDeleted + " units deleted)"); connection.commit(); } catch (SQLException sqle) { if (connection != null) { connection.rollback(); } throw sqle; } finally { if (s != null) { s.close(); } if (connection != null) { connection.setAutoCommit(wasAutoCommit); connection.close(); } } }
def insert_rows(self, namespace, raw_table_name, rows): if len(rows) == 0: return super(ImportDBMySQL, self)._enter('insert_rows') table_name = self.convert_raw_to_namespace(namespace, raw_table_name) packet_size = 1000 num_packets = ((len(rows)-1) // packet_size) + 1 for packet_num in range(num_packets): start_row = packet_size * packet_num end_row = min(len(rows), packet_size * (packet_num+1)) sorted_column_names = sorted(rows[0].keys()) cmd = f'INSERT INTO `{table_name}` (' cmd += ','.join(['`'+s+'`' for s in sorted(sorted_column_names)]) cmd += ') VALUES' first_row = True param_list = [] for row in rows[start_row:end_row]: val_list = [] assert sorted_column_names == sorted(row.keys()), \ (sorted_column_names, sorted(row.keys())) for column_name in sorted_column_names: val = row[column_name] if val is None: val_list.append('NULL') elif isinstance(val, str): val_list.append('%s') param_list.append(val) else: val_list.append(str(val)) if not first_row: cmd += ',' first_row = False cmd += '(' + ','.join(val_list) + ')' try: self._execute(cmd, param_list, mutates=True) except MySQLdb.Error as e: if self.logger: self.logger.log('fatal', f'Failed to insert row into "{table_name}": {e.args[1]}') raise ImportDBException(e) super(ImportDBMySQL, self)._exit()
/** * Constraint descriptor implementation that only provides the configured attributes. * This adapter class is needed to enable usage of the message interpolator. */ private static class AttributeConstraintDescriptor implements ConstraintDescriptor<Annotation> { private final Map<String, Object> attributes; public AttributeConstraintDescriptor(Map<String, Object> attributes) { this.attributes = unmodifiableMap(attributes); } @Override public Annotation getAnnotation() { return null; } @Override public Map<String, Object> getAttributes() { return attributes; } @Override public Set<ConstraintDescriptor<?>> getComposingConstraints() { return emptySet(); } @Override public List<Class<? extends ConstraintValidator<Annotation, ?>>> getConstraintValidatorClasses() { return emptyList(); } @Override public Set<Class<?>> getGroups() { return emptySet(); } @Override public Set<Class<? extends Payload>> getPayload() { return emptySet(); } @Override public boolean isReportAsSingleViolation() { return false; } }
/* * Copyright 2010-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jet.plugin.libraries; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.testFramework.LightPlatformTestCase; import com.intellij.testFramework.LightProjectDescriptor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetClass; import org.jetbrains.jet.lang.psi.JetPsiUtil; import org.jetbrains.jet.plugin.JetWithJdkAndRuntimeLightProjectDescriptor; import java.io.File; import java.io.IOException; public class NavigateToStdlibSourceRegressionTest extends NavigateToLibraryRegressionTest { /** * Regression test against KT-3186 */ public void testRefToAssertEquals() { PsiElement navigationElement = configureAndResolve("import kotlin.test.assertEquals; val x = <caret>assertEquals(1, 2)"); assertEquals("Test.kt", navigationElement.getContainingFile().getName()); } public void testJavaClass() throws IOException { doNavigationInSourcesTest("libraries/stdlib/src/kotlin/Iterators.kt", "Collections", "java.util.Collections"); } public void testKotlinClass() throws IOException { doNavigationInSourcesTest("libraries/stdlib/src/kotlin/Iterators.kt", "FunctionIterator", "kotlin.FunctionIterator"); } public void testClassWithJavaAnalog() throws IOException { doNavigationInSourcesTest("libraries/stdlib/src/kotlin/Iterators.kt", "Iterator", "jet.Iterator"); } public void testNavigationInKotlinBuiltIns() throws IOException { doNavigationInSourcesTest("libraries/stdlib/src/generated/_Arrays.kt", "Array", "jet.Array"); } private void doNavigationInSourcesTest(@NotNull String path, @NotNull String element, @NotNull String expectedFqName) throws IOException { PsiElement navigationElement = getNavigationElement(path, element); checkNavigationElement(navigationElement, expectedFqName); } protected PsiElement getNavigationElement(String path, String element) { File file = new File(path); PsiFile psiFile = getPsiFileForFileFromSources(file); String text = psiFile.getText(); int index = text.indexOf(element); PsiReference ref = psiFile.findReferenceAt(index); assertNotNull("Cannot find reference at " + index + ", " + text.substring(index - 20, index) + "<caret>" + text.substring(index, index + 20), ref); PsiElement resolvedElement = ref.resolve(); assertNotNull("Cannot resolve reference: " + ref.getElement().getText(), resolvedElement); return resolvedElement.getNavigationElement(); } @NotNull private PsiFile getPsiFileForFileFromSources(@NotNull File file) { VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, false); assertNotNull("Cannot find virtual file for " + file.getAbsolutePath(), virtualFile); PsiFile psiFile = getPsiManager().findFile(virtualFile); assertNotNull("Cannot find psi file for " + virtualFile.getCanonicalPath(), psiFile); return psiFile; } private void checkNavigationElement(@NotNull PsiElement element, @NotNull String expectedName) { if (element instanceof PsiClass) { assertEquals(expectedName, ((PsiClass) element).getQualifiedName()); } else if (element instanceof JetClass) { assertEquals(expectedName, JetPsiUtil.getFQName((JetClass) element).asString()); } else { fail("Navigation element should be JetClass or PsiClass: " + element.getClass() + ", " + element.getText()); } } @Override protected void tearDown() throws Exception { // Workaround for IDEA's bug during tests. // After tests IDEA disposes VirtualFiles within LocalFileSystem, but doesn't rebuild indices. // This causes library source files to be impossible to find via indices super.tearDown(); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { LightPlatformTestCase.closeAndDeleteProject(); } }); } @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return ProjectDescriptorWithStdlibSources.INSTANCE; } private static class ProjectDescriptorWithStdlibSources extends JetWithJdkAndRuntimeLightProjectDescriptor { public static final ProjectDescriptorWithStdlibSources INSTANCE = new ProjectDescriptorWithStdlibSources(); @Override public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model, @Nullable ContentEntry contentEntry) { super.configureModule(module, model, contentEntry); Library library = model.getModuleLibraryTable().getLibraryByName("myLibrary"); assert library != null; Library.ModifiableModel modifiableModel = library.getModifiableModel(); modifiableModel.addRoot(VfsUtil.getUrlForLibraryRoot(new File("libraries/stdlib/src")), OrderRootType.SOURCES); modifiableModel.commit(); } } }
<gh_stars>1-10 # USAGE # python detect_low_contrast_video.py --input example_video.mp4 # import the necessary packages from skimage.exposure import is_low_contrast import numpy as np import argparse import imutils import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", type=str, default="", help="optional path to video file") ap.add_argument("-t", "--thresh", type=float, default=0.35, help="threshold for low contrast") args = vars(ap.parse_args()) # grab a pointer to the input video stream print("[INFO] accessing video stream...") vs = cv2.VideoCapture(args["input"] if args["input"] else 0) # loop over frames from the video stream while True: # read a frame from the video stream (grabbed , frame) = vs.read() # if the frame was not grabbed then we've reached the end of the video # stream so exit the script if not grabbed: print("[INFO] no frame read from stream - exiting") break # resize the frame, convert it to grayscale, blur it, and then perform # edge detection frame = imutils.resize(frame, width=450) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(blurred, 30, 150) # initialize the text and color to indicate that the current frame is # *not* low contrast text = "Low contrast: No" color = (0, 255, 0) # check to see if the frame is low contrast, and if so, update the text # and color if is_low_contrast(gray, fraction_threshold=["thresh"]): text = "Low contrast: Yes" color = (0, 0, 255) # otherwise, the frame is *not* low contrast, so we can continue # processing it else: # find contours in the edge map and find the largest one, which we'll # assume is the outline of our color correction card cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) c = max(cnts, key=cv2.contourArea) # draw the largest contour on the frame cv2.drawContours(frame, [c], -1, (0, 255, 0), 2) # draw the text on the ouput frame cv2.putText(frame, text, (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2) # stack the ouput frame and edge map next to each other ouput = np.stack([edged] * 3) ouput = np.hstack([frame, ouput]) # show the output to our scream cv2.imshow("Output", ouput) key = cv2.waitKey(1) & 0xFF # if the 'q' key was pressed, break from the loop if key == ord("q"): break
<filename>src/logics/selector.ts import { float, List } from '../base/conversion'; import { VectorLineModifyFlagID, LinePointModifyFlagID, VectorStrokeGroup, VectorStroke, VectorPoint, VectorGroupModifyFlagID, } from '../base/data'; import { IHitTest_VectorLayerLinePoint, HitTest_LinePoint_PointToPointByDistance, HitTest_Line_PointToLineByDistance } from './hittest'; export enum SelectionEditMode { setSelected = 1, setUnselected = 2, toggle = 3, } export class GroupSelectionInfo { group: VectorStrokeGroup = null; } export class LineSelectionInfo { line: VectorStroke = null; selectStateAfter = false; selectStateBefore = false; } export class PointSelectionInfo { point: VectorPoint = null; selectStateAfter = false; selectStateBefore = false; } export class VectorLayerEditorSelectionInfo { selectedGroups: List<GroupSelectionInfo> = null; selectedLines: List<LineSelectionInfo> = null; selectedPoints: List<PointSelectionInfo> = null; constructor() { this.clear(); } clear() { this.selectedGroups = new List<GroupSelectionInfo>(); this.selectedLines = new List<LineSelectionInfo>(); this.selectedPoints = new List<PointSelectionInfo>(); } isGroupDone(group: VectorStrokeGroup) { return (group.modifyFlag != VectorGroupModifyFlagID.none); } isLineDone(line: VectorStroke) { return (line.modifyFlag != VectorLineModifyFlagID.none); } isPointDone(point: VectorPoint) { return (point.modifyFlag != LinePointModifyFlagID.none); } selectPoint(line: VectorStroke, point: VectorPoint, editMode: SelectionEditMode) { if (this.isPointDone(point)) { return; } if (editMode == SelectionEditMode.setSelected || editMode == SelectionEditMode.toggle) { if (!point.isSelected) { let selPoint = new PointSelectionInfo(); selPoint.point = point; selPoint.selectStateAfter = true; selPoint.selectStateBefore = point.isSelected; this.selectedPoints.push(selPoint); point.isSelected = selPoint.selectStateAfter; point.modifyFlag = LinePointModifyFlagID.unselectedToSelected; this.selectLine(line, editMode); } } if (editMode == SelectionEditMode.setUnselected || editMode == SelectionEditMode.toggle) { if (point.isSelected) { let selPoint = new PointSelectionInfo(); selPoint.point = point; selPoint.selectStateAfter = false; selPoint.selectStateBefore = point.isSelected; this.selectedPoints.push(selPoint); point.isSelected = selPoint.selectStateAfter; point.modifyFlag = LinePointModifyFlagID.selectedToUnselected; this.selectLine(line, editMode); } } } selectLinePoints(line: VectorStroke, editMode: SelectionEditMode) { for (let point of line.points) { this.selectPoint(line, point, editMode); } } selectLine(line: VectorStroke, editMode: SelectionEditMode) { if (this.isLineDone(line)) { return; } let selInfo = new LineSelectionInfo(); selInfo.line = line; selInfo.selectStateBefore = line.isSelected; if (editMode == SelectionEditMode.setSelected) { selInfo.selectStateAfter = true; line.isSelected = true; line.modifyFlag = VectorLineModifyFlagID.unselectedToSelected; } else if (editMode == SelectionEditMode.setUnselected) { selInfo.selectStateAfter = false; line.modifyFlag = VectorLineModifyFlagID.selectedToUnselected; } else if (editMode == SelectionEditMode.toggle) { if (line.isSelected) { selInfo.selectStateAfter = false; line.modifyFlag = VectorLineModifyFlagID.selectedToUnselected; } else { selInfo.selectStateAfter = true; line.isSelected = true; line.modifyFlag = VectorLineModifyFlagID.unselectedToSelected; } } this.selectedLines.push(selInfo); } selectLinePointsForLines(editMode: SelectionEditMode) { for (let selLineInfo of this.selectedLines) { for (let point of selLineInfo.line.points) { this.selectPoint(selLineInfo.line, point, editMode); } } } editGroup(group: VectorStrokeGroup) { if (this.isGroupDone(group)) { return; } let selInfo = new GroupSelectionInfo(); selInfo.group = group; this.selectedGroups.push(selInfo); group.modifyFlag = VectorGroupModifyFlagID.edit; } editLine(line: VectorStroke) { if (this.isLineDone(line)) { return; } let selInfo = new LineSelectionInfo(); selInfo.line = line; this.selectedLines.push(selInfo); line.modifyFlag = VectorLineModifyFlagID.edit; } editPoint(point: VectorPoint) { if (this.isPointDone(point)) { return; } let selInfo = new PointSelectionInfo(); selInfo.point = point; this.selectedPoints.push(selInfo); point.modifyFlag = LinePointModifyFlagID.edit; } deletePoint(point: VectorPoint) { if (this.isPointDone(point)) { return; } let selInfo = new PointSelectionInfo(); selInfo.point = point; this.selectedPoints.push(selInfo); point.modifyFlag = LinePointModifyFlagID.delete; } updateLineSelectionState() { for (let selLineInfo of this.selectedLines) { let existsSelectedPoint = false; for (let point of selLineInfo.line.points) { if (point.isSelected) { existsSelectedPoint = true; break; } } selLineInfo.selectStateAfter = existsSelectedPoint; selLineInfo.line.isSelected = existsSelectedPoint; } } resetModifyStates() { for (let selGroup of this.selectedGroups) { selGroup.group.modifyFlag = VectorGroupModifyFlagID.none; } for (let selPoint of this.selectedPoints) { selPoint.point.modifyFlag = LinePointModifyFlagID.none; } for (let selLine of this.selectedLines) { selLine.line.modifyFlag = VectorLineModifyFlagID.none; } } } export interface ISelector_BrushSelect extends IHitTest_VectorLayerLinePoint { editMode: SelectionEditMode; selectionInfo: VectorLayerEditorSelectionInfo; } export class Selector_LinePoint_BrushSelect extends HitTest_LinePoint_PointToPointByDistance implements ISelector_BrushSelect { editMode = SelectionEditMode.setSelected; // @override selectionInfo = new VectorLayerEditorSelectionInfo(); // @override protected beforeHitTest() { // @override this.selectionInfo.clear(); } protected onPointHited(group: VectorStrokeGroup, line: VectorStroke, point: VectorPoint) { // @override this.selectionInfo.selectPoint(line, point, this.editMode); } protected afterHitTest() { // @override this.selectionInfo.updateLineSelectionState(); this.resetModifyStates(); } resetModifyStates() { this.selectionInfo.resetModifyStates(); } } export class Selector_Line_BrushSelect extends HitTest_Line_PointToLineByDistance implements ISelector_BrushSelect { editMode = SelectionEditMode.setSelected; // @override selectionInfo = new VectorLayerEditorSelectionInfo(); // @override protected beforeHitTest() { // @override this.selectionInfo.clear(); } protected onLineSegmentHited(group: VectorStrokeGroup, line: VectorStroke, point1: VectorPoint, point2: VectorPoint, location: Vec3, minDistanceSQ: float, distanceSQ: float) { // @override this.selectionInfo.selectLine(line, this.editMode); this.existsPointHitTest = true; } protected afterHitTest() { // @override this.selectionInfo.selectLinePointsForLines(this.editMode); this.selectionInfo.updateLineSelectionState(); this.selectionInfo.resetModifyStates(); } } export class Selector_LineSegment_BrushSelect extends HitTest_Line_PointToLineByDistance implements ISelector_BrushSelect { editMode = SelectionEditMode.setSelected; // @override selectionInfo = new VectorLayerEditorSelectionInfo(); // @override protected beforeHitTest() { // @override this.selectionInfo.clear(); } protected onLineSegmentHited(group: VectorStrokeGroup, line: VectorStroke, point1: VectorPoint, point2: VectorPoint, location: Vec3, minDistanceSQ: float, distanceSQ: float) { // @override this.selectionInfo.selectPoint(line, point1, this.editMode); this.selectionInfo.selectPoint(line, point2, this.editMode); } protected afterHitTest() { // @override this.selectionInfo.updateLineSelectionState(); this.selectionInfo.resetModifyStates(); } resetModifyStates() { this.selectionInfo.resetModifyStates(); } }
It’s official! Years after they were first rumored to be dating, Chloë Grace Moretz has finally confirmed her relationship with Brooklyn Beckham. “I think the more I don’t make it mysterious the more people don’t care, so yes we’re in a relationship,” the 19-year-old actress confirmed on Watch What Happens Live on Monday night. View photos RELATED: Brooklyn Beckham and Chloë Grace Moretz Show Some PDA – See Their Sweet First Selfie! The pair were first rumored to be dating in the summer of 2014 and since then have been spotted out together numerous times. In April they took their first sweet selfie standing side-by-side with Brooklyn’s arm around his lady love. View photos So what does the Neighbors 2 star think of her man’s famous parents – David and Victoria Beckham? “He’s a great dad, she’s a great mother. They genuinely are very good parents that’s what matters most,” she said, adding, “They made a pretty son.” View photos MORE: Chloë Grace Moretz and Brooklyn Beckham Can’t Stop Instagramming Pics of Each Other! Clearly the proud parents agree. Just last week, the fashion designer took her eldest son to London’s National Portrait Gallery, posing in front of a photo of herself taken while she was pregnant with Brooklyn. “This Juergen Teller shot of myself and David brings back memories!! I was pregnant with Brooklyn!!! I love u@brooklynbeckham @davidbeckham,” she captioned the pic. Related Articles
Rightwing extremists kill and injure more people in lone wolf attacks than Islamic terrorists acting alone, according to a report by a security thinktank. The Royal United Services Institute (RUSI) in London says in its report Countering Lone Actor Terrorism that rightwing extremists across Europe present a substantial threat to the public that should not be overlooked. It details the cases of 94 people who were killed and 260 who were injured in attacks by far-right terrorists acting on their own between the start of 2000 and the end of 2014. In contrast, religiously inspired lone attacks killed 16 and injured 65 people. The report, which is released in updated form on Wednesday, says: “Rightwing extremists represent a substantial aspect of the lone actor threat and must not be overlooked.” It says that lone wolf extremists have been responsible for 98 plots and 72 attacks in 30 European countries including Norway and Switzerland in the period examined. Security services say the lone wolf terrorist attack is one of the most difficult to detect and preempt. The RUSI report is the result of detailed examination of terrorist plots and attacks across Europe and is being constantly updated. They include the killing of 77 and injuring of 242 people in Norway by Anders Breivik in July 2011 in shooting and bomb attacks fuelled by his rightwing views and belief in the Islamisation of Europe. The report says the intense focus among the public and in the media on the danger from the Islamic terrorist threat is at odds with the reality of the threat posed by rightwing lone wolves. They inflict a higher death toll and in percentage terms more of them are lone wolves, as opposed to motivated by organised terror groups, than religiously inspired terrorists. “The media, and consequently public attention, is largely focused on violent Islamist extremists; while this may reflect the broader threat, it is at odds with that from lone actor terrorism,” the report says. The research was carried out by RUSI and a consortium of thinktanks including Chatham House and provides a database of lone wolf terror cases across Europe. RUSI said the overall objective was to see if it was possible to discern patterns or trends that could feed into recommendations for policy makers. “Lone actor terrorists are perceived as presenting acute challenges for law enforcement practitioners in detection and disruption,” the report says. “By definition, they act without direct command and control from a wider network, and it is assumed that without such communications they may evade the ‘tripwires’ that would usually bring them to the attention of the authorities.” It also states that lone wolf rightwing extremists are harder to detect than religiously inspired Islamicterrorists. “It was established that 40% of rightwing extremists were uncovered by an element of chance, as part of an investigation into other offences or because the perpetrator accidentally detonated a device, drawing attention to his or her activities. Although chance was also evident in some examples of religiously inspired terrorism, overall 88% of interventions were intelligence-led, suggesting a clear disparity,” the report says. RUSI also found that rightwing extremists were far less likely to talk about their activities, and were often discovered only after detonating a device or killing an individual. Islamist extremists, however, in 45% of cases talked about their inspiration and possible actions with family and friends. “In contrast, only 18% of leakage by rightwing extremists was to this audience,” the report says. Rightwingers are also found to be more likely to be socially isolated or suffer mental health problems than other lone wolf terrorists and more likely to “post telling indicators” on the internet.
package ru.otus.kirillov.controllers.sockets.getCacheStats.messages; import ru.otus.kirillov.cacheengine.stats.CacheStatistics; import ru.otus.kirillov.utils.CommonUtils; public class GetCacheStatsUiSuccessRs { private final String cacheSize; private final String cacheHit; private final String cacheMiss; private GetCacheStatsUiSuccessRs(String cacheSize, String cacheHit, String cacheMiss) { this.cacheSize = CommonUtils.retunIfNotNull(cacheSize); this.cacheHit = CommonUtils.retunIfNotNull(cacheHit); this.cacheMiss = CommonUtils.retunIfNotNull(cacheMiss); } public static GetCacheStatsUiSuccessRs of(String cacheSize, String cacheHit, String cacheMiss) { return new GetCacheStatsUiSuccessRs(cacheSize, cacheHit, cacheMiss); } public static GetCacheStatsUiSuccessRs of(CacheStatistics stats) { CommonUtils.requiredNotNull(stats); return new GetCacheStatsUiSuccessRs( Integer.toString(stats.getCacheSize()), Long.toString(stats.getCacheHit()), Long.toString(stats.getCacheMiss()) ); } public String getCacheSize() { return cacheSize; } public String getCacheHit() { return cacheHit; } public String getCacheMiss() { return cacheMiss; } }
A 65-mile stretch of the Mississippi River remained closed at New Orleans on Monday following a . Authorities involved in the cleanup and investigation planned a Monday morning conference call as they worked on estimates of how much oil spilled and when the river would re-open, a Coast Guard spokesman, Petty Officer Bill Colclough, said. At last count Sunday night, the river closure affected 26 vessels -- 16 waiting to go downriver and 10 waiting to go upriver. Officials reported only a light sheen following the accident but river traffic was halted to avoid contaminating passing vessels and to prevent oil from spreading downriver. No injuries were reported in Saturday afternoon's accident involving the barge being pushed by a tugboat and another tugboat near Vacherie, 47 miles west of New Orleans. The other tugboat was pushing grain barges. Public drinking water intakes on the river were closed as a precaution in nearby St. Charles Parish, officials said. "The water supply in St. Charles Parish remains safe," parish officials said in a news release Sunday afternoon. The closure included the Port of New Orleans. However, both the Carnival Sunshine and the Norwegian Jewel cruise ships were able to leave the port Sunday to begin their scheduled cruises, said Petty Officer Craig Woerhle at the Coast Guard Vessel Traffic Service in New Orleans.
<reponame>FroHenK/Cynosura.Studio export class Config { apiBaseUrl: string; }
// NodeMeta is used to retrieve meta-data about the current node // when broadcasting an alive message. It's length is limited to // the given byte size. This metadata is available in the Node structure. // Implements memberlist.Delegate. func (d *delegate) NodeMeta(limit int) []byte { d.mtx.RLock() defer d.mtx.RUnlock() return []byte{} }
def remove_all_depositions(self): all_depositions = self.get_deposition() for dep in all_depositions.json(): self.remove_deposition(dep["id"])
## Larry Winget has already helped countless people to get ahead in life. Here's what a few of them have to say about him and his program: "With Larry's help I got myself out of massive debt, quit my underpaying job, and got my life in order. Larry's harsh manner is a reality check and a swift kick in the rear to get your life in order. While Larry's tough love and advice is hard to swallow initially, he is a life-saver!!!" —JEWEL PENA "Larry has a no BS approach. Some people might find him rough around the edges, even offensive, but when you think about everything he has personally overcome, you'll see that he knows what he's talking about! We are living proof that his philosophy works!" —GREG AND SUE COSCINO "He's not only been where we were, he's done what it takes to fix it. He has this type of passion to help those who are serious about changing their lives. Yes, Larry is a very blunt, in-your-face hard-ass. But if you listen to him, what he says makes sense and his ideas really work. Before Larry, we didn't think we were ever going to get ourselves out of our financial mess. But after listening to Larry we could see the light at the end of the tunnel." —NICK AND BECCA ## YOU'RE BROKE BECAUSE YOU WANT TO BE ## YOU'RE BROKE BECAUSE YOU WANT TO BE How to STOP GETTING BY and START GETTING AHEAD ## LARRY WINGET GOTHAM BOOKS Published by Penguin Group (USA) Inc. 375 Hudson Street, New York, New York 10014, U.S.A. Penguin Group (Canada), 90 Eglinton Avenue East, Suite 700, Toronto, Ontario M4P 2Y3, Canada (a division of Pearson Penguin Canada Inc.); Penguin Books Ltd, 80 Strand, London WC2R 0RL, England; Penguin Ireland, 25 St Stephen's Green, Dublin 2, Ireland (a division of Penguin Books Ltd); Penguin Group (Australia), 250 Camberwell Road, Camberwell, Victoria 3124, Australia (a division of Pearson Australia Group Pty Ltd); Penguin Books India Pvt Ltd, 11 Community Centre, Panchsheel Park, New Delhi–110 017, India; Penguin Group (NZ), 67 Apollo Drive, Rosedale, North Shore 0632, New Zealand (a division of Pearson New Zealand Ltd); Penguin Books (South Africa) (Pty) Ltd, 24 Sturdee Avenue, Rose-bank, Johannesburg 2196, South Africa Penguin Books Ltd, Registered Offices: 80 Strand, London WC2R 0RL, England Published by Gotham Books, a member of Penguin Group (USA) Inc. Copyright © 2008 by Larry Winget All rights reserved Gotham Books and the skyscraper logo are trademarks of Penguin Group (USA) Inc. LIBRARY OF CONGRESS CATALOGING-IN-PUBLICATION DATA Winget, Larry. You're broke because you want to be: how to stop getting by and start getting ahead / Larry Winget. p. cm. ISBN: 978-1-1012-1701-6 1. Finance, Personal. I. Title. HG179. W5473 2008 332.024—dc22 2007033838 Without limiting the rights under copyright reserved above, no part of this publication may be reproduced, stored in or introduced into a retrieval system, or transmitted, in any form, or by any means (electronic, mechanical, photocopying, recording, or otherwise), without the prior written permission of both the copyright owner and the above publisher of this book. The scanning, uploading, and distribution of this book via the Internet or via any other means without the permission of the publisher is illegal and punishable by law. Please purchase only authorized electronic editions, and do not participate in or encourage electronic piracy of copyrighted materials. Your support of the author's rights is appreciated. While the author has made every effort to provide accurate telephone numbers and Internet addresses at the time of publication, neither the publisher nor the author assumes any responsibility for errors, or for changes that occur after publication. Further, the publisher does not have any control over and does not assume any responsibility for author or third-party Web sites or their content. ## This book is for my wife, Rose Mary. She stuck with me through thick and thin. (Even when the thin was so thin it became transparent!) She watched me lose, she watched me win. She believed in me when no one else did and when I forgot to. She is my rock. A party gives laughter, And wine gives happiness; But money gives everything. —Ecclesiastes 10:19 ## CONTENTS Introduction: The Difference Between Poor and Broke PART ONE. WHY YOU'RE BROKE Chapter One. Money Matters Chapter Two. Your Real Problem PART TWO. HOW TO START GETTING AHEAD (MAYBE EVEN RICH!) Chapter Three. Know Where You Are Chapter Four. How to Get Out of Debt Chapter Five. How to Cut Your Expenses and Increase Your Income Chapter Six. The Stuff Most People Overlook Chapter Seven. Now It's Time for Your New Budget! PART THREE. PROOF THAT IT CAN BE DONE! Chapter Eight. Interviews with Larry's Rich Buddies Acknowledgments Information About Larry's Free Video Download: Five Financial Lessons from Larry ## YOU'RE BROKE BECAUSE YOU WANT TO BE ## INTRODUCTION THE DIFFERENCE BETWEEN POOR AND BROKE BEFORE WE BEGIN, LET'S MAKE SURE WE UNDERSTAND ONE ANOTHER. Don't start in on me because of the title. Please don't say, "But what about the poor people, Larry? They don't want to be broke." Great point. You're right. I'm not talking about being poor. Poor is a condition I find very sad. Sad, yet inevitable. Jesus said, "The poor will be with you always." And they will. There are people who live in societies and countries where there are no opportunities for advancement and it takes all their effort just to survive. They are not going to have enough to eat well or live well or take care of themselves. So let's get this straight from the outset so you can get off your high horse and understand what I am really saying. I didn't write this book for the poor people of the world. I know it is going to take a lot more than a book to help truly poor people. To think otherwise would be insulting. I am talking about broke. Broke is not a condition like being poor. Broke is a situation you find yourself in because you are either underearning or overspending. I can't fix poor, though I would love to. I'm good, but I'm not that good. I can fix broke. That's what this book is about. Read it and find out how to fix your situation so you don't have to be broke any longer. You can get ahead and live the way you want to. I'll show you how, step by step. I wrote this book for the average person who has a job, makes a living, and still can't seem to get ahead. If you're someone who dreams of being rich but can't quite seem to turn your dreams into reality; if you're ready to turn your life around and finally have financial freedom; if you are buried in debt and can't stop living paycheck to paycheck; if you spend more than you make and can't figure out how to stop doing it, this book is for you! Got it? NOW, BACK TO THE TITLE. You read it right. You are broke because you want to be. "How can you say that? You don't even know me! There is no way you can sit there saying that I want to be broke when you have no idea who I am!" Here is how I know: * * * If you didn't want to be broke, you wouldn't be broke. * * * It's as simple as that. What you say you want means almost nothing. When every action you make contradicts your words, your words don't mean a damn thing! This may be a new idea for you, or not. It doesn't matter! Aligning our intentions with our actions is something we can all learn to do better. It is the key to unlock your potential, get out of debt, and get ahead in life. It is something you can learn, but in exchange you have to give something up. VICTIMHOOD: A PRIVILEGE YOU CAN NO LONGER AFFORD. Stop being a victim! No one else is to blame for your situation. Broke didn't sneak up on you in the night. A stack of unpaid bills didn't show up while you weren't looking. You didn't suddenly get behind. You chose to spend your money the way you did. Your life is a reflection of the choices you have made. If you want a better life, then make better choices. When you do, you'll find that taking credit for your successes feels a lot better than blaming others for your failures. If you are desperate to improve your financial situation, then this book is a great place to start. WHY SHOULD I LISTEN TO YOU, LARRY? I have a television show on A&E called Big Spender. The show is about people who are in financial crisis due to their spending habits. I ambush them in the middle of a spending spree and confront them with the mess they have created. I go through their finances and give them a plan to turn their money and their lives around before everything crumbles around them. The show is not about investing or the stock market or any sophisticated financial solution. It is about rescuing people from the hole they have dug before it turns into a grave. There are shows that teach you how to invest and what to invest in. That's not what I do. I force people to confront their situation and then give them a concrete plan for improving their situation immediately. That's what I know how to do, and that's what I'm good at. In fact, all I really know about money is how to make it, how to enjoy it, and how to make sure there is always plenty of it. Isn't that what you want to know? Isn't that what you are most lacking? I bet I'm right. As important as that, however, is this: I've been broke. Really broke. I was so broke I couldn't even pay attention. Later I'll give you the details of what happened to me and what I did about it, but here is the overview of why you should listen to me: I grew up dirt poor. I decided to get rich. I got rich. I went bankrupt. I learned from it. I became a millionaire. There is my credibility: failure—success—failure—success. Real world. No silver spoon, no golden parachute, no pie in the sky BS and no get-rich-quick schemes. Nothing but work: work on my thinking, work on myself, and then just plain old work! I know what I'm talking about. I've done it. And I can teach you how to do it too. A WORD OF WARNING: I am not a blow-smoke-up-your-skirt, you-can-do-any-thing-with-a-positive-attitude kind of guy. I am a nose-to-the-grindstone, no-excuses-will-be-accepted kind of guy. I'm harsh. I'm abrasive. Your feelings will probably get hurt as you read what I have to say. I'm not the guy you go to so he can put his arm around you and say, "That's okay, it will be all right." It's not okay and chances are it won't be all right. I'm the guy you go to when you are circling the drain. I'm the guy you go to when everything else has failed and you are desperate. I know what it's like to be desperate because I've been there. It's terrifying. And the last thing you want is a hug and to be told to have a positive attitude. I believe you want real answers and are willing to forgo the niceties to get them. WHAT THIS BOOK ISN'T. This is not an investment book. I don't know enough about investing to write a book. I have no clue how the stock market works and I don't care. I hire real experts who have even more money than I do to advise me on my investments. When you have money, that's what you should do too. This is not one of those cutesy parable books. Like the ones that preach at you about being rich and then suggest you live a pauper's lifestyle. Why work hard to become a millionaire and then live like a pauper? Where's the incentive in that? I am also not going to tell you "I want you to be rich" like some authors do. The reality is, it doesn't matter what they want or what I want. Until you want to be rich, nothing will change for you. This book isn't one of those new-agey, money-is-a-spiritual-concept books. I won't teach you to develop your prosperity consciousness or get beyond your poverty consciousness. And I am not going to tell you to touch your chest or head and repeat affirmations like some authors do. While I believe completely in those concepts, this just isn't that kind of book. Affirmations are fine, but affirmations alone don't change your life. You can say, "I am rich, I am rich, I am rich" until your face turns the color of money, but until you stop doing stupid stuff with your money and start doing smart stuff with your money, you will still be broke. Affirmation without implementation is self-delusion. Most people can't identify with those approaches because they are just too far in the hole for those books to have any practical application. When you are trying to figure out how to keep your ten-year-old beater from being repossessed, it's hard to focus on the chauffeur-driven limousine you would like to own. And as for that big "Secret" that has become the most popular book and DVD on the planet, I have an issue. The Secret's basic philosophy is: What you think about and talk about comes about. That's fine, but it's only part of the story and will leave you short on results. A secret that gives you only half the instruction manual is worthless. You want the real secret? Here it is: What you think about, talk about, and get off your ass and do something about comes about. Telling someone that they can think themselves rich makes as much sense as saying you can think yourself thin and healthy. At some point, you have to put down the ice cream, get your fat butt off the sofa, and do some exercise. Think thin and eat a package of Twinkies and see how much weight you lose. Think rich and blow your rent money on shoes and eating out and see how that works for you. If you act in contradiction to what you think, you will end up worse off than you were to begin with. * * * The Real Secret! What you think about, talk about, and get off your ass and do something about comes about. * * * Do you need this book? Do you spend more than you earn? Do you worry about how you are going to pay your bills? Are you barely getting by? Do you live paycheck to paycheck? Are your credit cards maxed out? Do you have a shopping problem? Do you have little or no savings? Is Social Security your only retirement plan? Do you have more debt than you can afford to make payments on? Are you terrified of an emergency that would leave you financially devastated? If you missed a paycheck, would you be screwed? Are you clueless about how to fix your situation? If you answered yes to even one of those questions, you need this book! THIS IS WORK! Going from getting by to getting ahead is tough—really tough. I went from broke and bankrupt to millionaire and every step was a hard one for me. It still is. But it can be done. The principles I am going to teach you in this book are the principles I use to this day and still find challenging. Rich is never easy unless you are one of Trump's kids or your last name is Hilton. Most of us aren't born that way. We have to work for it. This book is about work. I won't sugarcoat it. Books don't make you rich. Sooner or later, like it or not, it always comes down to work. Sadly, most people won't put in the time or the effort to get what they want. I don't make many guarantees in life or in my books. But I will make this one: If you stick with me during these pages, fill out the forms, and dare to do what I ask, then you will be better off financially. Maybe you won't be a millionaire, maybe not even a thousandaire, but you will be better off financially than you are right now. I promise. ONE LAST THING: The work I'm talking about begins with this book. This book is a work book. You will find lots of blanks for you to fill in. Fill them in. You have to read this book actively in order for it to do you any real good. You can't become successful passively. I don't believe you should read a book passively either. Your first assignment is to get a highlighter to highlight passages you want to remember. Second, get a pencil or pen to fill in the blanks. Third, actually fill in the blanks. If you skip the work, you only cheat yourself and chances are you have been doing that way too long already. Okay, let's get started. And as I say on my television show, Big Spender: It's about to get ugly! ## PART ONE ## WHY YOU'RE BROKE ## CHAPTER ONE ## MONEY MATTERS So you want to stop being broke and start getting ahead? Bullshit. (Okay, I warned you. I don't mince words. That was a pretty hard slap in the face. Do yourself a favor and get over it. You have a problem and need help or you wouldn't be reading the book to begin with. Work with me and let's fix your problem together. Listen to what I have to say. I know what I'm talking about. After all, I've been where you are and now I'm rich.) You want to be broke because you are. If you wanted to stop being broke, you would have done something about it already. You haven't, therefore you don't want to. DON'T TELL ME WHAT YOU WANT. I already know what you want. You want your life to be exactly like it is. You want to be a person who just barely scrapes by, because you do. You want to be a person who pays bills late, because you do. You want to be a person who mooches off of others, because you do. You want to be a person who buys things you can't afford, because you do. You want to have a car you can barely pay for because it makes you feel better about yourself, because you do. You want to wear the hottest new fashions instead of paying your rent, because you do. You want to spend instead of save, because you do. You want to eat out instead of saving for your kid's college education, because you do. People do what they do because they want to do it. Period. Do this little exercise for me: Quickly turn your head from side to side. Did you see anyone on either side of you holding a gun to your head forcing you to do the stuff you are doing? If no one is forcing you to do it, then you must be doing it because you want to. It's as simple as that. Go ahead and get mad at me now for saying what I just did. In fact, I want you to get mad. While you are getting mad, think about this: Are you mad at me and what I've just said or are you mad at yourself because you know I'm right? "I DON'T REALLY WANT TO BE RICH, I JUST WANT TO BE COMFORTABLE." Comfortable means that you don't feel bad but you don't feel all that great, either. Most people are comfortable. That's the problem. Comfortable people don't feel bad enough to change but don't feel good enough to really be able to enjoy their lives. Either way, their future is doomed. People never make changes in their lives when they are comfortable. You have to get uncomfortable in order to make a positive change in your life. This book is supposed to make you uncomfortable. * * * You will never change until you first become uncomfortable. * * * "MONEY ISN'T ALL THAT IMPORTANT TO ME, LARRY." Yeah, right. People say that to justify the fact that they don't have money. In fact, the only people I have ever heard say that were broke. Money is important. People who don't have money can't help anyone. Hospitals are built with money. Charities are funded with money. Homeless people are fed with money. So get some money so you can do your part. You owe it to yourself and you owe it to the world. Imagine this: You are sitting on your sofa watching the television coverage of a disaster. Something like Hurricane Katrina has just happened and you want to help. You would love to write a check for a thousand dollars, or ten thousand dollars, or maybe even just ten dollars, but you can't—you're broke. When you are rich, you have the freedom to do that kind of stuff. Which does more good—wanting to help or being able to help? "But, Larry, I send good thoughts and I pray for those people." Good for you. Send your good thoughts and say your prayers, because they are important. Then write a check. The world needs your good thoughts, your prayers, and your money! * * * "Keep on succeeding, for only successful people can help others." —Dr. Robert Schuller * * * MONEY DEFINES YOU. Some of you will have a real problem with that statement. The fact that I said those three words will upset some people so much they will call me shallow, greedy, and lots of other uncomplimentary things. However, you can argue with that statement all you want and I will still be right. When you think of Diddy or P. Diddy or Puff Daddy or Sean Combs or whatever his name is this year, do you think of him as an African American, a male, an entertainer, a movie star, a fashion mogul? Or do you think of him as rich? I'm betting rich. Is he a good person? Is he benevolent? Is he a total jerk? Beats me—I don't know him. I do know that he's rich. Donald Trump. What immediately defines him? His hair? His real estate? His television show The Apprentice? Sorry, those things don't come to mind first when you think of him. It's his money. He is rich. Love him or hate him, those thoughts come after you think of how rich he is. Money defines Donald Trump to each of us. Money determines the neighborhood you grow up in. It determines the clothes you wear to school. Money usually decides who your friends will be and how others will treat you. Money decides whether you will go to college or not. Money usually even picks the college. Money determines the house you live in, the car you drive, and the clothes you wear. It determines whether you get a good doctor or an amazing doctor. It determines whether you hire an ambulance chaser or the best defense attorney money can buy. It determines every restaurant you go to, every store you shop in, and every entertainment activity you attend. Money even determines the size of your gravestone and the quality of the casket you will be buried in. Fair? Probably not. But life simply isn't always fair. It is what it is. This is reality. I don't make the rules, I just try to figure them out, play by them, and win in spite of them. Money has defined my life. My lack of money while growing up is what made me who I am today. It motivated me to become the best at whatever I was doing and to work harder than most others so I could make plenty of money and not be poor. Going bankrupt made me even more determined to get rich again. Now the presence of money in my life defines me to the point that I have the credibility to do a television show about money and write books about how to be successful. Am I more than that as a person? Of course I am. I'm a good husband to my wife, a good father to my boys, and a good son to my momma. I'm a mediocre golfer, a great decorator, and a pretty good cook. I design my own cowboy boots and I can paint a room better and faster than anyone I know. I am a lot of things other than rich. But money still defines my life. Money defines your life, too. My point with all of this? Never say money doesn't matter. MONEY ALWAYS MATTERS. While money always matters, sometimes people expect too much from money. There are many things that money won't do for you. Money won't bring you happiness. Happy people are happy whether they have money or not. Happiness is a choice. Let's not give money much credit when it comes to being happy or not being happy. There are rich people who are happy and rich people who are miserable. But at least rich people are miserable in a better part of town! Money won't buy you friends. The friend that money can buy isn't much of a friend. When the money goes, so will the friend. Money can buy you companionship, though. Don't believe me? Walk through any casino in Las Vegas and look at the rich old geezers with the eye candy on their arms. Those little hotties aren't there because they find potbellies, bald spots, and yellow teeth charming and fascinating. So if it is shallow companionship you are looking for, then money can help. True friendship is never bought and paid for. Money won't solve your problems. More zeroes does not mean fewer problems. Bad things happen to rich people just like other people. People who have money worry, too. Sometimes they even worry about money. Money doesn't mean you will pay your bills on time. People who pay their bills on time do so because that is the kind of people they are. If you don't pay your bills on time when you are broke, then you won't pay your bills on time when you are rich. The newspaper is full of stories about rich movie stars who don't bother with their taxes or who are being sued because they didn't pay their housekeeper or their bills. These people can afford to do the right thing; they just aren't the kind of people who do the right thing. Money won't make you more charitable. People who are charitable are that way regardless of income. I find it interesting that the people who are most charitable, in terms of percentage of income given to charity, are people of moderate income. Ask a bartender or waiter who the best tippers are. It's not always the rich guy who orders the bottle of Dom Pérignon; it's usually the regular guy who has a regular job. Money won't give you a better marriage. While money problems are the number one cause of marital problems, having lots of money won't guarantee you a better marriage. People with a bad marriage usually have a bad marriage for lots of reasons. I have talked with many couples who say the only problem in their relationship is money. Usually, it doesn't take long to find out that money is the least of their problems. One couple I worked with on my TV show had been dating and engaged for ten years but had never had a discussion about money. They were planning their wedding and had no money saved. They were living on payday loans, had accounts in collections, were months behind on their rent, and each year were spending tens of thousands of dollars more than they earned. They had even had a car repossessed. According to them, their only problem was they didn't make enough money. But it looked to me like they had commitment problems: After all, they had been together ten years and hadn't gotten married. They had communication problems: They had never had a conversation about their money. They lacked discipline, had problems taking responsibility, and had integrity issues because they didn't bother paying their bills or their rent on time. This couple was a mess on every front, yet it was easier to blame money than for them to take a good hard look at themselves. If this is your situation, I'm sorry. Get some counseling and go to work on both your finances and your relationship. Money won't make you successful. Success is about much more than money. Success is all-inclusive. Success is having good relationships, fulfilling employment, and being as healthy as you can be. Yet while money is not success, success certainly requires money. Money won't make you a better person. If you are an asshole when you are broke, you will be an asshole when you are rich. You will just be an asshole with money. There are good people and there are bad people. That is reality. Good people pay their bills. They are charitable. They do the right thing regardless of circumstances, whether anyone is watching or not. They work. They have integrity. They are honest. They honor their commitments and obligations. They take responsibility for their words and their actions. They take care of their families. Bad people don't do those things. People are the way they are because that is the way they choose to be. Money doesn't change the kind of person you are. You are who you are because of the choices you make, not because of how much money you have. Money magnifies everything. Having money is like holding a magnifying glass up to every aspect of your life. If you are a good person who does good things when you have only a little, then you will be a good person who does even more good things when you have a lot. If you are a rude, discourteous, arrogant asshole, that is who you are with or without money; money just makes you more noticeable. In fact, magnification is what gives money a bad name. We watch moronic rich people on TV and we blame their money for making them stupid. If Paris, Britney, and Lindsay weren't rich, they would be still be crashing their cars and acting stupid at Wal-Mart instead of on Rodeo Drive. You just wouldn't know about it. When you see rich people doing ignorant things, don't blame the money. Money doesn't make you stupid; it just gets your picture taken more often. * * * "Most of the things money is the root of ain't evil." —Malcolm Forbes * * * WHAT WILL MONEY DO? Money will allow you to spend money when you want to, give money when you want to, and have financial security. That's about it. "Wait! That's it? You had a whole long list of what money won't do and you only give me one sentence about what money will do?" Yep, that's it. All money will do for you is give you a little freedom and a little peace of mind. Trust me, that is enough to make it all worthwhile! "But you don't understand!" Now you are going to offer up the excuses, aren't you? Well, don't. Just don't. I've never found an excuse I could get behind or buy into. Know why? I can always find someone worse off than you, someone with problems bigger than yours, and they still figured out a way to be rich and successful. If one can do it, so can another. SOME OF THE COMMON EXCUSES FOR BEING BROKE: "I grew up poor." Having money is not the result of your environment. There are more people who have earned their millions than have inherited their millions. Lots of millionaires grew up with nothing. My grandfather was a carney. Seriously. He worked at a traveling carnival with a bear, a monkey, and a pony ride. Later he lived in a storeroom in the back of a furniture store. My parents never had much. Yet I still got rich. * * * It's not how you start out that matters, it's how you end up. * * * "God will provide." Saying that is like going on vacation and leaving your doors unlocked. It's not smart. Do that and even God would think you were being stupid. God already provided for you by giving you the ability to earn a living. Don't blame God for your situation or expect God to show up with the grocery money. Instead, get off your lazy butt and go to work! And while we are talking about God, let's cover another popular excuse: "It's God's will." What kind of God do you worship who wants you to be broke? If you think God wants you to be broke, you need a new God. After reading just about every book representing most of the world's religions that I could lay my hands on, I haven't found anything that would make me believe that God wants you to be broke. Don't ever get sold on the belief that it is God's will for you to have anything less than all there is. "I'm a single parent. I work hard. It takes all I've got just to get home, fix dinner for the kids, take a bath, and get some sleep." This is a tough one. I know there are lots of people in this situation and I'm sorry. But it can be overcome if you want to overcome it. There are too many stories of single mothers and fathers who work two and sometimes three jobs, put themselves through night school, and finally move from getting by to getting ahead and then rich. You can do it too, if it means enough to you. So I am not going to let you off the hook. I am going to understand, sympathize, and then ask you: "So with all of that going on, how many hours of television did you watch last week? Couldn't you have been reading a book? Isn't there something you could have done to increase your worth to your employer or to yourself? Couldn't you have been learning some marketable skill?" Ouch! We all think we work so hard, there is just no time for anything else. Yet a study I found about media consumption says that the average American will spend: 65 days per year in front of the television 41 days listening to the radio 7 days on the Internet 7 days reading the newspaper 7 days listening to music That's plenty of time to read a book, take a class, or do some work on yourself. Something that would make you worth more in the marketplace. * * * "If you feed your mind as often as you feed your stomach, then you'll never have to worry about feeding your stomach or a roof over your head or clothes on your back." —Albert Einstein * * * I readily admit that there are lots of hardworking people out there who never get rich. I get it. Two hardworking people raised me, so it's hard for me to get too far down on people who work hard and are still pretty much broke. But I will. It takes more than hard work. It starts with hard work but it still takes more. It takes the willingness to do whatever it takes to get ahead. My son Patrick is a fashion designer. He works as many hours and about as hard as anybody I've ever seen. Early in his career, when he was trying to figure out how to make a living doing what he was doing, he learned to live on practically nothing. He did all of his shopping at the dollar store. He worked eighteen to twenty hours a day. He learned to eat on twelve dollars a week. Luckily, he could make his own clothes! He would go to the fashion trade shows in Las Vegas and while his buddies in the business were staying in suites at Mandalay Bay and Caesar's Palace, he was at the Howard Johnson's paying $39 a night, sharing a room with his business partner, and eating rice cakes, beef jerky, candy bars, and five-for-a-dollar sodas they had bought at the dollar store. Now he makes good money and I predict he will be a millionaire in the next few years. But he paid his dues. He sucked it up and did what it took to survive regardless of how inconvenient it was. Along the way, he learned to speak Mandarin Chinese, Spanish, and a bit of Japanese so he could communicate with his suppliers and manufacturers. Now he says he wouldn't trade those days for anything because of the lessons he learned. The lessons he learned could fill a book, and knowing him, someday they will. Really, who can eat on twelve bucks a week in Los Angeles? While I admire what my son has been able to accomplish, I really told that story about him to get to the story of Joel, who worked with Patrick. Joel moved to the United States from Guatemala to make a better life for his family. He had a job sewing garments in a large garment factory in Los Angeles. He rode the bus an hour to get to his job, which started at 7:00 A.M. and ended at 5:00 P.M. He then rode the bus back home to eat with his family and at 7:00 P.M. boarded another bus to a movie theater, where he took tickets until 10:00 P.M. He then got on another bus to travel to Patrick's place, where he sat at a sewing machine until 1:00 A.M. sewing samples for Patrick. At that point, Patrick would drive him home. He did this six days a week, and many times, seven days a week. According to Patrick, he never complained and was always happy, cheerful, and thankful just to be able to have three jobs so he could help his family go from getting by to getting ahead. There are millions of stories like Joel's. Stories like this make me very intolerant of people who complain about their lot in life and how hard they work on their one job. You do what you have to do because it is the right thing to do for your family and yourself. You do it because you want more. You do it because you can. Success and prosperity are rarely, if ever, easy. Success takes lots of hard work. "I deserve to spend my money the way I want!" I believe you deserve to be financially secure, have some savings, and be able to enjoy the money you have. You deserve peace of mind. With those two sentences, I have just proven that I think more of you than you do of yourself. "I'm too far behind to ever get ahead." No, you aren't. It may be ugly for you and things may be truly bleak, but you can always get ahead. I am not going to insult you by telling you it will be easy. At times, digging out of your mountain of debt to get ahead will be overwhelming. But know this: You can do it if you want to do it. You may not be able to make your life perfect, but you can certainly make it better than it is. The biggest mistake you can make is to believe that your situation is hopeless. It's not hopeless because you aren't helpless. Accept responsibility for where you are and then go about fixing it. Give yourself a little credit; you're reading this book, aren't you? "I don't know how to get ahead. No one ever taught me." A woman once told me her father said to her that as long as you dress really nice, wear a Rolex watch, and drive a Mercedes, then nothing else matters. I told her that her father was an idiot. To teach your kid something so totally stupid is criminal in my opinion. I felt sorry for this woman—for about a minute. She was almost thirty years old. At some point you know what is right and wrong regardless of what your parents did or said to you. I helped another couple who told me that neither of their parents was ever good with money, therefore they weren't. Okay, that excuse flies. But only to about the end of the block and then it crashes and burns with the rest of the excuses. I understand that we are all products of our environments to some extent. That works until you are about thirteen years old; then you should be able to look around and figure some things out for yourself. When you are thirty-five years old and still blaming your parents, you need a reality check. Grow the hell up. "I'm not good at math." I had a guy tell me the reason he couldn't get ahead and pay his bills was because he wasn't good at math. Lousy excuse. Especially since this guy was only working nine hours a week! Math wasn't his problem. Work was his problem. I'm not talking about advanced algebra. Just write down how much you make and then below it write down how much you spend. If the number on top is smaller than the number on the bottom, there is a problem. "It's the credit card companies' fault." Believe it or not, that is a popular excuse I hear often. One woman told me that the reason she had so much debt and was on the verge of bankruptcy was because the credit card companies kept sending her preapproved applications. She told me if they didn't send the applications, she wouldn't feel compelled to take the cards and charge things. Consequently, she had fifty-seven credit cards and owed nearly $100,000. Credit card companies are not to blame for your situation. You are. When the applications come in the mail, don't open them. Don't fill them out. Shred them. "Stuff happens." Yes it does. But if you are blaming your lack of money on the uncontrollable circumstances of life, then you are lying to yourself. I know things happen. When I was flat broke, my dog's knee blew out and her knee replacement cost me $1,200 I didn't have. Was it the dog's fault that I was broke? Was the world plotting to get back at me because of my lack of money? Was it the veterinarian's fault that it cost so much to replace the dog's knee? No, it was my fault I was broke. Your indebtedness is due to your lack of control over your spending. When an emergency comes along, you should have the savings on hand to take care of it. "But, but, but..." Get your buts out of the way and admit that the reason you don't have any savings to take care of emergencies is because you spent it on other things. You chose not to sock away a few bucks like you should have. It's not the fault of the emergency. It's your own damn fault. "Things cost too much." I know how much things cost. I know the price of a gallon of gas and a gallon of milk. I am not one of those guys who doesn't do his own shopping and doesn't have a clue. I go to the mall and the grocery store and pump my own gasoline just like you do. Yet I can still promise you that things do not cost too much. Things just cost what they cost. Besides, you have no control over what things cost. Deal with it. Don't whine about it. Your problem is not what things cost; your problem is that you don't earn enough money to pay for the things you want. You can't control what things cost; you can control your money. "I don't have a high-paying job." I hate it when people say stupid things like "Of course he's rich, he's a doctor." Or "She owns her own company; no wonder she drives a Mercedes." "He's a ballplayer; of course he drives a Lamborghini." (Okay, that last one works.) Your job won't make you rich (unless you are a ballplayer). There are broke doctors and lawyers and dentists and lots of broke company presidents. And there are rich truck drivers and janitors and factory workers. I've helped a bankruptcy attorney married to a mortgage broker who were on the verge of bankruptcy. I've worked with mortgage underwriters who were so broke and their credit was so bad, they couldn't buy a house. I even helped a CPA who had never kept a personal check record. See the irony in those situations? Jobs and money have little to do with each other. Don't blame your job for the fact that you don't have any money. It's not your job's fault. It's your fault. "But I don't have any skills." Whose fault is that? Get some skills. Read a book. Go to night school. Take a correspondence course. There are lots of ways to get skills. Some are even free. Besides, you already have the skills to do better. You could get an extra job with the skills you already have. If financial security is important to you, you should be willing to do whatever it takes regardless of the inconvenience. YOU ALREADY KNOW WHAT IT TAKES TO DO BETTER. There are only three reasons people don't do well in life. They are stupid, lazy, or don't give a damn. Which fits you? First, you aren't stupid. You may do stupid things, but you aren't stupid. Every person with a heartbeat knows at least one thing they could do to be more, do more, and have more. Let me prove it to you. I am going to ask you to look at several areas of your life and write down one thing you know you could do to make it better. I will help you by giving you an example. I want you to add one to what I give you. Be specific, because you know yourself better than anyone does. * * * THE ONE THING I KNOW THAT WOULD IMPROVE MY RESULTS: AT WORK. Larry's one thing: I will work every minute they pay me to work. My one thing: WITH MY FAMILY. Larry's one thing: I will stop parking myself in front of the television and instead spend time with my family. My one thing: WITH MY SIGNIFICANT OTHER. Larry's one thing: I will tell her something I appreciate about her every day. My one thing: TO BE A BETTER PARENT. Larry's one thing: I will spend at least twenty minutes a day talking to my kids in real conversation about things they are interested in. My one thing: WITH MY HEALTH. Larry's one thing: I will eat a little less and exercise a little more every day. My one thing: TO BECOME SMARTER. Larry's one thing: I will read a nonfiction book about how to be more successful. (Good news, this one counts!) My one thing: WITH MY FINANCES. Larry's one thing: I will stop spending money on things I don't absolutely need. My one thing: * * * See? You know at least one thing you could do in each area I have listed. You even know something you could be doing to improve your financial situation. The problem never is that you don't know what to do. The problem is that you don't do it. In other words, you are lazy! And you don't care. I don't get this at all! I don't understand how anyone can know what it takes to do better in life and not care enough about themselves or their family to do it. WHAT'S YOUR EXCUSE? Did I miss yours in my list of excuses? I might have. It would have taken a hundred pages to cover all of the excuses people use for not having enough. In addition to those I've listed already you could probably add: So what's yours? What are the excuses you use for your financial problems? Write them down. Without even looking at what you have just written, I can tell you that there is a problem with your list. You aren't on it. That's right. The list of reasons for not doing well in your life is actually a very short list. It should contain only your name. Why don't you just go back and add it? * * * "People do not want to take responsibility for the scarcity in their lives. It is much easier to blame circumstances, others, events, or even God for the things they have failed to acquire or achieve." —Dr. Wayne W. Dyer * * * In the next chapter, find out how to stop making excuses and start solving the problems that are really holding you back. ## CHAPTER TWO ## YOUR REAL PROBLEM THE BIG SHOCKER: You don't have a money problem. "I don't have any money; to me, that seems like a problem." The fact that you don't have any money is a result of all your other problems. You have thinking problems. Attitude problems. Self-esteem problems. You are lazy. You lack discipline. You lack integrity. You don't take responsibility. You lack goals. Your priorities are out of whack. Your biggest problem is not in your wallet or your bank account. Your biggest problem is between your ears. You will fix your money problems when you fix your other problems. That's what we are going to address right now. SPEND YOUR WAY TO RICH. "This doesn't even make sense, Larry. You can't spend your way to rich. Spending is what made me broke!" No it isn't. Spending didn't make you broke. Spending on the wrong things made you broke. When you learn to spend on the right things, then you will be rich. * * * "Almost any man knows how to earn money, but not one in a million knows how to spend it." —Henry David Thoreau * * * I dealt with a couple on my television show, Big Spender, where the wife had $600,000 worth of clothes. That's not a misprint. She had $600,000 worth of shoes, purses, and clothes. She had over four hundred pairs of designer shoes and three closets full of clothes separated by designer label! The couple didn't own a house. They spent much more money than they earned. Their credit rating was pathetic. They were living in her mother's house rent-free, in order to save for a house, while her mother lived with her grandmother. But they had spent all the money they were supposed to be saving on designer shoes and clothes and owned not one thing that mattered long term. They could have paid cash for three $200,000 houses! Instead, they had nothing. Spending didn't kill their financial future, but spending on the wrong things did. * * * If it's on your ass, then it's not an asset. * * * I never quit spending even when I was flat broke and bankrupt. I did quit spending on things with no future value, though. Eating out? We stopped. New clothes? We stopped. Cable television? It went away. My wife and I made a deal that we would spend money on only one thing: getting smarter. I bought books. I would skip a meal and skip watching television, but I wouldn't skip an investment in my brain. I knew that investing in success would pay off. And it did. After twenty years and nearly four thousand books, I am beginning to figure some things out! Education is not an expense; it is an investment. THE $30,000 MILLIONAIRE. When I was a little boy I saved up my pennies to order Sea-Monkeys from an ad in the back of a comic book. They looked so cool—happy little creatures smiling and swimming around in their little castles. I (and a million other little boys) found out, much to our dismay, that the precious little sea monkeys we were hoping for were nothing more than nasty little brine shrimp kicking around in dirty water. I got ripped off but I learned a valuable lesson. Things are not always as advertised. And that is the story of the $30,000 millionaire. You know the kind: the guy who earns thirty grand a year and yet tries to look and live like a millionaire. He has one cool outfit, a pair of $300 sunglasses, and parks his AMC Gremlin down the street from the highest-priced, classiest bar in town, then walks in like he owns the place and maxes out his third MasterCard trying to impress others. As they say in Texas, "All hat, no cattle." The $30,000 millionaire is a person who puts all his effort into looking rich rather than actually being rich. If he put as much effort into being rich as he did in looking rich, he just might find himself rich. FOLLOW THE MONEY. Just like in a crime drama, politics, or a good murder plot, the key is to "follow the money." Money is a dead giveaway of what is important in anyone's life. What do your bank statement and credit card statements say about you? I was working with one family when I asked the father if he loved his son. He said of course he did. I told him he didn't. I told him that he loved his cigarettes more than he loved his son because he spent more on his cigarettes than he did making sure his son had a secure future. I then took his cigarettes from him, threw them on the floor, and stomped them flat with my cowboy boot. He was pissed! I loved it. And I was right. It doesn't matter what you say is important to you, your actions always tell the truth. When you follow the money, you know what someone really loves. If you spend hundreds or even thousands of dollars at the mall to make sure you look fashionable and cute, then looking good is important to you. That's fine. Look as cute and fashionable as you can afford to look. But if you do that instead of making your car payment or paying your utilities or putting away money for your future or your kid's education, then you have messed-up priorities. I asked a guy who was in deep financial trouble what was important to him. He said, "Having fun, my family, and my wife." Gee, I wonder why he was in trouble? He put having fun ahead of everything else in his life. And that's exactly where his money went. He owed for his student loans, owed family members, and owed lots of other creditors, yet he spent money on gadgets and plasma-screen televisions and partying with his buddies and never even bothered to open his big basket full of bills. I dealt with another couple who had spent $70,000 on their wedding. Then they did a thirty-year refinance on their house to come up with the money to pay for it and their other credit card bills. I told them that on their thirtieth anniversary they could break out the champagne and toast the fact that they had finally paid for their wedding. Am I against expensive, fancy weddings? No, but for that couple the expense was out of scale with their income. One day of happiness and some good pictures and then thirty years to pay it off doesn't compute. You have to get your priorities straight before you ever are going to get your money straight. You need a written-down list of exactly what is most important to you. You do have that, don't you? "I just live. I have the stuff I have the money to pay for, or the stuff they will allow me to charge. My life is just the way it is. I don't have a list." There is your problem! No list. We are going to fix that now. Make a list of what is important to you. Write down everything that really matters to you. * * * WHAT IS IMPORTANT TO YOU? Okay, that's what you say is important to you. Get your bank statement and your credit card statements and write down where you spend your money. Then you will know what is really important to you. * * * See any difference between the two lists? Are you willing to do what it takes to get your actions into alignment with your priorities? IT'S EASIER THAN YOU THINK. This is how I did it: I decided to get rich. It happened when I was thirteen years old. I walked into civics class in the eighth grade wearing my only pair of blue jeans. They weren't Levi's like all the cool kids had. They were Roebucks. Remember Roebucks? Most people have never even heard of Roebucks. They were the Sears store brand jeans back in the '60s. My dad worked for Sears, Roebuck and he got an employee discount, so I had to wear the cheapest jeans that we could buy at a discount. My parents couldn't afford more than that one pair of blue jeans for me. The jeans had a tear on one of the pockets. The significance of that tear was that it made it obvious that I only had one pair of jeans. One day one of the kids in my class said to me, "Winget, you wear the same pair of jeans every day. Can't you afford more than one pair of jeans?" He said it in front of a lot of people and, most importantly, a lot of girls I would have done anything to impress. I tried to laugh it off and say that I had lots of jeans and somehow I tore them all in the same spot. But I was still busted. I knew it and they knew it. My parents were great people and doing what they could, but the bottom line was that I was a poor kid with only one pair of blue jeans to wear to school every day. I hated it. At that moment, in Muskogee, Oklahoma, at Alice Robertson Junior High School in eighth-grade civics class, Larry Winget decided he was going to be rich. While I had no idea how I would ever be rich, I knew I would do anything not to be poor. I couldn't bear the humiliation of being poor and having people know it. That decision shaped my life. I got rich at that moment. It took me more than thirty years to make it happen. After my decision to get rich, I began taking action. I got a picture in my mind what rich looked like, felt like, and smelled like. I started writing things down. I made lists with details of how I wanted to live and what I wanted to have. I affirmed wealth. The first thing every morning that came out of my mouth was, "I am happy. I am healthy. I am rich." Still is. I learned to celebrate every prosperous thing that happened to me. I stopped focusing on what I didn't have and started focusing on what I did have. While I didn't have much, I had the willingness to do whatever it took to get ahead. And what it takes that most people aren't willing to give is work. Hard work. Work on yourself, work on your life, and working while you are at work. In college, I did several things to make money. I raised houseplants from cuttings and sold them out of my driveway on weekends. I tied macramé pot hangers and sold them as well. My fingers were covered with blisters from tying so many. I was a telephone operator from 10:00 P.M. until 7:00 A.M. I then drove an hour to get to college, where I attended classes from 8:00 A.M. until 3:00 P.M. I came home and went to sleep for a couple of hours, got up and did my homework, and then tied macramé for a couple of hours. Am I bragging? Sort of. I'm proud of it. I worked. I was usually tired, burned out, and worn out. But I was willing to do whatever it took to get more out of life. As I look back I realize that I was never too good to do anything I needed to do to change my circumstances. There are people who have done much more than I have done and overcome odds much worse than mine to become rich. Stop thinking you are different or that your story keeps you from getting rich. Your story, regardless of how bad it might be, is not unique. I'll bet you are disappointed now, aren't you? You wanted more than some guy telling you to decide to be rich and then work your ass off to get there. You wanted some complicated strategy for wealth. I don't have one. I simply wanted to be rich, I decided to be rich, and I was willing to work as hard and as much as I needed to make it happen. WHY IS MORE IMPORTANT THAN HOW! * * * "He who has a why to live for can bear with almost any how." —Friedrich Nietzsche * * * In the second half of this book, you will learn how to realize your goals. I'll give you the steps it takes to make them real. But knowing "how" makes little difference without knowing "why"! Why is the motivator, the incentive, and the thing that keeps you sticking with it even when you don't feel like it. How is the work. Why is the reason to do the work. Why did I get rich? I owed it to myself. I owed it to my family. I wanted it. I knew I could do it. I didn't want the humiliation of having less than I could have. I wanted to know that I could achieve anything I decided to achieve. I wanted to live better than anyone in my family had ever lived. I wanted to travel, stay in nice hotels, and eat at great restaurants. I wanted to shop at expensive places and drive amazing cars. I wanted to be able to send my kids to any college they wanted to attend. I wanted my wife to have anything she wanted. I wanted a house that others would look at and say, "Wow!" I wanted to be able to help others by giving to charities that touched my heart. Those are just a few of my "whys." What are yours? ## PART TWO ## HOW TO START GETTING AHEAD (MAYBE EVEN RICH!) ## CHAPTER THREE ## KNOW WHERE YOU ARE Of all the people I have worked with on their money and money problems, there has yet to be one—I mean one—who knew how much money he earned and how much money he owed. You can't get ahead until you know what you have to work with. It's time to figure out exactly how much you owe. This is where you make a list of every dime you owe and who you owe it to. I mean all of it. That hundred bucks you borrowed from your brother-in-law goes on the list. This is also the place where you write down your other monthly expenses. Anything you spend money on such as groceries, gasoline, eating out, going to the movies, pet care, and more all go on the list. Don't just write down what you think you are spending; go from actual expenses. Check your bank records, receipts, and credit card statements. This is not the place to fudge the results; this is the place to tell yourself the cold, hard, ugly truth about your money. Now it's time for you to figure out exactly how much you earn. * * * THE MONEY YOU HAVE ON HAND: * * * This is what you have to work with other than your regular monthly income. Sadly, the total above is probably going to be pretty low because most people just don't have much money on hand. So let's move on to the number you really have to work with. * * * HOW MUCH MONEY I TAKE HOME (AFTER TAXES) EVERY MONTH: Monthly income:_______ * * * Now let's do a little basic math: Monthly income: _______________ Minus monthly expenses: _______________ Your financial picture: _______________ Here is a hint: The number on top should be bigger than the second number, leaving you with an excess of money each month. If you are currently making less per month than you spend each month, then you are in deep doo-doo. It either means you aren't paying your bills or you are living on credit cards. Shocked? I have done this exercise with many people and I've never met anyone who wasn't shocked by how much money they were spending. I have shown people they were spending twice what they earned and they didn't have a clue. I have sat with people who thought they were spending only about $1,000 a month more than they earned, only to prove to them, based on their true expenses, that they were spending nearly $7,000 a month more than they earned. * * * If your outgo exceeds your income, then your upkeep becomes your downfall. * * * So, how much short are you? Write it down _____________ If you aren't short, then how much more do you make than you spend? Write it down ____________ * * * HOW DOES THIS MAKE YOU FEEL? Capturing the emotion of how you feel right now is important. Take a minute and write down how you feel after finally discovering your true financial picture. * * * TAKE RESPONSIBILITY FOR YOUR SITUATION. EXPERIENCE REMORSE! I am talking about good ol' "Holy crap, I'm an idiot!!" remorse. I want you have the kind of remorse where you wallow in the mud, feel like a moron because you are, cry, apologize, and think there is no bigger dumb-ass on the planet. I want you to go to the mirror and look at yourself with tears running down your face and bemoan the fact that you and only you are to blame for all your problems. I want you to hurt and hurt bad! I want wailing and gnashing of teeth of biblical proportion. Why? Because it's honest. If you are spending more than you make, are in debt because you can't control your spending, and earn less than you could, then you deserve to feel the pain of your choices. I believe pain is a much better motivator than pleasure. Don't believe me? Think of Jack Bauer on the television series 24. I love that show and chances are you have seen it. If you haven't seen it, just know that Jack Bauer is a Bad-ass with a capital B. When the boogeyman goes to bed at night, he looks under his bed to see if Jack Bauer is hiding there. If Jack Bauer sat you down in a chair and said to you, "Tell me where the nuclear bomb is and I'll send you on an all-expenses-paid vacation to Tahiti," or if he tied you in a chair, held a pair of wire cutters to your hand, and said, "Tell me where the nuclear bomb is or I'm going to cut off your fingers one by one and watch you bleed to death," which would get your fastest and most honest response? See what I mean? Pain is always a better motivator than pleasure. Plus, remorse is the first step toward accountability. When you feel bad for doing something, you are taking responsibility for the action. On my A&E reality series, Big Spender, I confront people with their financial problems. Some of them cry. I like it when people cry. In fact, I love it when people cry. Not because I'm a bully who enjoys watching tears run down someone's face but because it shows me that they have finally attached some emotion to their mistakes. They are feeling the pain of their decisions. When that happens, they have a shot at changing. In one episode, I dealt with a guy who was a moocher. He mooched off his parents and his fiancée. He drove a car that was in his fiancée's name. He carried a credit card that was also in her name because his credit was too bad to get his own. He carried another credit card that was in his mother's name to buy all of his gasoline. He lived with his fiancée in a house that was in her name and he didn't contribute one dime toward the house or any of the household expenses. He ate out nearly every meal because he didn't like to cook, eat leftovers, or eat frozen food. He was a grown man acting like a spoiled baby. I confronted him with his mistakes and gave him the verbal spanking he deserved. I was all over this guy. It got ugly! I made him sob and boo-hoo until he finally admitted his mistakes. It was painful for him. (Sometimes, Jack Bauer looks under his bed to see if I'm there!) At the end of the day of shooting, he wanted to quit. He didn't see any way he could continue, because he didn't want to go on national television and appear to be the bad guy or look stupid. The problem? He was the bad guy and had been very stupid. I told him while there was no way to change the past, no one would judge him poorly if he turned it all around in the future. I was giving him a chance to look like a hero instead of a bad guy. He had already done the hardest thing of all: He had taken responsibility for making the mess and he felt bad about it. The rest, while tough, is never as tough as that first, all-important step. In my own life, when my back was against the wall and there was literally no place to turn, I went to see a bankruptcy attorney. The attorney talked to me about options, but explained after reviewing my case that I didn't really have any. Because of the business I owned 15 percent of, and my willingness to sign the loans, which included my personal guarantee on each of the loans, I was toast. So off to bankruptcy court I went. If you've never been, trust me, it's not a place you want to go. Some of my creditors even showed up. I had to talk to them and answer their questions. I had to look them in the eye and admit to them and everyone in the courtroom that I was a deadbeat and couldn't pay them the money I had agreed to pay. One of them even yelled at me and wanted to know what kind of a person I was to get myself in that condition. I didn't have an answer. My head was hanging so low that I couldn't even look up past my feet. I was disgraced. I had let my family down, ruined our credit, and embarrassed myself. My bankruptcy filing came out in the newspaper. Everyone I knew was aware of what I had done. I had been branded a loser and a failure. I could not imagine feeling worse. I was left with two choices: wallow in it or get past it. I decided to get past it. I sucked it up and went to work doing anything I could to make a buck. That humiliation motivated me. The pain of going through that experience made me know that I was never going to feel like that again. I made a commitment to get rich again. Feel the pain. Know what you cost yourself and your family. Know how your irresponsibility is going to affect your life for a good long while—maybe forever. Then, after you feel appropriately remorseful, wipe away the tears, suck it up, and get mad about it. Anger can be a very healthy emotion when used to motivate yourself into positive action. Get angry and fight back. Yep, I said fight. You are in a battle. You need to steel your confidence with anger. Be angry that you messed up. Be angry that you didn't keep your word to your creditors. Get mad at yourself for all your mistakes. Get sad, get mad, and then get on with it. The progression for moving forward: Remorse Anger Determination! COME CLEAN. If you are part of a couple who is in financial trouble, this is the time to come clean about all of your expenses. No hiding things. You need to know where you both are, so get it all out in the open and deal with it. I worked with one couple that was in real trouble. She was a shopping maniac. Her husband knew about her debts, or so he thought. Behind his back, she borrowed $30,000 from her mother to consolidate some of her credit card expenses. He was clueless about this transaction. I exposed her deceit on national TV and he was, to say the least, pissed off. But not as pissed off as I would have been. I can be tolerant of almost anything other than purposeful deception and lying. You need to work together on your problem or your problem simply won't get fixed. One person in the couple can't do it alone. If only one person in the partnership tries to fix it alone, then he or she will begin to resent the other person and the relationship will suffer because of it. When I crashed and burned financially, my wife and I circled the wagons and worked together to fight our way back. We opened up the lines of communication like never before. We plotted and schemed and presented a united front to our creditors and to the world. It made our marriage stronger. In fact, it is one of the things that has sustained us through the years when we have faced any number of problems. KNOW WHERE YOU WANT TO BE. I have been in the self-help business for nearly twenty years. Over that time I have talked with thousands of people one-on-one about their lives. I used to get letters and now I get e-mails—hundreds of them each month—from people who want to ask me questions about how to better their lives. Most just want to explain how bad their lives are. They don't really want to get better. I actually write most of these people back personally. My favorite question to ask them is, "Did you have a plan to lead a life that is so messed up? Did you write down that you wanted to be broke? That you wanted to be stuck in a dead-end job? That you wanted to be trapped in a crappy marriage? That your kids would be a mess?" I know their answer will be, "No, of course not!" I then ask, what was their plan? I know the answer to that one, too. They didn't have a plan. None of the people I've helped on my television show has had a written-down plan. Not even a 3 ´ 5 card with one sentence on it. Not a Post-it note. Nothing. And they wonder why their lives are such disasters. Isn't it obvious? They don't have a plan for their life to be anything other than a disaster. Do you? * * * Nobody ever wrote down a plan to be broke. Broke happens when you don't have a plan. * * * How much money you would like to earn? How much money would you like to have in savings? How much money would you like to give to charity? How much money would you like to have in an education account, an emergency fund, etc. How would you like to dress? Where would you like to travel? At which restaurants would you like to eat? What kind of car would you like to drive? What would you like to own? What kind of house would you like to live in? What part of town would you like to live in? You get it by now. So what do you want? How would you like to live? Write it down: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Just like the title of the book says: You're broke because you want to be. You can also be rich because you want to be—but only if you are willing to take action. CREATE AN ACTION PLAN TO GET WHAT YOU WANT. It's not enough to just know what you want. If you only focus on wanting things, you will end up with more want. You have to have an action plan: things you can do every day to move yourself closer to your goal. It is important for you to know what you want in the future, but now you need to put your energy into the present. Always ask yourself what you could be doing right now to make sure you have the future you want to have. To be fair, you probably didn't write much down in that section because you simply don't know where to begin. That's okay: I'm about to help you with that. Read on. ## CHAPTER FOUR ## HOW TO GET OUT OF DEBT Time for the real how-to stuff now. It's time to take some real action on your life and your financial future. If you want to turn your life around financially, it's really very simple. It comes down to two things: You have to either reduce expenses or increase income. Which should you do? Both. To really get ahead, you have to spend less money and earn more money—it's not enough to do just one. Here are the steps you should take right now to help you do just that: STOP SPENDING. * * * THE HOLE PRINCIPLE. When you find yourself in a hole—stop digging. * * * It doesn't make sense to go any deeper in debt. So don't. Plug the holes. Stop the hemorrhaging. Spend money only on the necessities. What are the necessities? Shelter. Your rent or your house payment. This includes utilities. Food. That means eating conservatively...at home! Bills. Your obligations. Money you have already spent that must be paid back. Those are the necessities: a roof over your head, food in your tummy, getting out of debt. And remember, no new debt! KEEP A JOURNAL. Part of knowing where you are is to keep a journal of your expenses. Get a little blank book or even a spiral notebook. Put the date at the top and draw a couple of vertical lines. Write down what you spend your money on and exactly how much everything costs. Keep track of every penny that flows from your hands on a daily basis. Track the categories of your daily expenses: gas, food, clothes, shelter, utilities, insurance, entertainment, and stupidity. Yes, stupidity is a category, too. We all have things we spend our money on that are just flat-out stupid. When you start tracking your stupid stuff and see how it adds up at the end of the month, you will be less likely to spend your money in stupid ways next month. JOURNAL PAGE EXAMPLE CUT UP THE CREDIT CARDS. You knew this was coming. This is old, worn-out news. So stop right now; go get your purse or your wallet and a pair of scissors and start cutting. Keep one card for emergencies. And a trip to the mall is not an emergency. (I once told a young woman that she had to cut up her credit cards but could keep one for emergencies. She picked her Neiman Marcus card. Holy crap! All I could do was shake my head and tell her to cut it up.) You get to keep one of the following: a Visa, MasterCard, American Express, or Discover. Something you can use anyplace when you have a real emergency—I'm talking broken bones or blood, something that requires medical attention. I am not anti–credit card. I have several. But I pay them off when the bills come in. That's the rule. If you can't pay it off when the bill comes in, or at least the following month, then don't charge it. Old balances cost you way too much in interest. Notice I didn't say, "Cancel the credit card." I said cut it up. If you have a credit problem, then cutting up the card means you won't have the card to carry around and you won't be able to use it to increase your debt. No card, no way to use it. Very simple. THE THREE MOST IMPORTANT NUMBERS IN YOUR LIFE. Surprisingly, those numbers are not your IQ (assuming yours hits the triple digits). Those three numbers are your credit rating. * * * There are two things you will never be without: One is your reputation and the other is your credit rating. You can ruin both in an instant, and you may never be able to fix either. * * * Your credit score determines whether you can get a loan and how much you will pay for the loan. It's important. Over a lifetime it can either save you hundreds of thousands of dollars or cost you hundreds of thousands of dollars. It can even have an impact on whether you get a job or not. Your former employer won't legally be able to tell me whether you are a responsible person, but your credit score will. Protect your credit score at all costs. It is going to be with you forever. A bad credit score never really goes away. You can take the steps to fix it and the bad ratings will drop off eventually, but if creditors dig deep enough, those little dings will still always be there like a dark cloud hovering over you. Note: It is impossible to give you a specific number of what constitutes a good credit rating. Scores range from 350 (rare) to over 800 (equally rare). I'll just say that your number needs to be in the mid-600s for you to qualify for a decent interest rate on a home or car loan. But a swing of even 20 points in either direction can make a huge difference in the amount of money you end up paying over the life of your loan. Your overall goal should be for a rating in the 700s. To find out more about your credit score, contact any of the three major credit reporting bureaus: Equifax: www.equifax.com Experian: www.experian.com TransUnion: www.tuc.com CALL YOUR CREDITORS. The most common mistake people make with their creditors is to stop talking to them. They hide from them. They duck creditors' phone calls and ignore their letters. Stop doing that. Take the initiative and open up the lines of communication. That's right, get on the phone and talk to them. Credit is judged on two things: willingness and ability to pay. If you haven't been paying your bills, then you have already demonstrated to your creditors that you don't have the willingness to pay. Let them know you are now willing to pay them. Talk to them about your ability to pay them and negotiate the best deal you can for repayment of your debt. Don't pay someone else to call your creditors. The "credit doctors" will happily call your creditors to negotiate on your behalf, but they don't do this for free. There is a charge involved and sometimes it is hefty. Want to know why they can charge so much to do it? Because they know how much you don't want to do it. Don't pay someone else to clean up a mess that you made. SET PRIDE ASIDE. When a creditor calls asking for money that is due, don't be defensive. This is a huge mistake most people make when it comes to dealing with their creditors. Thirty years ago I worked in the business office for Southwestern Bell, calling people about their telephone bills. I got yelled at, cussed out, and called names just for asking people to pay their bills. I learned some things from that job about paying your bills. If a late payer would just tell the truth and admit that he messed up, take responsibility, say he was sorry, and send me any amount of money no matter how small, I would leave his telephone turned on. Lie to me and the next time he reached for that phone, he wouldn't hear that sweet little dial tone in his ear; he would hear only the deafening sound of silence. Don't forget it's your fault you are behind on your bills, not the fault of your creditors. Your creditors are only doing their job when they try to collect from you. Their job sucks. They have been lied to, cussed at, and heard every excuse in the book. Be nice to them. Shoot them straight and send them some money. Never make a promise you don't intend to keep. Work with them, not against them, and you might find them pretty easy to get along with. You need your creditors on your side, so don't alienate them. Try this: Pay everybody something, even if it is just a little bit. The ones with the highest interest rates get the most. The one with the smallest interest rate gets the minimum payment. But everyone gets something. WARNING!! SLOW TRAFFIC AHEAD! Getting out of debt and becoming financially secure is a slow process. Just like getting into debt was a slow process. It takes some time. Don't get depressed and disillusioned because it is taking so much time to pay things off. Chances are you have very high interest rates and most of your payments are going to interest. That means it will take a long time before you ever even hit the principal. Don't give up. You nickel-and-dimed your way into debt and you are going to have to nickel-and-dime your way out. Get a calendar. Get one with squares big enough to write in. Write down the day each bill is due. When you make the payment, write PAID in bright red across it. I can't begin to tell you the relief you will have when you see a calendar full of big red PAIDs written all over it. It will make you sleep better, that's for sure. Pay what you agreed to pay, when you agreed to pay it. It's an issue of integrity. Paying your bills late makes you a liar. The credit card company agreed to extend you the credit and you agreed to make your payment on the designated day. You even signed a contract saying that you would abide by the terms of the agreement and pay your bill on a certain date each month. If you aren't doing it, then you have lied. It's as simple as that. You aren't holding up your end of the bargain. CALENDAR PAGE EXAMPLE Pay your bills as they come in. Don't save your bills and pay them all at once. First, that makes it a chore. And we all do our best to avoid a chore. Second, a big stack of bills can be overwhelming. Instead, when a bill comes in, pay it. It only takes a minute and will give you a feeling of accomplishment that you are paying your way out of debt on a regular, almost daily basis. Make little payments on your payments. This is a trick I learned years ago when I owed a lot of people a lot of money. When a bill comes in, let's say a credit card bill, pay as much as you can at that moment. However, make a copy of the payment part of the bill. In fact, make several copies. Then when you get a little more money, write another check and send it in. Yes, it is a little more trouble and will cost you for additional envelopes, some stamps, and the cost of the copies. But it's worth the fifty cents to make even a ten-or twenty-dollar payment on your account. I have made two and three payments a month on a bill because I found I had an extra twenty dollars that wasn't obligated. So I obligated it before something else could come along. You will be chipping away at your debt, and you won't be tempted to spend the money on something else. Use all available income to pay down your debts. Don't think you can borrow your way out of debt. Beware the temptation to borrow money to pay off debt. We have all been tempted by the debt consolidation home equity loans and on rare occasions those make sense. When you do it, you are reducing the interest on the amount owed: a good thing. But unless you can rein yourself in and not incur more unsecured credit card debt, then you are going to end up right where you are again: clearly a bad thing. Statistics say that about half of the people who use home equity to consolidate their debts end up right back where they were before they did the loan consolidation. They max their credit cards out again and have a home equity loan on top of it. You are probably better off just keeping your debts the way they are and paying them off as quickly as you can. Don't borrow from family or friends. Friends, family, and funds should never be mixed. You might be able to pay off a bill, but you will probably end up losing a friend or causing resentment in your family. Even if they offer, my advice is to say no. You made the mess; it's up to you to fix it. In the long run you will be glad you did it alone. Bankruptcy is rarely your best option and it should never be your first option. I just watched a television commercial with a smiling bankruptcy attorney saying, "If you have too many bills and not enough money to go around, bankruptcy is your answer." I can tell you, that is an out-and-out lie. Bankruptcy is an answer. It might even be the answer. But it should not be your first answer. Advertisements like that sucker people in because they offer an easy way out. People always want an easy way out. Let me tell you from firsthand experience that bankruptcy is not an easy way out. Bankruptcy may appear to be a quick fix, but it is actually rarely any kind of fix. In fact, I saw one study stating that as many as half the people who declare bankruptcy do so more than once, proving that bankruptcy didn't really solve anything for them. Their habits didn't change and they ended up in the same mess again. Bankruptcy doesn't alter personal behavior. Until you start to act differently by spending less, earning more, and saving, you are doomed to repeat the behavior that created the problem. I know that people in horrible financial situations can become desperate. I know that bankruptcy can seem like your only option. I am aware that our society is full of people who are nothing but a bankruptcy looking for a place to happen. But do anything you can to avoid filing for bankruptcy. "But, Larry, you did it." Believe me, no one will ever let me forget that I did it. It's been nearly twenty years, and every time I want to buy a house or do anything on credit, they are quick to remind me. You will be told that a bankruptcy will eventually go away. Officially, at some point it won't count. But unofficially it will bite you in the ass for the rest of your life. My personal bankruptcy was the result of a business bankruptcy. I was the president and minority stockholder of a small business. I willingly signed my name on the bank loans and tax forms, making personal guarantees for money the company could not pay back. The company went bankrupt for many reasons, not the least of which was my own stupidity. I made many of the mistakes and I'll take responsibility for them and accept the consequences. I went down shortly after the company went down. But at least when I went down, it wasn't because I couldn't stop shopping at the mall! If you can avoid this last-ditch solution by reducing expenses and earning more money, you owe it to yourself to do so. In the next chapter, I'll show you how small changes add up to more money than you think. ## CHAPTER FIVE ## HOW TO CUT YOUR EXPENSES AND INCREASE YOUR INCOME The only way to get more is to give more. While it may sound strange, that is how it works. You give and then you get. But first you give. Then you get. Not the other way around. Lots of employees go to their bosses and say, "If you give me more money, then I'll give you more work." What their bosses should be saying is, "If you will give me more work, then I'll give you more money." This principle works in every area of life. You can't get more time to spend with your family until you give up the time you are spending doing something else. You can't get healthier until you give up what is making you unhealthy. And you can't get ahead until you are willing to give up the things that are keeping you broke. WHAT ARE YOU WILLING TO GIVE UP? Are you willing to give up some of your television time? Family time? Sleep? Clothes? Eating out? Shopping? Your car? Golf? Friends? Tell me exactly what you think you could give up to either work more or learn more—anything absolutely nonessential. EVERYTHING COUNTS. Don't think something is too insignificant to make a difference. Everything in your life either moves you closer or farther away from where you want to be. Nothing is neutral. No conversation, decision, or action. Every book, magazine, and television show moves you closer to or farther from your goal. Every friend you have moves you closer to your goals or farther away from your goals. Let's look at the things you should give up to move you closer to your goal of getting ahead financially. Give up cable television. Cable television rates typically run around $100 per month. Twelve hundred bucks a year would go a long way toward reducing your debt, wouldn't it? Disconnect. You can do it! I know, I know; how will you ever survive without HBO? You will. I told a guy on Big Spender that he had to give up cable television and he went ballistic on me. He said that was the step too far. I guess he thought working was too much to ask, too, because he didn't have a job. He had cable television but he didn't have a job. He got mad and screamed at me, "I heard you were once broke. What did you do?" I told him I sold blood to make my house payment and all I was doing was asking him to give up cable, so he needed to shut the hell up. He did. Get some rabbit ears and watch whatever you can get. Or give up television altogether. A woman on Big Spender was so upset her television was gone that she screamed and cried about it. After a month of doing without it, she told me she didn't even want it back. She and her family were reading together and playing games and going for walks and having conversations. Their family was closer because the television was gone. Get a cheaper car. I worked with a man whose net take-home was $1,800 per month. His car payment was over $900 per month. He actually thought that was pretty good; just a month before, his car payment had been $1,200, and his fiancée talked him into getting a slightly cheaper car. My suggestion to him was to do whatever it took to get a $200-per-month car payment. I knew he was upside down in his car loan, and I didn't really care if he had to drive his $200-per-month car for the next fifteen years...he needed the cash flow to pay his other bills. I don't care who you are—to spend 50 percent of your income on a car is stupid. It took visiting nine dealerships before he could find someone who was able to help him. He ended up financing the cheaper car and the leftovers of the too-expensive-for-him car he had traded in. And he increased the length of time he had to make payments. Some might say that was a stupid move. I disagree. It gave him back $500 a month that he desperately needed. He was then able to pay off credit cards that had a 30 percent interest rate. He was able to play catch-up with the rest of his obligations. Suck it up and trade in that expensive car you don't have the money to pay for, and get something that fits your budget. You are not your car. Get past the whole status symbol stupidity and realize that when you are in trouble, you don't need a status symbol; you need transportation. Move. I know this is a big step, but it is sometimes necessary. Lenders have been way too eager to loan people money to buy houses, and now those people can't afford their houses any longer. People have taken out interest-only loans and now their principal is about to kick in and they simply don't have the money. If that describes you, sell the house and move. Chances are you couldn't afford the house when you bought it; if you took out an interest-only loan, that was a clue! So cut your losses, learn your lesson, and move on. Or maybe you took out an adjustable-rate mortgage (ARM) that is now about to adjust, and you know there is no way you can make your new, higher payment. You don't want your house to be foreclosed, so sell while you still have a chance. You might not make much (if any) money if the market is depressed. You might even lose some money. Too bad. Sit down with a real estate professional and talk to your mortgage company and figure out the best step for you to take. By the way, when I say real estate professional, I mean someone who does more than list houses and complete the paperwork. I am talking about someone who has been in the market a while and has friends in the lending industry who can work with you to get you out of your mess. If you rent, don't even think about this one; just find a cheaper place to live. Then move. Hard? Yes. Inconvenient? Of course. Necessary? Without a doubt. Give up your high-speed Internet connection. Sorry. If you are scraping by and barely paying your bills, it's back to dial-up for you. And please don't tell me that you need it. Unless you make your living on the Internet, you don't need it. It is not a necessity. You just enjoy it. You get a kick out of it. It's entertaining. So is a book. Enjoy the Internet at a slower speed until you can easily pay for it. Get rid of your home phone. I know I just told you to rely on dial-up for your Internet connection, but you may be in such dire straits that even this is a bad idea. Keep your cell phone and dump your home phone. Get a new cell phone plan. Cut back on your minutes. Do whatever it takes to make your monthly expense lower. You don't need to download music videos on your phone. You don't need to answer e-mail on your phone. You only need to make necessary phone calls—especially those long-distance calls that you may currently be making on your home phone line at an extra cost. Your first necessary phone call is to your cell phone provider to cut back on your plan. Cut your insurance expense. Call your agent. Raise the deductible. Change your coverage. Do what it takes to lower your payment. This is for homeowners, auto, and health insurance. Change them all—keep your coverage, but do what you can to lower the costs. Stop eating out. I have already covered this one, but I want to say it again. It seems that one of the major reasons people don't have enough money to pay their bills is because they eat out too much. Why is there never enough money to pay the rent or make the car payment but always enough for a Big Mac? Don't tell me it is for the sake of convenience. Fast-food restaurants are rarely fast and it is never convenient to wait in line just to buy fake food that is going to shorten your life. Stop going out. You don't have the money to meet your buddies for a happy-hour drink after work. So don't. You don't have the money to meet your friends for golf or for lunch. You don't have the extra money to go to the movies. You don't even have the money to rent a movie. So don't do these things. You don't have the money for a lottery ticket. Chances are pretty good you aren't going to win anyway. You don't have the money for any nonessential spending right now. Someday you will, but for now you don't. It's time to pay the piper for your past mistakes. (By the way, piper is code for MasterCard, Visa, American Express, and Discover Card.) Give up the salon. Learn to color your own hair and do your own nails. It may not look as good, but you need that money for other things. And forget tanning salons and spas completely. That's an unnecessary expense. There have been some women on my TV show who flat out refused this suggestion. That's fine. Don't do it and keep living on money you don't have or that you owe someone else. Which would make you feel better, a manicure or a payment on your debts? Until you can answer, "Paying a debt," you aren't ready to get ahead. Drop the gym membership. You aren't using it anyway, so save the money. There is plenty you can do to stay healthy at home without going to the gym. I believe in gyms. I believe in getting healthy and staying healthy, but it's a luxury you can live without while you are playing catch-up with your money. Walk. Run. Lift your kids. Go to the park with your kids. Get mad at me over this one all you want. But it is rare that a truly physically fit person who really uses a gym membership gets ticked off over this advice. It's always the fat folks who get mad about giving up their membership, even though they haven't waddled through the door of their gym in months. Give it up, go for a walk, and use the money to pay off your debts. "But I have a contract." I hear that a lot. Talk to the gym manager. Explain your situation. Don't worry about embarrassing yourself; for all you know, the manager may be in the same shape you are. Just tell him that you can't pay for the membership any longer and you need a way out of it. Work something out. Stop smoking. At $4 per pack, a one-pack-a-day habit is $1,460 per year. If you live long enough to smoke for forty years, that is $58,400. If you made a yearly contribution of $1,460 to a tax-deferred savings account such as an IRA or 401(k), with a projected interest rate of 8 percent compounded annually, you could have over $400,000 for retirement or your children's future or to enjoy in your old age. Here is the question, Smoker. Is it worth it? What is more important: your kid's financial future or your cigarette? On top of the stupidity of the expense, you are killing yourself. Quit and spend the money on your financial security, not on dying early. WHAT WILL YOU DO WITH YOUR TIME? MAKE A PLAN! Now that you know some things you should give up and even have a list of things you are willing to give up, you have to have something there to replace those items. If you don't have things ready to fill in the holes you have just created, you might fill them in with more things that do you little or no good. Have your stack of self-improvement books ready to go so when you turn the television off, you will be ready to replace your television time with some reading time. If you are going to give up eating out, you'd better have some groceries ready to go that you can prepare. If you give up going to the mall, what will you do instead? Go to the library? Exercise? What? Remember the law of physics that says nature abhors a vacuum. If you create a space in your life, something will show up to fill it in. You are in charge of what fills in the space you have created. "But, Larry, this is all such a sacrifice!" Okay, then don't do it. Don't sacrifice your lifestyle and just keep living the way you are right now. It's up to you. * * * In order to have what you have never had and get something you have never gotten, you have to do something you have never done. * * * HOW TO MAKE MONEY. * * * You can't make money. You can only earn money. * * * Never again say, "I need to make more money." You aren't the Treasury Department and you don't get to print it up when you need it. You have to earn it. That's always where the money comes from. Instead say, "I need to earn more money." Earn more money. Remember I told you there were only two ways to get ahead: reduce expenses or increase income. So far, I've only talked about reducing expenses, but now it's time to address increasing income. This probably means getting a second job. Sometimes it takes one job to get by and another job to get ahead. "What? A second job? Don't you want me to have a life?" Actually, that is exactly what I want for you. I want you to have a life where you aren't living paycheck to paycheck. A future that isn't full of worries and concerns over how to pay your bills. A real life. The life you want. And if it means you have to get a second job to make that happen, then suck it up. When I was broke and struggling I tied macramé, trimmed trees, painted houses, swept floors, and even sold blood. You do what it takes when you have to. I'm not above doing what it takes. Even as a rich guy, I always look for ways to make extra money. Just in the last few years I have flipped houses and owned a mobile cigar company. I'm always amazed at capable men and women who are unemployed and yet won't take a job sacking groceries because it is beneath them. If I have bills to pay and groceries to buy and kids to clothe, then nothing is beneath me. No honest job is below my level. Recently I was sitting with my wife at a great outdoor restaurant in San Diego's Gaslamp Quarter when a guy came by and started digging in the trash can. A lot of things jumped into my mind: He's homeless and looking for something to eat, he's looking for a cigarette or a half-full can of beer, his predicament is sad, it's his own fault—all of that and more ran through my mind in one second as I watched him scour through the trash can. Then I saw that he was actually pulling out plastic soda bottles and aluminum cans and sticking them in a couple of big bags he had. After a few seconds he ran to the next trash can...yep, he ran. He was digging out stuff that could be recycled and he was moving as fast as he could to get as much as he could—probably so he could make it to the place where he'd cash it all in before they closed. This guy had a job. It probably wasn't the job he had always wanted, or even wanted now, but it was what was available to him and he was doing it. He was working. I admired this guy. He wasn't begging or griping (at least not to me); he was hustling along the sidewalk doing what he could that day to make a buck. Could he do more? Probably. Couldn't we all? Absolutely. I have no idea what this guy's story was. He could have been homeless and this was how he got money to eat. This could also have been a second job or a third job. What matters is that here was a guy who was willing to do something most people wouldn't do. Are you? Are you willing to take on an extra job to pay off your bills earlier? If you aren't willing to do whatever it takes to get ahead, then you don't deserve to get ahead. Most people don't want to earn more money...they just want to have more. I guess the Money Fairy is supposed to slip into your bank account at night and deposit money. Even the Tooth Fairy expects you to leave a tooth behind in exchange for the money. You give up the tooth; the Tooth Fairy gives up a little coinage. That is how the Money Fairy works too: You give up a little work and the Money Fairy shows up with a little money. Everyone can do something. Everyone has a skill that can be marketed. Everyone can do more than they are doing. You might not like it, but it can still be done. While there is never a shortage of ways to earn money, there is a shortage of willingness to do whatever it takes to earn money. * * * Life is not made up of the haves and the have-nots—but instead of the wills and the will-nots. * * * By the way...and this is a BIG by the way: Earning more is not a license to spend more. It does no good to go out and make an extra $500 a month if you are going to spend an extra $600 a month. I worked with a woman who got a second job to pay for her shopping habit. But her habit was to spend more than she earned and her habit didn't change. So the second job only allowed her to overspend at a higher income level. The extra income you earn goes toward reducing your debts so you can save and give and live without the stress and worry that comes from overspending. Sometimes, though, an extra job may not be enough. Sell stuff. If you are in desperate need of cash to pay your obligations, then sell your stuff. When I filed for bankruptcy and was in serious financial trouble, I sold everything. My wife and I agreed that we wouldn't sell our wedding rings—but everything else was fair game. I even sold our sofa and living room chairs. We sat on the floor. I hated it. It was humiliating. But I did it. I had to. I needed the cash to pay my commitments. My commitments meant more to me than my stuff. Begin by selling your toys. It's not playtime any longer—it's time to save your ass. Get rid of the boat, the motorcycle, the RV, the four-wheelers, the gym equipment I bet you don't use anyway, the fishing equipment, the hunting equipment, the golf clubs, the Jet Skis, and the bicycles. "But, Larry, those are my hobbies. I love that stuff." Too bad. Bye-bye. You can buy new stuff once your bills are paid off and you're in a better place financially. Next, go to your closet. Go to the bad end of your closet. (Guys, you didn't even know you had a bad end in your closet, did you? This is the stuff you don't wear, can't wear, and wouldn't wear on a bet.) Pull everything out and get all of it ready for a yard sale or the consignment shop. Then take a good look at your furniture. Do you really need that chair? Be tough on yourself...you have bills to pay! Think garage sale, yard sale, consignment shops, pawnshops, eBay, and craigslist.com. These are just places to start. Post your stuff on bulletin boards at work. Get creative and get selling! I know it is hard to get rid of the things you have. You like your stuff. We all do. But this is a time to like getting out of debt more than you like the things you own. It's just stuff! Stop being so attached—it's unhealthy. Especially if you're holding on to it as a symbol of prosperity that doesn't reflect the reality of your situation. MY PERSONAL SYMBOL OF PROSPERITY. When I started making some real money, I wanted to reward myself. I had worked my ass off to get rich, so I decided to buy a gorgeous little Porsche Carrera convertible. Did I need it? Nope. But rewards are rarely about need; they are almost always about want. I wanted it, so I bought it. Holy crap, it was a hot little car. Did I have any problem buying it? Not at all. I could afford it. If you find yourself in the same position, I suggest you do the same thing. It was a symbol of my prosperity. When you do well, you want a reward and I think you should have it. Here is the problem with a Porsche: It's not the most practical car in the world. Not that you buy it to be practical, you buy it because you can and because it says PORSCHE on the back end. Golf clubs, bulldogs, groceries, and suitcases don't fit in a Porsche very well. Neither does anything else except the driver and a small friend. While I loved my Porsche and enjoyed driving it, I bought other cars—three other cars. So my wife and I had a total of four cars for the two of us to drive. And I travel most of the time. My symbol of prosperity had officially become a symbol of excess. A little excess isn't necessarily a bad thing if you can afford it—and I could. I just liked knowing I could afford to own an amazing car whether I ever drove it or not. Does that make sense? Sure it does...for a while. Then I stopped driving it almost completely. In fact, in two years I drove it fewer than seven hundred miles. I'll do the calculation for you: That's less than thirty miles per month! A set of tires rotted on it while it sat in my garage. I had to keep it plugged in all the time just so it would start, because the battery kept dying due to lack of use. My wife tried to get me to sell it. I refused. But one day, after replacing the tires and the battery and having to walk around it every day to get to my three other cars, I realized that my symbol of prosperity had gone beyond my symbol of excess to become a symbol of my stupidity. So I sold it. I had nothing to prove to myself or to anyone else any longer. I didn't need a reminder that I was doing well. Now I drive a pickup truck and don't give a damn what anyone thinks about it. See? Still a redneck at heart! One time there was a woman on my show who had nearly $20,000 worth of shoes. She loved her shoes. But based on her income and her other bills, she simply couldn't afford to support that kind of shoe habit. I told her she needed to sell most of her shoes to pay her bills. She flatly refused. Her brother offered to pay her the full retail amount of her shoes so she could pay off her debts. Again, she refused. Her shoes made the move from symbols of prosperity and excess to symbols of stupidity. Another woman on the show had over two hundred DVDs—many unopened. She just liked having them. I told her to sell them to pay her bills, which were in collection! She sold fifteen. She thought the others were "collectors' items." DVDs are never collectors' items. (By the way, I have noticed from working with people who have real money issues that most have huge DVD collections. So if you see yourself getting too many, you might want to stop and think about it!) Are you really much different from these two women or me? Don't you have things that have made the transition from a symbol of prosperity to a symbol of excess to a symbol of stupidity? I had a Porsche. For one lady it was shoes. For another it was DVDs. What is it with you? Write it down: * * * * * * * * * * * * * * * Now make a list of all the other stuff you can sell. When you finish the list, do a walk through the house and make your list longer. Reality check: I know you will probably only get about 10 cents on the dollar for the stuff. You will find yourself saying things like, "I paid $400 for this and now I can only get $40." That's how it works. Sorry. The point is that you need that $40 to pay a bill. You also need a fresh, clean start. Get rid of the stuff that is weighing you down. Unclutter your life by ridding yourself of useless items. In doing so, you will make space for new habits and ways of thinking that will get you ahead. ## CHAPTER SIX ## THE STUFF MOST PEOPLE OVERLOOK I probably haven't surprised you with any- thing I've suggested up to this point. This stuff is mostly just common sense. And if you watch television, and I would lay odds you watch a lot of it, then you may have heard most of the ideas I have offered up to this point many times. You just haven't acted on them. This chapter will probably have some stuff you haven't heard before—stuff that may surprise you or even seem trivial and insignificant. Yet it is this stuff that can make the difference between getting by and getting ahead. Read on for changes you can make that will have a tremendous impact on your financial future. If you do these things, I guarantee you will get ahead! CHANGE CHECKING ACCOUNTS. Many banks have checking accounts that round up the amount of the check you write and put the odd cents in a savings account. If you write a check for $18.37, then 63 cents will go into a savings account. You will be amazed how quickly this adds up. TAXES. PAY THEM. Like everyone, I gripe a bit when it comes to paying my taxes. But when I find myself whining about taxes, I remember a time when I didn't have to pay taxes. Can you imagine that? No taxes. I definitely don't want a year like that ever again. Know why? I didn't make any money! I just try to remind myself that I enjoy the things my taxes pay for. I like roads to drive on and police and fire protection. I'm not wild about all the things my taxes pay for. But there are times when you take the bad along with the good, and paying taxes is one of those times. GET A GOOD BANKER. Know your banker by name. Make sure your banker knows you by name. Go into your local branch and meet someone. Explain who you are and what you would like to do. It will be hard. I still have a problem with this one because people at banks come and go, and for the most part don't care about you or your money. Keep asking until you find someone who does. Remember, they need your business. Even if you are a bad customer, they make money on your bounced-check charges. PICK UP THE PENNY. A penny is interest on one dollar for one month. Pick it up and put it in your pocket. I pick up at least one every day. I have a big jar that I fill up every year with change I have picked up off the street. Picking up the penny is a reminder to me that money is important. It is also proof that money is always flowing into your life; you just have to pay attention and be willing to pick it up. I watch people walk right past pennies on the street. Maybe they don't see them. I see them all. I have trained myself to spot money wherever it presents itself. I even have a little mantra that I have said for the past twenty years: "Money comes to me from all directions." It does. It does for you, too. You just haven't trained yourself to recognize that, and you might not be willing to take the steps to take advantage of the situation. Or maybe you think the amount is too insignificant. No amount of money is insignificant. It adds up—even a penny at a time. I know that picking up a penny won't make me rich. But after picking it up, I will have more money than I had before I picked it up, and that is the overall direction I want to be moving in at all times. When I was a little boy, my dad once asked me, "If I hired you to go to work for me and I agreed to double your salary every day you worked for me, but the first day your salary would only be a penny—day two it would be two pennies, day three only four pennies, and so on—would you take the job?" As a small child I said, "No! No way I would work for so little! I'm worth more than a few pennies." Then my dad explained to me how quickly I would be rich if I agreed to take the job. He got a sheet of paper and told me to figure it out. I did. This is what I came up with: The amazing thing to me as a child and even now is the speed at which money multiplies. So while it won't happen quite this fast in real life, remember that even a meager start in saving and paying your way out of debt will build very quickly. (In the meantime, if someone makes you this offer, take it!) CARRY CASH. The best thing about cash is that when it is gone, it's gone. The worst thing about cash is that when it's gone, it's gone! With a credit card you can slide right past your limit. Even with a debit card, your bank will probably allow you to slide right past zero and then charge you a hefty amount for doing it. Not so with cash. This is what you should do. Is your budget $200 a month for groceries? Then get an envelope and write GROCERIES on it. When you get paid, cash your check and put $200 cash in the envelope. When you go to the grocery store, you use this envelope and only this envelope to pay for your groceries. When the $200 is gone, you stop buying groceries and you stop eating. Repeat this process with every cash item on your budget. Envelopes full of cash are the way to go until you get a handle on your spending. SAVE YOUR CHANGE. When I buy something and pay cash, I never use change. I always break a dollar and get the change back. When I get home, I dump that change in a one-gallon milk bottle that I keep in my closet. A one-gallon jar holds about $400 worth of change. Usually I use it to buy something cool that I want. In the old days of less money, I would pay a bill with it. Try my suggestion. Just break a dollar bill to pay for things and save the change. You won't miss it and when your jar is full, you will be able to do something significant. SHOP WITH A LIST AND A BUDGET. Most purchases are unplanned and not budgeted for. This has to stop. Make a list of what you need and how much you have to spend on it. Stick to the list. Don't vary from the list for any reason. When you get to the checkout, if you pull something out of your basket that wasn't on the list, tell the cashier to set it aside because you have changed your mind. This isn't a game—this is war. Have the discipline to win the war by sticking to your list and your budget. (More on making that budget in Chapter 7!) BUILD A CUSHION. SAVE! Save for an emergency. Some financial advisors say you should have six months' worth of living expenses in your savings account. That won't happen for most people. I say shoot for one month's worth of living expenses as a bare minimum. Put it away and don't touch it for any reason. By the way, a credit card is not your first source of emergency funds. Cash is the first source. Just because you have a "clean" credit card, it doesn't mean you are ready for an emergency. And don't think you are emergency immune. You aren't. People get laid off. Companies go out of business. Medical emergencies happen. Elderly parents get sick and you have to step in to take care of them. Bad stuff does happen to good people. I understand that. Be prepared. I filmed a television show with a couple who had no money, no jobs, lots of bills, and no plan for things to get better. They were resistant to every suggestion I made, yet they agreed to follow my plan for thirty days. Part of my plan was to stash just $200 away as an emergency fund. Begrudgingly, they did it. They would rather have spent it on fun stuff but they did as I asked. Before I could go back to do my follow-up with them to see how their month had gone, his father had a heart attack and had to be hospitalized. Luckily, he had the money—that $200 emergency fund—to fly back and see his father. This guy didn't much like me or my ideas for his money...until then. When we wrapped the show, his tearful confession was that without that $200 he would not have been able to see his father. I originally had no hope for this couple and their future—yet that event turned them around and they are now doing great. Don't wait for an emergency to happen to find out you need an emergency fund. Prepare now. Open a savings account just for this purpose and stash a few bucks in it at every opportunity. This is not a vacation fund or fun fund. This money is to be used when it hits the fan and you need help. FORGET COUPONS. I know this is blasphemy to a lot of people. However, using coupons is not always about being frugal. Sometimes it is about being cheap. The amount of time it took you to scour the paper for coupons could have been spent getting smarter or earning more money. When I want something and it happens to be offered at a discount, or I happen upon a coupon that allows me to buy exactly what I want cheaper, then I take advantage of the coupon or the discount. Not to get what you want at a lower price when you can is stupid. However, this is not what I am talking about. I am talking about people who alter what they want based on the discount or the coupon. I know people who decide where they want to eat based on their stack of coupons. You want Chinese food for dinner, but you have a coupon for pizza so you wind up eating pizza just because of the coupon. If you do this, you are being cheap. You are compromising your desires and settling for less than you deserve. You are letting discounts determine your life and have allowed yourself to become the victim of a stupid coupon. Get in control. Live your life the way you want to live it. Don't have the money to do that? Remind yourself that your condition is your own damn fault and then commit and constantly recommit yourself to having the money to live any way you want to live. DON'T BUY IN BULK. I love Sam's and Costco. I love walking the aisles and am constantly amazed at the bargains you can get there. You really can save money at the warehouse clubs. But be careful! Things that look like a bargain, while being cheaper than you would normally pay, don't always end up being a bargain. Because things are so much cheaper per item, people tend to buy more than they need and end up spending more than they have to. I don't care if it is the buy of the century, no one needs a four-pack of 64-ounce bottles of ketchup. Unless it is something that can be consumed quickly, completely, and constantly, like toilet paper, then you are paying too much when you buy bulk quantities. READ. How many self-help books, business books, or biographies have you read in the last year? Okay, let's widen the search even more. How many books of any kind have you read in the last year? It is an easy question that doesn't require a story or any excuses—it just requires a number. So what is the number? Take the next step. Write down the names of the self-help books, business books, or biographies you have read in the past twelve months. * * * MY LIST OF BOOKS: You're Broke Because You Want to Be * * * Nothing on your list? Then you aren't serious about improving your life. You aren't taking action on becoming more prosperous. You have to study in order to achieve what you want. Your situation, especially your financial situation, will improve right after you improve. Interesting factoid: A study by the U.S. government found that 46–51 percent of U.S. adults read and write so poorly that they earn significantly below poverty level wages. * * * Everything in life gets better when you get better, and nothing in life gets better until you get better. * * * "But there isn't enough time to read!!!" Sure there is. The average welfare recipient has the same amount of time every day as the average billionaire. It's not how much time you have; it's how you choose to spend the time. I've read nearly four thousand books in the past twenty years. I read them when I was broke and I read them now that I'm rich. But especially when I was broke. I was searching to find out from every source possible how to live a better life. If your life isn't what you want it to be in any area, then you should be doing the same thing. When something is important to you, you find the time. The good news is that you are now reading a book. But this is only one book. I'll admit that it is a great book, but you can't stop after one great book. You need to search for more great books. Read some great books about the philosophy of wealth. Here are a few I especially like: Think and Grow Rich, by Napoleon Hill Manifest Your Destiny, by Dr. Wayne W. Dyer Creating Affluence, by Deepak Chopra You Were Born Rich, by Bob Proctor Why You're Dumb, Sick & Broke...and How to Get Smart, Healthy & Rich!, by Randy Gage After you've read about the philosophy of being wealthy it's time to get some very practical advice about getting rich. I can help get you from broke to breaking even so you will have some money to start building wealth and getting rich, but the next step is up to you. To take it to the next level, try these books: Rich Dad, Poor Dad, by Robert T. Kiyosaki Start Late, Finish Rich, by David Bach Never Eat Alone, by Keith Ferrazzi The Millionaire Zone, by Jennifer Openshaw Go Put Your Strengths to Work, by Marcus Buckingham And for overall success in life and business, definitely read anything by Larry Winget, especially It's Called Work for a Reason! Your Success Is Your Own Damn Fault and Shut Up, Stop Whining & Get a Life Reading increases your worth—ultimately your net worth—but also your worth to others. The more you know, the more you are worth. The more you are worth, the more you will earn. As success philosopher Jim Rohn says, "If you knew better, you would do better." CHANGE YOUR LANGUAGE. If you constantly think like you are broke, talk like you are broke, and do the things a broke person does, then you will be broke. This is the type of language I want you to change: "I can't afford..." If you say that you can't afford something, you will never be able to afford it. Saying "I can't afford" makes you a victim. The price of things does not dictate whether you can have them or not. That isn't the case and we both know it. You are in control. So talk like you are in control. Instead say, "I don't choose to spend the money I have right now on that." Even if you don't have the money! This statement is a reminder that spending is a choice. Your entire life is about choices. You control the choices you make. That is a position of power, not victimhood. Speaking of having control over your choices... LOSE WEIGHT AND CLEAN UP YOUR HOUSE. If your spending is out of control, then chances are very good that other parts of your life are out of control. Let me give you my observations. These are broad, sweeping statements, and there are exceptions—but I have found that... People who are out of control with their spending are usually out of control with their eating. People who spend big usually eat big. People who are out of control with their spending are usually out of control in their relationships. People who are out of control with their spending are usually out of control when it comes to keeping their houses and cars clean. A lack of personal discipline in one area nearly always shows up in other areas. Watch the shows on television about cleaning up and reorganizing a room in a house. The ones where a camera crew goes into a room they can't even walk through. Sometimes there is stuff that is stacked waist deep in a bedroom with only a small trail to a bed that is covered in crap. I guarantee you those people have money problems. And sorry, but many of them are also overweight. I can walk through your house and tell you what your checkbook looks like. Do it yourself right now. Take a quick look around your house. Is it tidy? Clean? Are your closets and drawers organized? Are the dishes clean and put away? If so, it is likely that you have a neat, tidy system for keeping track of your money. Or do you have piles of dirty clothes on the floor? Are all of your drawers junk drawers? Is the garage a disaster? If this is the case, I am guessing you have no idea how much money you have or who you owe. When you get control over one area of your life, then the other areas start to come together. Get everything going for you that you can by fixing the things you control in each area of your life. EAT LESS. One of the best ways to lose weight and save some money would be to simply eat less. I worked with a couple who spent $20,000 a year eating out and still spent $18,000 a year on groceries. Two people! That $38,000 was equivalent to one of their salaries. Of course I cut all eating-out from their budget, but I also decreased the amount they were spending on groceries. It was just too much. When making a budget, I always leave people $50 per person per week in grocery money. Any person can have plenty to eat on that much money. I'm talking about a healthy diet. People who argue that it can't be done are not eating sensibly. They are buying cookies and prepared foods that cost a lot and eat up their food budget. I took one woman to the grocery store to watch her shop the way she normally did for her husband and four-year-old son. She bought prepared meals (we used to call them TV dinners) for almost every meal. She bought bags of cookies and sugar-laden cereals, soda, candy, and chips. Her basket was full and yet she didn't have any real food in it. She even bought prepared mashed potatoes. What? I asked her if she couldn't boil her own potatoes and mash them herself, and she told me she wasn't Betty Crocker. Imagine her displeasure when I made her put it all back and shop with only the one hundred dollar bill I gave her. I walked her through the store, buying meat, chicken, fish, vegetables, whole-grain breads and cereal, and lots of fruit. I helped her fill her basket with real food that would last for more than a week and when we went to the checkout line, she still had money left over. Yes, she and her husband would have to cook it. No, it wouldn't keep for weeks. Yes, it was less food than they were used to eating. But that was a good thing. They were both overweight, so they were actually doing both their budget and their waistlines a huge favor. Take a hard look at your food budget. I know you probably don't have a food budget, but you are going to have one from now on. How much do you spend on food every week? Decide to spend less. Use my $50-per-person-per-week plan. Buy healthier food, which costs less. Prepare it yourself, which costs nothing. The meals will be good for you, good for your family, and you might even enjoy doing it. Besides, if you are an average person in today's society you could easily afford to lose a few pounds. TAKE A TOUGH LOOK AT YOUR FRIENDS. In Randy Gage's book Why You're Dumb, Sick & Broke...and How to Get Smart, Healthy & Rich, he quotes one of our shared heroes, Jim Rohn, in saying that your income will be the average earnings of your five closest friends. I believe this to be true. That's why I try to surround myself with very rich people. Don't believe it? Let's try it right now. I want you to write down the names of your five closest friends and then write down how much money you figure they make and average it out. Don't pick up the phone and call them; you pretty much know how much money they make! Add them all together and divide by five. What's the average?__________ The formula works, doesn't it? What's the message? You may want to upgrade your friends. Does that mean you have to dump your old friends? That probably isn't a totally bad idea! But at least try to develop new friends who embody the traits you would like to see more of in your own life. Ask yourself these questions about your friends: What do you and your friends talk about? Do you make fun of rich people? Put other people down? Do you bitch and gripe and whine about work and how unfair life is? What books do your friends read? (If you answer this question with "Books?" that would be a clue.) What do your friends expect from you? What do your friends let you get by with? If the answers to these questions are not ones you are particularly proud of, then you face the tough decision of keeping friends who are keeping you from your goals or choosing new friends who move you closer to your goals. This is not easy, I know. But I can promise you, if it were a choice between my friends and the financial welfare of my family, I would dump my broke-ass friends in a heartbeat. BE GENEROUS IN TIPPING AND BILL SPLITTING. Want to know if someone is cheap? Have dinner with them and watch what happens when the bill comes. Anyone who starts saying things like, "But I only had water, so mine is two dollars less," is a cheap person. Divide the total bill by the number of people eating, pay up, and move on. Lousy tippers are killing their chances at ever being prosperous. If you are less than generous with others, others will be less than generous with you. GIVE AWAY SOME OF YOUR MONEY. I know, I know. I tell you to stop all spending except on the necessities, to focus on your debt, and to save all you can, and now I am telling you to just give away your money. Doesn't make sense, does it? You are so right. It doesn't make any sense...except it works. When you willingly share part of what you have earned with others, then it magically comes back to you. I don't know why it works, but I know it works. Proof that it works: After my business failure and bankruptcy, I was broke. I stopped giving money to charity because I didn't feel like I could afford to give any away. While most would think my actions justifiable, my parents had taught me that if you have anything, you should share it with those who have nothing. One day as I sat in my office, I had an absolutely overwhelming urge to write a check and give away some money. I felt like I needed to give away $100. While that isn't a lot of money, at the time it seemed like a huge amount—especially since it was $100 more than I had given in a very long time. Plus, it seemed that I had so many bills and other obligations, Christmas was coming soon and I had two little boys to buy presents for, and I needed to spend my money on other things. Regardless, I couldn't shake this need to give. So I followed my gut and immediately wrote out a check for $100 to one of my favorite charities, stuck it in an envelope, addressed it, and put a stamp on it. I became so afraid that I would back out on sending it that I got in my car and took it immediately to the post office and dropped it in the outgoing mail. I felt instant relief about doing it, although I had no idea how to tell my wife what I had done. She was the one trying to stretch our small amount of money to cover our large amount of bills every month, and a hundred dollars less in the account was not going to be easy to explain. That night at my home, my doorbell rang. It was my attorney. Since most attorneys don't make house calls, I wondered what in the world he could want that was so important he would come to my house at night. I invited him in. He told me that he had just had someone call him to forgive a huge debt that he owed in his business and he wanted to pass his good fortune along by forgiving some of his debtors. He then handed me a statement of my account and told me that it had been forgiven and to have a nice evening. As I looked, dumbfounded, at my bill, I noticed that the balance on my account had been $100. Some might say that is an interesting coincidence. And maybe that's all it is. But for both my wife and me, it was a lesson to never stop giving, no matter what your circumstances. It is just the right thing to do. I don't often quote preachers but coming from Tulsa, Oklahoma, makes you very familiar with Oral Roberts and his ministry. I don't care what anyone thinks of him; that isn't my point. Years ago I read something he said that forever changed the way I think about giving: "A rejected opportunity to give is a lost opportunity to receive." Will that happen if you give? No guarantees from me. I have no clue whether it will happen to you or not. I just know that the best way to begin any money venture, whether it is an investment or getting out of debt, is to give away some money. I personally believe in giving away 10 percent of your money, but not for the religious reasons some people use. So I don't use the word tithe. (In fact, I don't want you to ever think about or use the word tithe again. The word just has too much religion associated with it.) When I hear the word tithe I think of a pompadour-haired preacher on television, wearing a turquoise suit and telling me that God needs my money and that if I will send it to the preacher, he will make sure God gets it. Personally, I don't think God needs or even wants your money. I don't think God gives a hoot about your silly 10 percent. You shouldn't give because you think God wants you to or because other people need it, though other people certainly do need it. You should give because you have faith you will have more money coming in. You need to attest to the fact that you can learn to live on the remaining 90 percent. You need to trust yourself to the point that you know more money is on the way even though you are giving some of what you have to people who need it even more than you do. Money flows. Money comes to you and it goes from you. If you are unwilling to give your money away, you prove that you lack trust that money will ever come back to you. If your hand is gripped too tight to release what you have, then you won't be able to open up your hand to receive more. Again, I don't care how broke you are, you can still figure out how to give something away. Do it. Giving is also part of the obligation that comes from having money. Yes, I said obligation. When you have money, you are obligated to share a portion of it with those who don't have money. Not the broke people of the world who can get off their butts and work to earn their own money but the poor people of the world who have little chance to do any better. TUCK A BENJAMIN. A Benjamin is a one hundred dollar bill. I like 'em. I like 'em a lot. I try to collect as many of them as I can. I always keep one folded and tucked down in the dark recesses of my wallet. You should too. It will help you feel better about your situation. With a Benjamin in your pocket, you will think of yourself as a prosperous person. And you will never be broke. A prosperous person who isn't broke acts with confidence. Trust me, it will help. If you get caught in an emergency and are forced to use it, replace it as quickly as you can. Can't do a hundred? Start with a twenty. Then move up to a fifty. Then one hundred. The hundred is the magic bill. No matter how rich you may find yourself someday, the face of Benjamin Franklin smiling at you will always make your day a little brighter. BE THANKFUL FOR WHAT YOU HAVE. "I don't have very much, so what do I have to be thankful for?" You could have less, couldn't you? Sure you could. Remember that old saying "I felt sorry for the man who had no shoes, until I saw a man who had no feet." Things could be worse for you. Don't ever say anything stupid like, "Boy, things couldn't get any worse than this!" Believe me, if there is one thing I have learned about life, it is that things can always get worse! So even when things appear to be terrible for you, be thankful that they aren't worse. You have the talent and the ability to improve things. You can make things better. That alone is plenty to be thankful for. To remind yourself of all the good you have going for yourself in the midst of all the bad, I want you to make a list. Yes, another list! * * * "The more you are thankful for what you have, the more you will have to be thankful for." —Zig Ziglar * * * * * * "A grateful mind is a great mind, which eventually attracts to itself great things." —Plato's Laws * * * FAMILY FINANCIAL FAUX PAS I get hundreds of e-mails from people who are concerned about their family members who are in financial trouble. Some of these letters are desperate cries for help, clearly written out of both love for that person and the pain caused by watching them suffer. They tell me how they have tried everything to save their brother or daughter or other family member from financial ruin and yet nothing seems to work. Here is why nothing works: The family member in trouble doesn't want to change the situation. The sad truth is that you can't change it for him. You can't rescue someone who doesn't want to be rescued. People who need help rarely appreciate the help. Most won't even accept the help. You can only help people when they want to be helped. Has your family member asked for help? I mean, more than just asking to borrow money to get out of a bind. Has she asked for help in changing how she lives so she won't get in a bind again? If she hasn't asked for that kind of help, chances are she doesn't really want to change her life. She doesn't want to stop being broke. She just wants to be bailed out when she has gone the step too far. An additional problem in trying to rescue someone is that you perpetuate the idea in his mind that he is a victim. After all, you only rescue victims, right? You also confirm that same idea about him in your own mind, meaning that you will treat him like a victim. Stop treating others like victims. Instead, treat them like responsible individuals who have created their own messes and who have the ability to clean up their messes. You should help them clean up their messes if they want help and ask for help. But let them learn the value of self-respect by taking responsibility for their actions. Throw them the rope, but let them climb out of the hole on their own. Since most of the requests I receive are from parents who want to help their children, I know your role in teaching your kids about money is important. Kids and money. The only thing kids know about money is what you teach them. You set the example. Don't expect your kids to learn how to spend their money wisely if they have watched you piss yours away on stupid stuff. Your choices will become their choices. Every dime you spend shows them how to spend their money. Kids should earn their money. Give kids chores to do for pay. These should be special chores, not the chores that come with being a part of the family. As part of a family, they should automatically do things like help clear the table, empty the dishwasher (or even be the dishwasher), help with their own laundry, vacuum the house, carry out the trash, and pick up after themselves. This goes for both boys and girls. I don't agree with the notion of girl chores and boy chores. A boy can help in the kitchen and a girl can help in the garage. I am talking about chores that go above and beyond the normal stuff—maybe washing the car or mowing the lawn or cleaning out the gutters. It isn't my job to figure what the job is; it's your job. My point is that when kids earn their money, they learn to respect both the work and the money. "I want my kids to have better than I had." We all do. It's normal. But it can easily be overdone. You don't do your kids a favor by buying them everything they want or everything you didn't have. I have dealt with many parents who thought they were showing their kids love by buying them everything they could dream of. I have seen a closet full of hundreds of outfits for a one-year-old baby. Clothes with the tags still on that she would never get to wear because she would outgrow them too fast. I have been in houses where you couldn't walk through any room in the house because of the toys—toys that had never been played with and never would be. In every situation the parents had not put aside one penny for their children's education. When I attacked them for their ridiculous spending, they tried to convince me that they did it out of love for their children. I have dealt with parents who were about to have their houses foreclosed on and their cars repossessed, yet still had convinced themselves that buying hundreds of dollars worth of clothes and toys each month for their one-year-old was a good idea. They wanted to make sure she was happy. A one-year-old is happy when you hold her and hug her and feed her. You can give her a cardboard box to play with and she will be tickled pink. Parents who spend their money only on things that have no future value are not showing love for their kids. What they are really doing is showing how uncaring and irresponsible they are. They are playing fast and loose with their children's future. They are robbing their kids of their education. In my opinion, this is a form of child abuse. Tough language, I know, but to steal your child's future is a serious offense, in my book. Teach your kids about credit. Show them your credit card statements and explain what interest rates mean. Tell them how a house that costs $300,000 doesn't really cost $300,000 when you pay for it over the next thirty years. Advise them that they will be bombarded with credit card applications as soon as they reach eighteen years of age and teach them the pitfalls of credit card abuse. Don't let your kids be blindsided by the false promises of the good life that credit card companies advertise. When your kids get in financial trouble, help them. But not every time. Let your kids suffer the pain of their decisions. That's how they will learn to make better decisions. Let them worry and feel remorse for their overspending. Let them suffer the embarrassment of receiving a collections call. Let them do without and let them pay some late charges. It's good for them. Really. Lessons not learned will be repeated. However, sometimes there may be a legitimate reason to help your kids. When it comes to helping your kids with a money problem, you have to decide whether it is going to be a gift or whether you are making them a loan. Either way, make it clear which one it is. A gift is easier. That way you know going in that you aren't going to get repaid. If you just give them the money, they might spend it on something else and the bill won't get paid. After all, they are in trouble because they can't handle their money. When it's your money helping them out, take control of the situation and fix it. My suggestion is to take the bill out of their hands and pay it yourself. If you help your kids with a loan, it makes you a creditor. Make sure you are willing to be a creditor and act like a creditor to your kids before you make that loan. Being a creditor means setting up a repayment plan that must be enforced. You will have to make collection calls and you will be viewed as the bad guy. They will play the "But I'm your baby" card and you will feel guilty. You will make them mad and they will make you mad. Your relationship will be damaged, maybe forever, over money. A young woman on my TV show had borrowed money from both her father and her brother. Not a lot of money—only a few hundred dollars. She never paid them back. She was embarrassed. She became fearful of even making contact with them. She stopped all contact with them for years because she hadn't paid them a few hundred bucks. When I made her go meet with her father it was tough. He loved her and she loved him, but a wedge had been driven between them over a relatively small amount of money. How sad. Be careful loaning your kids money. Know up front that it probably isn't going to end well. Be prepared for that outcome. Then ask yourself whether it's worth it. It might be better to just give them the money. Before you help your kids, sit down with them and see if you can advise them on how to help themselves. Sometimes, that's when they learn the most. Bounce some checks—become a cop. My son Tyler is a police officer in Phoenix, Arizona. I am very proud of him. He is great at what he does. On top of all that, he loves being a cop. How did it happen? Money. Tyler, as a teenager, was a less than responsible human being. He played a bit too hard and didn't take anything very seriously. He had a job that he went to and worked pretty hard at. He was enrolled in a college that he didn't go to and didn't work very hard at. Instead he partied with his friends. And when he didn't have the cash to party, he wrote a check. The problem was that the money wasn't always there to cover his checks. One time he wrote an 85-cent check for a highway toll. The check bounced twice and ended up costing him over $80, which he also didn't have. After a couple of months of this I found out he had about $800 in bad checks and was in serious trouble. He came into my office and laid it all in front of me and said, "Dad, I have messed up." (Only his language was a bit more explicit.) After reviewing his predicament, I said, "Yes, you have." (Only my language was much more explicit.) He said he had decided that he needed to get his life in order and wanted to join the U.S. Army. At that point, we weren't in any kind of war and I thought it was an excellent idea for him. I told him I would bail him out of his $800 of stupidity if he would enlist. He agreed and off we went that very day to the army recruiter. Tyler flourished as a soldier. He went from the most undisciplined kid to the most disciplined man I have ever seen. After nearly eight years in the army, he wanted to get out and be a cop. Now he is. Why? You can say it was his destiny. Maybe. But I believe it was because of $800 in bounced checks. Yes, I helped him by paying the $800. But he recognized his irresponsibility and knew he needed discipline in his life. He came up with the plan to fix his life. That decision, which was based on a money problem, shaped the rest of his life in a very positive way. Cosigning. Again, be careful. I've done it with both of my boys and it worked out. But I was lucky. My boys might mess up and screw over their credit card companies, but they would never even consider screwing over their dad. That is more a reflection of our relationship, though, than it is the money or the cosigning arrangement. Your kids are not entitled to your money when you die. My goal is to spend every dime I have left on the last day I'm alive. Why not? I earned it, didn't I? "But, Larry, it's important to leave your children something." You are absolutely right. But it is not important to leave your kids money. It is important to leave your kids with the confidence they can earn their own money. It's important for your children to know that you loved them enough to make sure that you provided for their education. It's important that you demonstrated your own ability to live to the fullest of your potential. It's important to teach your kids how to earn money, spend money, invest money, and enjoy money. It is not important to leave your kids any money. SHOPAHOLICS AND ENABLERS. People shop for lots of reasons. They do it to feel better about themselves, to be somebody they really aren't, and out of a sense of entitlement. They do it to relieve stress, because they are happy, and because they are sad. Some people shop and spend simply out of habit. The issue I see the most is that people shop to escape. They can't face their real lives, and shopping brings them some temporary comfort from their lousy relationships, their self-esteem problems, and even their lack of money. I worked with a guy who told me he went shopping because it made him feel better about the fact he had money problems. Money problems that existed because he shopped too much! There are also people who are addicted to shopping. On Big Spender I meet lots of them—people who shop every single day. For anything. Life has no meaning unless they are spending money. Even a quarter. As long as the money leaves their hands and goes into the hands of someone else, then they think they are in good shape. A shopping addiction is just like an addiction to cocaine. And it is cured in the same way. You have to go cold turkey. One time I had a cop on the show who was in drug enforcement but also loved to shop. He couldn't seem to stop even after I had worked him over. He told me he thought a more gradual approach would work better for him. I asked him what his response would be if a crack addict told him the same thing. "I'm just going to gradually cut back until I don't do it any longer." He said that he would tell him, "Bullshit." Okay then, "Bullshit." You don't wean yourself off shopping. You just stop. I am not an expert on addictions. If you are truly a shopping addict, then you need professional help. Get some. Search the Internet or make some calls and find someone you can talk to about your addiction. Try: www.debtorsanonymous.org www.shopaholicsanonymous.org However, don't be so quick to think you have an addiction just because you like to shop. Some people who just don't have the personal discipline and self-control will play the addict/shopaholic card as an excuse for their inexcusable behavior. Regardless of the degree of your shopping problem, here are some things I have found to be helpful: Stay away from stores. If you were an alcoholic it wouldn't be a good idea to spend time hanging around bars, would it? And if you were an overeater, you'd avoid the all-you-can-eat buffets, wouldn't you? So if you have a shopping problem, stay out of the malls and places where you will be tempted to spend money! Stores are not the only place to avoid. Stay away from the television shopping channels and from eBay and other Internet shopping Web sites. Duh! I counseled a woman who was such a shopaholic that I didn't even want her going into the gas station to pay for her gas because she couldn't do it without buying a magazine, a Coke, or a candy bar. Stores of any type tempted her that much. In addition to getting some counseling, my suggestion was to remove as much temptation as possible. Get new habits. Many people spend out of habit. They buy takeout on Tuesday nights. They get a latte on their way to work. On Saturdays, they go to the mall. They check their e-mail and then hit eBay, even though they don't want anything or need anything. Don't fall into this trap. You especially need new habits if your situation has changed. You are used to shopping with your friends and going out to lunch or having a drink after work. But you got laid off or divorced or had a financial emergency, so your situation has changed and you can't do it any longer. Explain to your friends and replace that habit with a new one. Try the library. When I suggested the library to a woman, she responded with, "And what would I do there?" I laughed in her face. I suggested she might try finding a book to read. She said, "Yuk!" I asked, how about the park for a walk? She made an ugly face at me. She loved walking around the malls but couldn't find the energy to walk around the park. Overweight, not very smart, and unwilling to do a damn thing about it. I can't tell you what to do. Find something that doesn't cost any money that can occupy your time. Just don't go shopping! Shop with a list, a budget, and maybe even a chaperone! I've said it before and I'll say it again: Don't deviate from your list or your budget for any reason. If you can't be trusted to go to a store by yourself, go with someone who can keep you on track and remind you that you are at the store to buy essentials. Carry cash. I've already covered this one, but it is especially important for the shopaholic. If you have $25 in your shopping budget to buy a gift, then put that $25 in an envelope with BOB'S GIFT on it and only use that amount of money. It's easy to spend $40 when you have budgeted $25 if you use a credit or debit card. Envelopes with cash will keep you in check. A word to the shopaholic enablers out there: I could just as easily be the host of a television show called Big Enabler. Shoppers almost always seem to have an enabler: someone who either encourages them to spend money or won't say no to them when it comes to spending money. The enabler doesn't have the guts or the will-power to say no to the shopper. I worked with one couple in their first year of marriage. He handled the bills and couldn't tell his wife no because he felt she might think less of him as a man. He wanted her to have anything she wanted, and he'd lie awake nights trying to figure out how to pay for things. She was oblivious to the fact that they were one paycheck away from bankruptcy. When he finally fessed up to her about how he felt, she assured him that she loved him regardless. Then she felt bad for spending so much. You don't do your family or friends any favors by letting them ruin their lives when you can stop it. That's not love. Have your own little personal intervention and deal with the issue. The shopper might get mad, scream and yell, and tell you it isn't any of your business. But a friend should always come clean and tell another friend the real truth. And couples in a relationship should have complete, open communications about money. If you are the enabler to a shopper, then you can't be the chaperone when the shopper goes shopping. If you are the enabler, you shouldn't call the shopper to go to lunch. You shouldn't ask them to go to the movies. You must limit your contact to activities that don't cost any money. ## CHAPTER SEVEN ## NOW IT'S TIME FOR YOUR NEW BUDGET! In order to get ahead, you must have a written budget for spending money. In the past, you spent what you spent based on your whims and short-term desires, with little thought to whether you had the money or not. You spent and then figured out how to pay for it based on your juggling abilities. And you ended up broke. So obviously that wasn't a good plan. You have been living backward. You spend and hope your expenses match your income. It is time to stop living backward. You are going to begin your budget with your income rather than finish your budget with your income. * * * Stop living backward and begin to live forward. Begin with the end in mind. * * * Here is your goal: Live on what you earn. Period. No excuses. No one cares about your excuses and problems. We are dealing with numbers here and the numbers don't have emotion. They are just numbers that have to balance. These numbers are what you live by. In this book you have learned techniques for reducing your monthly expenses. You may have even taken the steps to do it. If you haven't, you should start immediately. You should have contacted your credit card companies and your insurance company. You should have disconnected your cable television and adjusted your cell phone plan already. You should have stopped eating out completely and cut back on groceries. You should have sold your toys and items you don't need in order to reduce your debt. Now you should be ready to create a budget. We begin with the end in mind: Monthly Income ________ This is ALL you have to work with. No more. This is it. It has to cover all of your expenses and leave you a bit to put in savings and a bit to give away. This total must not be more than your income. If it is, go back and adjust. Get ugly and make it fit. "But how??!!" I don't know and I don't care. You can't survive spending more than you make. Make it fit. Keep slashing your expenses until you figure it out. Or earn more money. But please don't be stupid and cut back on your savings in order to keep your cable television. When you have cut the numbers until they fit within your income, live on what you earn. That is what responsible adults do. Be one. "But I don't get to live very well based on this budget." I once told a woman that she might end up having to eat wish sandwiches every day. She said, "What's a wish sandwich?" I told her that's when you have two pieces of bread and you wish you had some meat to go between them. She didn't think I was funny. You'll be fine. This budget won't kill you. Will you die from doing this? No? Then don't worry about it. It's not forever. It's what you have to do until you stop being broke. In fact, this will do you a world of good. You will sleep better knowing that for the first time in a long time, you are living on what you earn. When you earn more money, you can live a little better. ADVICE FOR WHEN YOUR LIFE TURNS AROUND. Hire a professional. Once you have money, hire a professional to help you with it. Here is the key to finding a professional to help you with your money: Make sure they have a lot of money. Never pay someone to help you manage your money if they have less money than you do. Hire a really successful rich person to help you with your money. Ask them how much money they have and how they got it. If they won't tell you, move on until you find someone you can talk to who will come clean with you. You can't get a bargain when it comes to financial advice. Be willing to pay to get someone who is good at it. One of the ways you will know they are good at it is if they are rich! Enjoy your money. When you are making good money and your bills are under control, then enjoy yourself. Go to the best restaurants you can afford. Dress the way you want and wear the best watches and jewelry you can afford to wear. Take great vacations. Give huge amounts to charity. Get a massage or have a facial whenever you feel you want one. You didn't bust your butt to get rich only to live like you are barely getting by. That's dumb and an insult to your progress. Just don't abuse your wealth. Always make sure that you follow the guidelines of saving some of what you make and spending less than you make. ## PART THREE ## PROOF THAT IT CAN BE DONE! From Getting by to Getting Ahead to Getting Rich ## CHAPTER EIGHT ## INTERVIEWS WITH LARRY'S RICH BUDDIES Tired of what I have to say? Maybe you don't even believe me. Want a second opinion? That's fair. I called a few of my rich friends to ask them how they got that way and if they had any lessons they could share. You should do the same thing. Call a handful of your really rich friends and ask them how they got that way. Wait, you don't have any rich friends? If you were rich, you would! I chose these five people for one reason: None started out rich. They all came from humble beginnings, and now they are all millionaires. They've all been broke and desperate and figured out how to turn it around. I respect where they came from and how they got where they are. While each story is different, see if you can spot the similarities. JOE Professional speaker, author, entrepreneur, restaurateur, real estate investor Like me, Joe grew up poor yet is now one of the most successful business consultants and speakers in the country. Joe grew up on a little dairy and tobacco farm in Tennessee. He tells me that he was poor but he didn't really know it at the time. He wore clothes that were handed down from his big brothers. His mother bought groceries according to what was on sale that day. And his family never once took any kind of vacation. In the fifth grade he got interested in books and started reading James Bond books by Ian Fleming. He didn't care so much about the spy stuff. He was more interested in where the stories took place. He read about travel and living a high-class lifestyle in places like Nassau, New York City, Paris, and Monte Carlo. During high school, Joe would skip classes and drive to Nashville, about thirty miles from his home, just so he could drive through the richest neighborhood in the city—Belle Meade. He was a sixteen-year-old kid with nothing, from a little bitty country town, cutting class just so he could go look at big, expensive houses. But more than big houses and travel to exotic places, money represented freedom from worry to Joe. His parents had to worry about money every day of his life, and he didn't ever want to live like that. Joe went to a small college and got a degree in political science. He had a wide variety of jobs, including working on staff at the House of Representatives, booking bands in nightclubs, and eventually he became a real estate agent. He discovered he hated selling houses. However, one day he went to a real estate sales seminar and heard Tom Hopkins, one of the biggest names in real estate training and professional speaking at the time. As he watched Tom, he thought about what Tom did for a living: traveling around the country doing seminars and having a good time. He decided that was what he wanted to do someday. It took him two more years to make the move, but one day he quit his job and started knocking on doors, trying to sell himself as a speaker and trainer. When asked what he spoke about, he would just ask, "What do you want?" He knew if he could get a few hours to read a book or two on any subject, he could put together a seminar on it. A few took him up on it, but he was barely making a living. He was broke and hanging on by his fingernails. Like most new small business owners, he was so busy trying to live on the little money he did make, he didn't save anything for taxes. So at the end of the year he would find himself, as he puts it, "in the fetal position on the floor facing a tax bill that there was no way in hell I could pay." But somehow he stuck with it—and because he refused to give up, things finally started to come together for him. Joe told me that one of the biggest factors in his success story was that he decided to be better than the competition. The credo he lived by was "Know more than your competition; be quicker than your competition; and do more for the customer than your competition." When a company wanted a proposal for a consulting/speaking job, his competitors would send their proposal through the mail or, at most, via FedEx. Joe would scrape together his last two nickels, buy a plane ticket, and deliver his proposal in person. Because he went the extra mile, he usually got the job. Joe worked harder, studied more, and was obsessed with always getting better and out-hustling the other guy. At that point in Joe's career, a typical job would be to drive for twelve hours to speak to the employees of a school system in Mountain City, Tennessee. The speech would be in the high school gym to teachers, cafeteria workers, janitors, bus drivers—everybody. But he was making as much as $300 a day and felt "ten feet tall and bulletproof." Joe said: "I kept slogging through the muck of the lousy motels and fast food and endless nights away from home. Persistence. There's nothing like it! Except for education. I read everything. Still do. Business books, The Wall Street Journal, music magazines, fashion magazines, Architectural Digest, The Economist—you name it, I read it." There are days Joe reads nearly every word of five different newspapers in addition to a stack of magazines. Lastly, Joe told me that while he never had a written-down business plan, he did always have goals. He knew exactly what he wanted his life to look like and stuck with it until it did. Joe now is one of the highest-paid, most successful speakers in the country. He regularly travels to all those places he read about in the Ian Fleming novels when he was a kid, and he lives in a big, expensive house in Nashville just like the ones he used to drive by when he cut class. JOHN Insurance agent, financial planner John grew up in Fort Worth, Texas. His daddy was a Sheetrocker during the week to support his Sunday preaching job for which he refused to be paid. According to John, "In my family it seemed that being financially downtrodden was mistaken for righteousness." He told me that while they really didn't know any rich people, it could only be assumed rich people were sinful. His family's biggest financial extravagance was to eat at a hamburger joint once a month. In fact, he never had a steak in a restaurant until he was in college. But it was this lack of money that made his family totally focused on money. He worked with his father every day after school and six days a week during the summer from the first grade on. By the time he was fourteen, he was a journeyman Sheetrocker and as good as any adult on the crew. Because Sheetrockers are paid by the job and not by the hour, John learned the free-enterprise system: The more you produce, the more money you can earn for your family. At about this time, during one of his family's many financial crises, John promised his mother that someday he would be rich so she wouldn't have to worry about money ever again. He said it wasn't a flippant comment at all; it was a promise that he was resolved to make happen. John says of all the promises he has ever made and fulfilled, this one to his mother has been the most rewarding. John worked hanging Sheetrock to put himself through college. Along the way, he started hiring other students to work for him. He said that it amazed him that people would work so hard for a "by the hour" job, never expressing any interest in his profits or losses or how his expanding business worked. They just wanted their pay for the hours they worked. But John still wanted to understand business well enough to get rich. Though John was a music major who had grown up poor and never had any money or any training in business math, it all seemed pretty simple to him. "If I got paid two hundred dollars for a day's worth of work and I owed my helpers one hundred dollars, then I was a businessman. On the other hand, if I got paid one hundred dollars for the day's work but owed my helpers two hundred dollars, then I was a fugitive, as I did not have the money to pay them and they would probably kill me with their Sheetrocking tools." Therefore John learned how to calculate his profits and losses on an hour-by-hour basis to make sure there was enough money to pay his helpers. He would set certain financial targets, and if he met them, would reward himself with a steak dinner at a nice restaurant. Soon John was eating a steak every night. John says that the simple math of being wealthy makes great sense to him. "If you're broke, then the cost of a hamburger seems very high. If you have tons of dough, the cost of that same hamburger seems insignificant." John said that as he made more money, things seemed cheaper to him. While the cost of the hamburger and other goods remained the same, loads of money seemed to make everything a bargain. John made the decision that he wanted to create a world for himself in which the cost of things was insignificant—a world where he was so financially successful that everything he wanted to buy would seem like a bargain. John decided to study all the ins and outs of the money and prosperity game. He wanted to learn all he could about how to attain wealth and invest it wisely. John is now a financial planner specializing in older Americans whose net worth is in excess of 100 million dollars. John is fascinated by the commonalities of affluence he has learned from working with very wealthy people. According to John, he says it comes down to these few things: Competency. Hard work. Perseverance. Serve others according to their needs, not your own. Spend less than you make. BRAD Brad coaches and leads one of the top financial planning offices for a major firm in Canada. Brad grew up in a house full of people: two siblings, a single mother, an aunt suffering from MS, plus a grandmother and grandfather all living in one small house with one bathroom. Brad's bedroom was a closet off the living room. According to Brad, "Love was plentiful, money was always tight." They felt it most on Thursday night because that was grocery-shopping night. Going to the store was always full of tension and stress because there just wasn't enough money to get what they wanted. So it was day-old bread, powdered milk, and orange crystals instead of orange juice. Those grocery-store experiences made him hate the feeling of not having money. The defining moment for Brad was when he decided to stage his own personal hunger strike before Christmas. He thought if he didn't eat, it would save his family money so they could have more for Christmas. After three days of not eating, he couldn't go on and decided that money was not going to dictate his life, but his life was going to dictate his money. Brad decided to become rich. He worked construction and lived above a funeral home for $100 a month rent. He moved on to retail so he could make a few more bucks to live and he could buy books. He made success and wealth a study course by reading at least fifty books per year. Looking back, he says he has spent at least $100,000 at Brad's University of Wisdom by investing in books and attending seminars. Even after becoming a millionaire, Brad still attends lectures and seminars all over the world to expose his mind to the world's great thinkers and leaders. He began by surrounding himself with like-minded people who would challenge him and force him to become more by expecting more from him. Brad has kept a daily journal for twenty-five years. Give him a date and he can flip through his journals to tell you where he was, who he was with, what was said, and what he thought about it at the time. When I was writing my book It's Called Work for a Reason! I called Brad to ask him to review notes from a speech he had heard me give more than ten years earlier and to remind me of anything particularly good I had said. It only took a few hours before I had a list of things he had learned during my session that day. He also told me how well they had worked since. What a source of information your journals can be! Brad is also a voracious goal setter. Every New Year's Day he sits by the pool at some beautiful resort and makes a list of everything he wants in life. These goals include money, health, spiritual development, business, personal development, family, travel, and anything else that comes to mind. They are extremely specific, and he reviews them constantly to monitor his progress. He makes his kids do the same thing. If you had asked Brad at the age of seventeen what his life would look like today, you would find that today it looks almost exactly as he pictured it. He knew what he wanted in a wife and he got it. He knew what he wanted his children to be like and he got that, too. He would have told you that he would have lots of money, ample time to spend it, and would give lots of it away to those who need it. He does. He would have told you that he would have enough money so he would never, ever have to worry about it again. He promised himself that he would surround himself with astonishing people whom he would be able to call friends. I am one of them and for that we are both better people. Brad says, "My dreams are so precise I could draw an artist's sketch of all of them." Today Brad lives like a movie star with the anonymity of a regular guy. He loves life and family and friends. He still laughs in the face of the naysayers. He has never given up on anything, and says he never will. PEGGY Real estate agent and developer Peggy was born into a poor family. She describes her father as a "mean alcoholic," but when he was sober she was able to draw great self-confidence from him. As a child, people would ask her, "What do you want to be when you grow up?" She would spill out actress, airline stewardess, mother, dancer, veterinarian, scientist, archeologist, and any other thing that interested her at the time. But her father told her she could be whatever she wanted and she believed him. Everyone else told her to pick just one thing, but her father never limited her in any way. When she was twelve years old Peggy began to "blossom" and her family didn't have enough money to keep her in bras. Humiliated, she told herself, "This will never happen to me again." Mine was a pair of blue jeans...Peggy's motivation was a bra. Peggy graduated from high school in May and got married in July at the age of eighteen. Her first son was born six days after her nineteenth birthday. Within five years she had two more sons. At the age of twenty-six she found herself getting divorced from a man who promised that, if she left him, he would never pay her any child support. He was true to his word for the next eight years. Peggy had never worked outside the home and had no skills of any kind other than typing, which she had learned in high school. So she rented an old typewriter, practiced her typing skills, and landed a job as a legal secretary after talking politics with the senior partner who interviewed her. After a week, they caught on that her skills were limited and fired her with two weeks' pay. But Peggy remembered thinking, "That was easy. I'll do it again!" And she did. She got a job making $475 a month gross income. She had no child support to help and her rent was $350 a month. To make ends meet, she sold everything she owned. A man she was dating at the time taught her how to deal poker. She landed a job dealing poker at night and worked as a secretary during the day. She was working two full-time jobs while trying to raise three small boys. But as Peggy puts it, "Those were dark days and now I'm grateful for the gift of desperation. I made up my mind to survive and I did." Peggy found working full-time both day and night to be a hard schedule and a hard life for a young, naïve mother of three. So she turned her attention to a career in real estate since it offered not only an unlimited potential for income but also a flexible time schedule. At least she could work any eighty hours a week she chose to work! When Peggy started selling real estate, she had been able to save only two months' worth of living expenses. Because she made only straight commission, she had to sell something fast. She sold a house for $19,500, giving her a commission of $585, which she split with her broker. A year later she bought her own house...pretty good for a girl who, only two years before, had never owned her own car. Peggy now does what she does, not to survive but to help make people's dreams come true. She has a "love affair" with selling real estate. Peggy has come a long way from that first commission of $585. Her average commission now is over $20,000. She owns fifteen houses and regularly buys, renovates, and sells houses in addition to her regular real estate endeavors. She and her team are rated the top team in her market and she has a net worth of more than 2.5 million dollars. RANDY GAGE Entrepreneur, author, multimillionaire, world traveler You will notice Randy's full name is given. He wanted it that way. Some didn't. Some multimillionaires wanted to keep their business to themselves and shared their stories with you simply because they are my friends and I asked them to. Randy's story is one he readily shares with people in his seminars and books. Randy was the middle child of a single mother who raised three kids while knocking on doors selling Avon. So Randy began with nothing but a determination to better himself. He had some bumps in the road along the way, but he persevered not only to become a successful multimillionaire but also to help millions of other people reach higher levels of success through his books, seminars, and coaching. The most important factor for Randy was making the decision to be wealthy. Even as a child, he hated being poor and swore that he would become wealthy. He told all his friends that he would be a millionaire by the time he was thirty-five. Guess what year he made it? You got it: the year he turned thirty-five. Randy was a teenage alcoholic and then moved on to hard drugs. He was expelled from high school and at age fifteen he went to jail for a series of burglaries and armed robberies. Yet even in those troubled times, he had a belief that he would grow up to be wealthy. It would be nice to say that as soon as he turned from a life of crime to earning an honest living, his fortunes turned around. Nice but not true. Even though he dedicated himself to hard work, things didn't change right away. Randy didn't really have a clearly defined dream. He knew what he was running away from, but he didn't have a clear vision of what he was running to. Like most of us, he fell prey to the common beliefs, such as money is bad, rich people are evil, and it is somehow noble or spiritual to be poor. As a result, he strove for success on a conscious level, working hard, opening businesses, and hoping for success. Yet he kept subconsciously sabotaging his own success. He failed in a lot of business attempts, all while ruining his health, relationships, and other areas of his life. He reached the breaking point when his business was seized by the tax authorities and auctioned off for debts. He was left with no car, no money, no credit cards, and $55,000 in debt. He sold his furniture to pay the rent and slept on the floor. His life sucked. But he stuck with it, because by this time he had started to develop a vision of what his dream life could look like. He began a study of the science of prosperity. He read hundreds of books and filled dozens of notebooks with the ideas he learned. He went to seminars and workshops and started really evaluating how he spent his time. He looked at the people he was hanging out with and decided he needed to change some of them. He wasn't afraid to work longer and harder than other people were. He adopted the motto "I will do today what others will not do, so in the future I can do what others cannot do." And he made it come true. Today he lives in his dream home packed with more designer clothes and shoes than an Armani boutique. He's in better health in his late forties than he was at twenty, and he arranges his entire business schedule around the schedules of the four softball teams he plays on. He has his "fleet" of sports and luxury cars downstairs and wakes up to a view of sailboats on the bay. In the winter, he's in Florida, and in the summer you'll find him in Paris or Costa Rica. Now he travels the world, coaching others to reach success. GREAT STORIES, HUH? I love these people and their stories. You might say I am lucky to be surrounded by people like this. I am. The best part is that I could have taken another twenty minutes after calling these five friends and had five more just like them with great stories ready to help me out. You might be the kind of person who sees wealthy people and assumes these people are just lucky or that they inherited their money. The reality is probably that they worked their asses off to get their money. Know what? You are surrounded by people just like these. They might not be multimillionaires, but I guarantee you they have stories of overcoming adversity that would encourage you. You probably just never took the time to ask for their stories. You could be a person just like any of my friends. Your story can't be any more tragic or complicated than any of these. Even if it is, you can overcome it if you look at what they did and emulate the lessons learned. SUCCESS ALWAYS LEAVES CLUES. After reading hundreds of biographies of great people I have noticed that successful people are all very similar. Their stories contain common threads. The people we all look up to are rarely extraordinary people. Instead, they are regular people doing extraordinary things. As you read the five stories about my friends, did you notice any similarities? There are many: Each started with almost nothing. Each faced adversity. Each had every excuse in the world to stay broke, yet refused to. Each made a decision to be wealthy. Each worked smarter, harder, faster, and longer than their peers did. Each studied success. Each had goals they were willing to take action on. Each of them stuck with it even when it sucked. Take a good hard look at your life. Then look at the similarities above. Now go to work. No excuses and no whining. Use these stories to inspire you to better things. It's not about talent or being special. It's about a willingness to do what it takes! CAN YOU DO IT? Of course you can. I've never met anyone who couldn't do better, and you are no different. You can do it. But that isn't really the question. The question is, will you do it? It's never about whether you can do it—it's always about whether you will do it. If you are sick of just getting by, will you change that and begin to get ahead? I hope you make that decision. How far ahead is up to you. Following my plan can make you rich. But rich is up to you. Millionaire is up to you. You get to choose how far you take these principles. The principles never change, only the number of zeroes you put behind your net worth. It won't be easy. It will sometimes be embarrassing. It may never be perfect. But it can be done. Now you know what it takes. The reality is that it's hard. It is hard to achieve prosperity at any level. When you look at your life, your job, and your bank account, you might think that being rich or even getting ahead is impossible. If you think it is impossible, then it is. Stop thinking that way. If you say that it is impossible, it is. Stop talking that way. If you act as if it is impossible, it is. Stop acting that way. To achieve the impossible requires discipline. We aren't a society that believes much in discipline. Discipline requires work—a daily commitment steeped in action in order to achieve your goals. That's my problem with goal setting. Too much focus on the goal and not nearly enough focus on the daily commitment or the action necessary to achieve the goal. MY LESSON IN IMPOSSIBLE. I grew up on a farm called Henry's Bantam Ranch. We had over a hundred varieties of bantam chickens. We also had rabbits, goats, pigs, cows, pigeons, horses, and other assorted animals and birds. One day a new calf was born and even though I was a little boy, I could pick it up and carry it around. My dad told me if I picked that calf up every day of its life and never missed a day, even when that calf was grown I would still be able to pick it up. I was skeptical. He explained to me that the calf would grow just a little every day but it wouldn't grow so much that I couldn't pick it up the next day. He said that if I ever missed a day for any reason, I wouldn't be able to do it. This seemed impossible to me. I looked at that calf 's mother and she weighed about 500 pounds. I couldn't imagine picking up a 500-pound cow, but I always trusted my dad, so I told him I would do it. I picked the calf up and said to myself, "Day one." The next day, I went out to the barn and again picked up the calf. No problem. "Day two." The next day I did the same thing. I did it for about a week with no problem at all. Then it rained and I got busy and I had to play with my friends and I missed a day. The next day I went to the barn and it was really hard to pick the calf up. My dad just smiled and said, "You can't miss a day. If you want to do the impossible, you can't miss a day." Then I got busy again and missed a couple of days. When I went to the barn the next time with my dad, I couldn't pick the calf up. No matter how hard I tried, I couldn't do it. My dad just laughed. If I had continued every day with that calf, I have no idea if I would have been able to pick it up when it weighed 500 pounds. After all, a 500-pound cow is hard to get your arms around. But I still never forgot the lesson. If you want to achieve the impossible, you can't miss a day. It's the daily discipline, the daily work that makes achieving things possible. The impossible doesn't care whether you are busy, it doesn't care whether it's raining, or you don't feel good, or if you want to play with your friends, it still requires you to do all you can every day. Maybe getting rich seems impossible to you. Maybe just getting back to even seems impossible for you. I remember when it did for me. The whole concept might be something you just can't get your arms around. It doesn't matter. You still have to work on it every day. You have to spend a little less, save a little more, pay a little more on your debt, read a little more, do a little more, and you have to do it all every day. You can't miss a day. YOUR FINAL EXERCISE. Now you know what it takes to go from getting by to getting ahead. You just have to make the commitment to do it. But a commitment only to getting ahead is just the first step to a life of financial security. I want you to be inspired to take these principles to the next level: getting rich. You deserve it. You deserve the peace of mind that comes from being rich. Remember how I became rich? I made the decision. All of my rich buddies, Joe, John, Brad, Peggy, and Randy, made that decision too. Now you need to make that decision. Take a minute and write down your decision to be rich. It's not enough to say it in your mind or to even say it out loud. Make it real by writing it down. Now sign it. This is your contract with yourself. This is a deal you are making with yourself and your future. You aren't making a deal with me. Your decision to be rich has nothing to do with me. It has to do with you. View this decision to be rich as a binding contract. You might be saying, "This is stupid. Who will know if I keep the contract or not?" Only you will know. You are the one who has to look yourself in the eye. Since you probably just skipped this final exercise, stop and go back and write down your decision to get rich. Date it and sign it. And never forget: * * * A deal is a deal. * * * Larry's Twelve Ways to Go from Getting By to Getting Ahead 1. Know where you are. 2. Take responsibility for the situation. 3. Feel bad about it. Experience remorse. 4. Make the decision for things to be different. 5. Know exactly what you want your life to look like. 6. Create an action plan to get there. 7. Know what you are willing to give up to get what you want. 8. Spend less than you earn. 9. Figure out ways to earn more. 10. Stop all unnecessary spending. 11. Pay off debts as quickly as possible and only go into debt for things with long-term value. 12. Build a cushion. Save! "Live long and prosper." The Vulcan Salute, Star Trek ## ACKNOWLEDGMENTS To my rich buddies who contributed their personal stories to this book. Their friendship is a constant inspiration to me. To my boys, Tyler and Patrick, who have always been proud of me and let me know it. I owe them big for that. To my wife, Rose Mary, who loves me in spite of myself. To my mom and dad, Dorothy and Henry Winget, who taught me to tell the truth, to be honest, work hard, and take responsibility: the real keys to success. To Vic Osteen, my manager and friend, who knew me when I was a nobody and helped me become a somebody. To A&E for picking me to be the host of Big Spender. To NorthSouth Productions for producing Big Spender. They always make me look good and are simply the best to work with in every way. To my friends at Gotham Books: Bill, Erin, Jessica, Lisa, and Beth. They are great folks who get me and what I do. They are a terrific team and I appreciate being a part of it. ## FREE VIDEO DOWNLOAD: Five Financial Lessons from Larry To receive your free gift for purchasing this book, go to www.YoureBroke.com. You will find instructions for downloading your free video of Larry discussing key principles from the book and more. You'll actually get to see the tools discussed in the book and hear Larry talk about changing your financial future. Plus, you will receive some extra bonus gifts just for visiting the site. You can even download the budget page from the book so that you can begin the process of getting ahead today! Be sure to have the book on hand when you visit the Web site and are ready to download the video, as it contains the secret to downloading your free financial lessons. www.YoureBroke.com ## Larry Winget is the author of the New York Times and Wall Street Journal bestseller It's Called Work for a Reason! Your Success Is Your Own Damn Fault (Gotham Books, 2007) and Shut Up, Stop Whining, & Get a Life: A Kick-Butt Approach to a Better Life (more than 100,000 copies sold). One of the country's highest paid professional speakers, he also stars in A&E's reality series Big Spender and is a featured guest on CNBC's The Millionaire Inside. He lives in Paradise Valley, Arizona, with his family.
Process development for the enrichment of curcuminoids in the extract of ionic type of NADES Curcuminoids were successfully extracted from Curcuma zeodaria powder with Natural Deep Eutectic Solvents (NADES) as solvent. Ionic types of NADES such choline chloride-citric acid-water (CCCA-H2O = 1:1:18, mole ratio) and choline chloride-malic acid-water (CCMA-H2O = 1:1:18, mole ratio) gave the highest yield of extracted curcuminoids, ca. 0.270±0.025 and 0.355±0.055 mg/g respectively for CCCA and CCMA. However, the final product of the extracted curcuminoids was mixed in the NADES matrix. Hence, a separation process by means a solidification was mandatory. Isopropanol-n-hexane in both volume and molar ratio, i.e. 1:1, 1:1.5, 1:2, 2:1, and 2.5:1, were observed as a solvent in the solidification process as well as the solubility of curcuminoids in both isopropanol and n-hexane. Unfortunately, both of CCCA-H2O (1:1:18) or CCMA-H2O (1:1:18) and curcuminoids form a homogenous mixture with isopropanol. Therefore, all NADES constituents, i.e. choline chloride, citric acid/malic acid, and water, should be first removed before solidification process. Solubility of curcuminoids in isopropanol and n-hexane was, respectively, 3.2 mg/mL and 0.4 mg/mL at 40 °C. Isopropanol-hexane (1:1.5, v/v) give the highest recovery of curcuminoids, ca. 74.29%, by solidification process. Introduction Curcuma zeodaria or kunir putih (in Bahasa) contains bioactive compounds, curcuminoids. Curcuminoids consist of curcumin (C), desmethoxycurcumin (DMC) and bisdemethoxycurcumin (BDMC) which potentially act as antioxidant and anticancer. Due to the low solubility of curcumin in water (pH = 7.3), approximately 4 ppb of water (4μg / L) , curcumin is not yet approved as an anticancer agent. Therefore, a carrier which can release curcumin completely into the human body is needed . Natural Deep Eutectic Solvent (NADES) solubilized and extracted curcumin is much better than commonly organic solvent such methanol, ethanol, as well as water at 40 ˚C within 24 hours of extraction time . Natural Deep Eutectic Solvent (NADES) is an environmentally friendly solvent which is made of natural primary metabolites such amino-acids, monosaccharides, disaccharides, polysaccharides, acetic acids, lactic acids, choline chlorides, etc. in a certain molar ratio . Ionic types of NADES, i.e. CCMA (Choline Chloride-Malic Acid) and CCCA (Choline Chloride-Citric Acid) with 1:1:18 in mole ratio yield the highest curcuminoids compared to other types of NADES . The batch stirrer reactor is previously applied for the extraction curcuminoids from Curcuma zeodaria . Therefore, extracted curcuminoids and NADES as solvent including the powder of C. zeodaria are completely mixed as a slurry. Therefore, the separation process following the purification process is needed to be developed to produce high purity of curcuminoids while maintaining both physically and chemically stable curcuminoids for longer self-life. Hence, a solidification method is considered. It is done by purifying the target analytic simply by precipitation. It is expected that the curcuminoids can be directly purified and precipitated from the extracted solution, mixture of curcuminoids and NADES. Reagents and chemicals Standard Curcuminoids which contain 75.13%-w of curcuminoids (C), 21.29%-w of desmethoxycurcumin (DMC), and bisdemethoxycurcumin (BDMC) was commercially purchased from Merck (Darmstadt, Germany) as well as solvents such as acetonitrile, acetic acid, and methanol. All the solvents were in High Pure Analytical grade. While individual components of NADES such as choline chloride and malic acid were purchased from Sigma Aldrich (St. Louis, MO, USA). Food grade of citric acid was purchased at Surabaya local market (Gajah, Jakarta, Indonesia) and buffer solution (pH = 2.0) from Mediss (India). Moreover, a filter paper (no. 589/2) within 4-12 m of pore size was purchased from Whatman (Germany). Natural Deep Eutectic Solvents (NADES) preparation All NADES used in this study were prepared based on the method by Rachmaniah et al. , which is a modified method of . Each constituent of NADES was accurately weighted in molar ratio; mixed with water and subsequently stirred in sealed bottle equipped with water bath at 70 o C. The agitation was continued till all the solid compounds of NADES melted, forming a homogeneous mix of liquid. The formed liquid was directly stored in drank. Solubility test of curcuminoids in isopropanol-Hexane Solubility test of curcuminoids was conducted by gradually adding an accurate weight of curcuminoids in mixture of different molar and volume ratio of isopropanol-hexane at 40 o C. The addition was stopped until saturated condition of curcuminoids was reached, Indicated by a precipitation of curcuminoids. Subsequently, samples were suddenly cooled at 9 o C, vacuum filtered, dried at dessicator. A dried sample of curcuminoids was weighted and its percentage of recovery was calculated. Sample preparation for solidification process An accurate weight of curcuminoids standard was dissolved in CCMA-H2O (1: 1: 18) or CCCA-H2O (1: 1: 18) at 40 o C within S/F ratio of 5/10 (mL NADES/mg curcuminoids). Subsequently, isopropanolhexane was added, suddenly cooled at 9 o C, vacuum filtered, dried at dessicator. A dried sample of curcuminoids was weighted and its percentage of recovery was calculated following the equation (1). Result and discussion Purifying and having curcuminoids in solid form from extract mixture of NADES is required. Curcuminoids in the solid form is more storable than in liquid. The keto structure of curcumin is commonly found in the solid phase . While in the liquid phase, the keto-enol structure of curcumin is more stable than its diketone structure . Enol enthalpy of formation of curcumin is lower than its keto tautomer; implying that the enol tautomer is more stable (Figure 1) . Curcumin in diketone structure obviously does not have active methylene group. This C-H bond has higher enthalpy of dissociation than O-H group at phenolic; therefore, O-H bonds more reactively active follows antioxidant mechanism . Figure 1. Keto-enol form of curcuminoids . Therefore, firstly, a solubility test of curcuminoids in mixture of both of volume and molar ratio of isopropanol-hexane at 40 o C was conducted (Table 1 and 2). Mixture of isopropanol-hexane as solvent was chosen since it was the most suitable solvent to solidify the curcuminoids , increasing the solubility and simultaneously avoiding the degradation of curcuminoids. Therefore, 40 °C was settled. Mixture of isopropanol-hexane (1:1.5, v/v) gave the highest recovery of curcuminoids, ca.74.29% (Table 1). Moreover, solid form of curcuminoids in volume ratio was more coarse compare to the molar ratio variable (Figure 2 and 3). Interestingly, volume ratio of isopropanol-hexane at 1:2 (v/v) and 1:1 (v/v) resulted in the finest form of curcuminoids. Therefore, the solubility of curcuminoids in isopropanol and n-hexane were also observed. There were 3.2 mg/mL and 0.4 mg/mL of curcuminoids solubility, respectively, in isopropanol and n-hexane at 40 °C. Curcumin and desmethoxycurcumin could partly be dissolved in n-hexane . Hence, by increasing volume of n-hexane, curcuminoids would more likely precipitate. As a nonpolar solvent, n-hexane acted as anti-solvent in this solidification process of curcuminoids, precipitating the curcuminoids . Meanwhile, isopropanol with mediumpolarity selectively dissolved curcuminoids. Hence, the optimum solidification of curcuminoids could be done by combining solvent and anti-solvent. Solidification of curcuminoids using molar ratio of isopropanol-hexane was also observed (Table 2). Unfortunately, the results of molar ratio were not as good as the volume ratio. The solid form of curcuminoids was finer, creating some difficulties in the filtering process. It might be explained by the smaller volume of n-hexane added as it was counted in molar ratio. Hence, it affected the precipitation. To conclude, Isopropanol-hexane (1:1.5, v/v) is the best combination for solidifying curcuminoids. Furthermore, the volume ratio of Isopropanol-hexane is studied to solidify the curcuminoids in NADES matrix. A sample of curcuminoid-NADES (CCMA-H2O = 1:1:18) 20.6 mL was added with 2.5 mL Isopropanol-hexane (1:1.5, v/v). A resulted mixture was suddenly cooled at 9 o C. Two organic layers were observed ( Figure 4A). Considering the densities of isopropanol and hexane, the upper layer mainly contained hexane while the lower layer contained isopropanol. Unfortunately, though upper layer was sharply separated, curcuminoids in lower layer still could not be precipitated by adding either more isopropanol or hexane. In addition, observing this phenomenon, we mimic the lower layer by accurately mixing (in percentage of weight) curcuminoids-choline chloride-malic acid-water-isopropanol. A homogenous mixture of curcuminoids-choline chloride-malic acid-water-isopropanol was formed ( Figure 4B) such a eutectic mixture. Isopropanol is commonly used as a solvent for many natural products such as curcuminoids. There is presumably a competition in dissolving curcuminoids between isopropanol and NADES. Moreover, choline chloride-polyalcohol, i.e. 1, 2-propanediol, isopropanol, in certain molar ratio can form a NADES . Choline chloride also has high solubility in isopropanol, ca. 58.8 mg/mL at 40 o C. Consequently, curcuminoids cannot be successfully solidified using hexane as anti-solvent when NADES is still present in mixture. Due to the phenomenon, curcuminoids in NADES matrix cannot be precipitated directly by solidification process using isopropanol-hexane. The NADES ingredients should be minimized first or even eliminated to precipitate curcuminoids by solidification.
"Goddesses With Guns" rally in San Antonio (KSAT/screen grab) Women were in the minority at a so-called “Goddesses With Guns” rally over the weekend that intended to prove that not all gun lovers were a “bunch of redneck men.” According to the San Antonio Express-News, a group of women from Houston and “about 40 other people” gathered in San Antonio on Saturday to show support for their Second Amendment rights. Emily Grisham told the Express-News that the group was formed as a response to Moms Demand Action, a group which supports gun safety laws. Open Carry Texas, a group founded by Grisham’s husband, CJ, sparked controversy earlier this year when members carried assault-style rifles into Chipotle and other national restaurant chains. Grisham said that the “Goddesses With Guns” rally was created to counter the “myth that OCT is just a bunch of redneck men that all they do is go out there and scare women and scare their children. We don’t.” But the Express-News reported that “men slightly outnumbered women at the rally.” Grisham’s husband said that some of the members of Open Carry Texas had planned to take their loaded weapons to a nearby Walmart following the rally with the hopes of getting arrested. It’s illegal to openly carry a loaded firearm within San Antonio city limits. “If we don’t get ticketed or arrested … then [we] can’t go to court and fight this ordinance,” he explained. “We’re not doing it to be civilly disobedient. That’s the only way our legal system allows us to fight it.” Liberaland pointed out last week that only 18 of the 47 people who had signed up to attend the “Goddesses With Guns” rally were women. Watch the video below from KSAT, broadcast Sept. 20, 2014.
Gerard W. Ostheimer “What’s New in Obstetric Anesthesia” Lecture EVERY year, the Society for Obstetric Anesthesia and Perinatology celebrates the life and legacy of Gerard Ostheimer, M.D., an obstetric anesthesiologist renowned for his wisdom, his passion for life, and his generosity to the society and the specialty. The celebration takes the form of an eponymous lecture given at the Society for Obstetric Anesthesia and Perinatology Annual Meeting with the purpose of evaluating literature contributions from a single year that are pertinent to the clinical care and research of obstetric anesthesia patients. From more than 1,400 contributions in 2003, 841 were abstracted in the Society for Obstetric Anesthesia and Perinatology 36th Annual Meeting program syllabus, with general themes summarized in the lecture.This article focuses on four advances that are of importance to anesthesiologists who practice within an obstetric setting. These include advances in the uniquely human obstetric disease, preeclampsia; a leading cause of maternal death, peripartum hemorrhage; the functional physiology of maternal pain and labor analgesia; and the philosophical issues surrounding delivery of care: ethics and consent.
There ’ s No Place Like Home : Coordinating Care for Veterans In VA, care coordination involves the use of telehealth, disease management, and health informatics technologies to enhance and extend care and case management activities. VA is initially focusing its care coordination effort on the home and using home-telehealth technologies. We describe this range of activities as care coordination/home telehealth (CCHT). We are finding these technologies particularly useful for extending care in rural and underserved areas.
/** * Use a for loop to print the even numbers between 1 and 50, including the first even number, and the number 50. * Print each number on a new line. */ public class Lesson_24_Activity_Two { public static void main(String[] params) { for (int i = 2; i <= 50; i += 2) { System.out.println(i); } } }
/** * Handles {@link Command#ENABLE} via setting the desired state of the Unit and sending * START command to the Unit if it is not in STARTED state yet. */ private class EnableHandler implements CommandHandler { @Override public boolean handles(Command c) { return c == ENABLE; } @Override public void handle(Command c) { DesiredState previousDesired = desiredState; desiredState = ENABLED; publishState(state, previousDesired); if (state != STARTED) { sendCommand(id, START); } } }
package apps import ( "github.com/cloudfoundry-incubator/cf-test-helpers/cf" "github.com/cloudfoundry-incubator/cf-test-helpers/workflowhelpers" . "github.com/cloudfoundry/cf-acceptance-tests/cats_suite_helpers" "github.com/cloudfoundry/cf-acceptance-tests/helpers/app_helpers" "github.com/cloudfoundry/cf-acceptance-tests/helpers/random_name" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/gomega/gexec" ) var _ = AppsDescribe("Getting instance information", func() { Describe("scaling memory", func() { var appName string var runawayTestSetup *workflowhelpers.ReproducibleTestSuiteSetup BeforeEach(func() { runawayTestSetup = workflowhelpers.NewRunawayAppTestSuiteSetup(Config) runawayTestSetup.Setup() appName = random_name.CATSRandomName("APP") Eventually(cf.Cf(app_helpers.BinaryWithArgs( appName, "-m", DEFAULT_MEMORY_LIMIT)...), Config.CfPushTimeoutDuration()).Should(Exit(0)) }) AfterEach(func() { app_helpers.AppReport(appName) Eventually(cf.Cf("delete", appName, "-f")).Should(Exit(0)) runawayTestSetup.Teardown() }) It("fails with insufficient resources", func() { scale := cf.Cf("scale", appName, "-m", workflowhelpers.RUNAWAY_QUOTA_MEM_LIMIT, "-f") scaleMatch := "insufficient" if Config.RunningOnK8s() { scaleMatch = "Insufficient" } Eventually(scale).Should(Or(Say(scaleMatch), Say("down"))) scale.Kill() app := cf.Cf("app", appName) Eventually(app).Should(Exit(0)) Expect(app.Out).NotTo(Say("instances: 1/1")) }) }) Describe("Scaling instances", func() { var appName string BeforeEach(func() { appName = random_name.CATSRandomName("APP") Expect(cf.Cf(app_helpers.CatnipWithArgs( appName, "-m", DEFAULT_MEMORY_LIMIT, "-i", "1")...).Wait(Config.CfPushTimeoutDuration())).To(Exit(0)) }) AfterEach(func() { app_helpers.AppReport(appName) Expect(cf.Cf("delete", appName, "-f", "-r").Wait()).To(Exit(0)) }) It("can be queried for state by instance", func() { Expect(cf.Cf("scale", appName, "-i", "2").Wait(Config.CfPushTimeoutDuration())).To(Exit(0)) app := cf.Cf("app", appName).Wait() Expect(app).To(Exit(0)) Expect(app).To(Say("#0")) Expect(app).To(Say("#1")) }) }) })
// Size return a uint64 measure of the filo size in bytes. func (f *filo) Size() uint64 { if f.read != nil { res := f.read(f.h) return uint64(res.Len()) } return 0 }
/** * A comparator for flaws and their resolvers that uses lifted abstraction hierarchies. * * The ordering places unsupported databases first. Other flaws are left unordered * Unsupported databases are ordered according to their level in the abstraction hierarchy. * */ public class AbsHierarchyComp implements FlawComparator { private AbstractionHierarchy hierarchy; /** * Map AnmlProblems to a pair (n, h) where h is the abstraction hierarchy for the nth revision * of the problem. */ static Map<AnmlProblem, Pair<Integer, AbstractionHierarchy>> hierarchies = new HashMap<>(); public AbsHierarchyComp(PartialPlan st) { if(!hierarchies.containsKey(st.pb) || hierarchies.get(st.pb).value1 != st.pb.chronicles().size()) { hierarchies.put(st.pb, new Pair<>(st.pb.chronicles().size(), new AbstractionHierarchy(st.pb))); } this.hierarchy = hierarchies.get(st.pb).value2; } private int priority(UnsupportedTimeline og) { // open goal, order them according to their level in the abstraction hierarchy return hierarchy.getLevel(og.consumer.stateVariable.func()); } @Override public int compare(Flaw o1, Flaw o2) { if(o1 instanceof UnsupportedTimeline && o2 instanceof UnsupportedTimeline) return priority((UnsupportedTimeline) o1) - priority((UnsupportedTimeline) o2); else return 0; } @Override public String shortName() { return "abs"; } }
// Known reports whether an equipment is known func (eq Equipment) Known() bool { for _, k := range knownEquipments { if eq == k { return true } } return false }
/** @file * @brief Internal header for Bluetooth BASS. */ /* * Copyright (c) 2019 Bose Corporation * Copyright (c) 2021 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr/types.h> #include <bluetooth/conn.h> #include <bluetooth/audio/bass.h> #define BT_BASS_SCAN_STATE_NOT_SCANNING 0x00 #define BT_BASS_SCAN_STATE_SCANNING 0x01 #define BT_BASS_OP_SCAN_STOP 0x00 #define BT_BASS_OP_SCAN_START 0x01 #define BT_BASS_OP_ADD_SRC 0x02 #define BT_BASS_OP_MOD_SRC 0x03 #define BT_BASS_OP_BROADCAST_CODE 0x04 #define BT_BASS_OP_REM_SRC 0x05 #define BT_BASS_SCAN_STATE_IDLE 0x00 #define BT_BASS_SCAN_STATE_SCANNING 0x01 #define BT_BASS_SCAN_STATE_FAILED 0x02 #define BT_BASS_SCAN_STATE_SYNCED 0x03 #define BT_BASS_PA_REQ_NO_SYNC 0x00 #define BT_BASS_PA_REQ_SYNC_PAST 0x01 #define BT_BASS_PA_REQ_SYNC 0x02 #define BT_BASS_BROADCAST_ID_SIZE 3 #define BT_BASS_VALID_OPCODE(opcode) \ ((opcode) >= BT_BASS_OP_SCAN_STOP && (opcode) <= BT_BASS_OP_REM_SRC) struct bt_bass_cp_scan_stop { uint8_t opcode; } __packed; struct bt_bass_cp_scan_start { uint8_t opcode; } __packed; struct bt_bass_cp_subgroup { uint32_t bis_sync; uint8_t metadata_len; uint8_t metadata[0]; } __packed; struct bt_bass_cp_add_src { uint8_t opcode; bt_addr_le_t addr; uint8_t adv_sid; uint8_t broadcast_id[BT_BASS_BROADCAST_ID_SIZE]; uint8_t pa_sync; uint16_t pa_interval; uint8_t num_subgroups; struct bt_bass_cp_subgroup subgroups[0]; } __packed; struct bt_bass_cp_mod_src { uint8_t opcode; uint8_t src_id; uint8_t pa_sync; uint16_t pa_interval; uint8_t num_subgroups; struct bt_bass_cp_subgroup subgroups[0]; } __packed; struct bt_bass_cp_broadcase_code { uint8_t opcode; uint8_t src_id; uint8_t broadcast_code[16]; } __packed; struct bt_bass_cp_rem_src { uint8_t opcode; uint8_t src_id; } __packed; union bt_bass_cp { uint8_t opcode; struct bt_bass_cp_scan_stop scan_stop; struct bt_bass_cp_scan_start scan_start; struct bt_bass_cp_add_src add_src; struct bt_bass_cp_mod_src mod_src; struct bt_bass_cp_broadcase_code broadcast_code; struct bt_bass_cp_rem_src rem_src; };
//package eu.eventsotrm.core.apt.event; // //import static eu.eventsotrm.sql.apt.Helper.writeGenerated; //import static eu.eventsotrm.sql.apt.Helper.writeNewLine; //import static eu.eventsotrm.sql.apt.Helper.writePackage; // //import java.io.IOException; //import java.io.Writer; //import java.util.ArrayList; //import java.util.List; // //import javax.annotation.processing.ProcessingEnvironment; //import javax.tools.JavaFileObject; // //import eu.eventsotrm.core.apt.SourceCode; //import eu.eventsotrm.sql.apt.log.Logger; //import eu.eventsotrm.sql.apt.log.LoggerFactory; // //public final class EventStreamGenerator { // // private final Logger logger; // // public EventStreamGenerator() { // logger = LoggerFactory.getInstance().getLogger(EventStreamGenerator.class); // } // // public void generate(ProcessingEnvironment processingEnvironment, SourceCode sourceCode) { // List<String> streams = new ArrayList<>(); // sourceCode.forEventEvolution(t -> { // // for (String proto : t.eventEvolution().proto()) { // int index = proto.lastIndexOf('/'); // if (index == -1) { // index = 0; // } else { // index++; // } // String item = proto.substring(index, proto.indexOf(".proto")); // if (!streams.contains(item)) { // streams.add(item); // } // } // }); // // generate(processingEnvironment, sourceCode, streams); // // } // // private void generate(ProcessingEnvironment env, SourceCode sourceCode, List<String> streams) { // // // check due to // // "org.aspectj.org.eclipse.jdt.internal.compiler.apt.dispatch.BatchFilerImpl.createSourceFile(BatchFilerImpl.java:149)" // if (env.getElementUtils().getTypeElement(sourceCode.getCqrsConfiguration().basePackage() + ".Streams") != null) { // logger.info("Java SourceCode already exist [" + sourceCode.getCqrsConfiguration().basePackage() + ".Streams]"); // return; // } // // if (streams.size() == 0) { // logger.info("No proto found => skip"); // return; // } // // // try { // JavaFileObject object = env.getFiler().createSourceFile(sourceCode.getCqrsConfiguration().basePackage() + ".Streams"); // try (Writer writer = object.openWriter()) { // writeHeader(writer, env, sourceCode); // writeEnumContent(writer, streams); // writer.write("}"); // } // } catch (Exception cause) { // logger.error("Exception -> [" + cause.getMessage() + "]", cause); // } // // } // // private void writeEnumContent(Writer writer, List<String> streams) throws IOException { // for (int i = 0; i < streams.size() ; i++) { // writer.write(" "); // writer.write(streams.get(i)); // if (i + 1 < streams.size()) { // writer.write(","); // writeNewLine(writer); // } else { // writer.write(";"); // writeNewLine(writer); // } // } // } // // private void writeHeader(Writer writer, ProcessingEnvironment env, SourceCode sourceCode) throws IOException { // // writePackage(writer, sourceCode.getCqrsConfiguration().basePackage()); // // writeGenerated(writer, EventStreamGenerator.class.getName()); // writer.write("public enum Streams {"); // writeNewLine(writer); // } // //}
/** * @author Tiago Ribeiro */ public class InMemoryDepositRepository extends InMemoryDomainRepository<String, Deposit> implements DepositRepository { static { InMemoryInitializer.init(); } @Override public Deposit depositById(String depositCode) { return null; } }
import { DWORD } from "../user32/win_def"; export const errHandlingApi = { GetLastError: [DWORD, []] };
Transplantation for the treatment of type 1 diabetes. Transplantation of pancreatic tissue, as either the intact whole pancreas or isolated pancreatic islets has become a clinical option to be considered in the treatment of patients with type 1 insulin-dependant diabetes mellitus. A successful whole pancreas or islet transplant offers the advantages of attaining normal or near normal blood glucose control and normal hemoglobin A1c levels without the risks of severe hypoglycemia associate with intensive insulin therapy. Both forms of transplants are also effective at eliminating the occurrence of significant hypoglycemic events (even with only partial islet function evident). Whereas whole pancreas transplantation has also been shown to be very effective at maintaining a euglycemic state over a sustained period of time, thus providing an opportunity for a recipient to benefit from improvement of their blood glucose control, it is associated with a significant risk of surgical and post-operative complications. Islet transplantation is attractive as a less invasive alternative to whole pancreas transplant and offers the future promise of immunosuppression-free transplantation through pre-transplant culture. Islet transplantation however, may not always achieve the sustained level of tight glucose control necessary for reducing the risk of secondary diabetic complications and exposes the patient to the adverse effects of immunosuppression. Although recent advances have led to an increased rate of obtaining insulin-independence following islet transplantation, further developments are needed to improve the long-term viability and function of the graft to maintain improved glucose control over time.
<filename>src/Dispositivo/dispositivo-mensajes/dispositivo.mensajes.ts<gh_stars>0 export const mensajesDispositivo = { encontrarUno: 'Id Dispositivo erroneo', crearUno: 'Dispositivo inválida', actualizarUno: 'Error actualizando Dispositivo', eliminarUno: 'Error al eliminar una Dispositivo', };
<filename>packages/hydrooj/src/model/training.ts import { flatten } from 'lodash'; import { FilterQuery, ObjectID } from 'mongodb'; import { TrainingAlreadyEnrollError, TrainingNotFoundError } from '../error'; import { TrainingDoc, TrainingNode } from '../interface'; import * as document from './document'; export function getStatus(domainId: string, tid: ObjectID, uid: number) { return document.getStatus(domainId, document.TYPE_TRAINING, tid, uid); } export function getMultiStatus(domainId: string, query: FilterQuery<TrainingDoc>) { return document.getMultiStatus(domainId, document.TYPE_TRAINING, query); } export async function getListStatus(domainId: string, uid: number, tids: ObjectID[]) { const tsdocs = await getMultiStatus( domainId, { uid, docId: { $in: Array.from(new Set(tids)) } }, ).toArray(); const r = {}; for (const tsdoc of tsdocs) r[tsdoc.docId] = tsdoc; return r; } export async function enroll(domainId: string, tid: ObjectID, uid: number) { try { await document.setStatus(domainId, document.TYPE_TRAINING, tid, uid, { enroll: 1 }); } catch (e) { throw new TrainingAlreadyEnrollError(tid, uid); } return await document.inc(domainId, document.TYPE_TRAINING, tid, 'attend', 1); } export function setStatus(domainId: string, tid: ObjectID, uid: number, $set: any) { return document.setStatus(domainId, document.TYPE_TRAINING, tid, uid, $set); } export function add( domainId: string, title: string, content: string, owner: number, dag: TrainingNode[] = [], description = '', ) { return document.add(domainId, content, owner, document.TYPE_TRAINING, null, null, null, { dag, title, description, attend: 0, }); } export function edit(domainId: string, tid: ObjectID, $set: Partial<TrainingDoc>) { return document.set(domainId, document.TYPE_TRAINING, tid, $set); } export function del(domainId: string, tid: ObjectID) { return Promise.all([ document.deleteOne(domainId, document.TYPE_TRAINING, tid), document.deleteMultiStatus(domainId, document.TYPE_TRAINING, { docId: tid }), ]); } export function getPids(dag: TrainingNode[]) { return Array.from(new Set(flatten(dag.map((node) => node.pids)))); } export function isDone(node: TrainingNode, doneNids: Set<number> | number[], donePids: Set<number> | number[]) { return (Set.isSuperset(new Set(doneNids), new Set(node.requireNids)) && Set.isSuperset(new Set(donePids), new Set(node.pids))); } export function isProgress(node: TrainingNode, doneNids: Set<number> | number[], donePids: Set<number> | number[], progPids: Set<number> | number[]) { return (Set.isSuperset(new Set(doneNids), new Set(node.requireNids)) && !Set.isSuperset(new Set(donePids), new Set(node.pids)) && Set.intersection( Set.union(new Set(donePids), new Set(progPids)), new Set(node.pids), ).size); } export function isOpen(node: TrainingNode, doneNids: Set<number> | number[], donePids: Set<number> | number[], progPids: Set<number> | number[]) { return (Set.isSuperset(new Set(doneNids), new Set(node.requireNids)) && !Set.isSuperset(new Set(donePids), new Set(node.pids)) && !Set.intersection( Set.union(new Set(donePids), new Set(progPids)), new Set(node.pids), ).size); } export const isInvalid = (node: TrainingNode, doneNids: Set<number> | number[]) => !Set.isSuperset(new Set(doneNids), new Set(node.requireNids)); export async function count(domainId: string, query: FilterQuery<TrainingDoc>) { return await document.count(domainId, document.TYPE_TRAINING, query); } export async function get(domainId: string, tid: ObjectID) { const tdoc = await document.get(domainId, document.TYPE_TRAINING, tid); if (!tdoc) throw new TrainingNotFoundError(domainId, tid); for (const i in tdoc.dag) { for (const j in tdoc.dag[i].pids) { if (Number.isSafeInteger(parseInt(tdoc.dag[i].pids[j], 10))) { tdoc.dag[i].pids[j] = parseInt(tdoc.dag[i].pids[j], 10); } } } return tdoc; } export const getMulti = (domainId: string, query: FilterQuery<TrainingDoc> = {}) => document.getMulti(domainId, document.TYPE_TRAINING, query).sort({ pin: -1, _id: -1 }); export async function getList(domainId: string, tids: ObjectID[]) { const tdocs = await getMulti( domainId, { _id: { $in: Array.from(new Set(tids)) } }, ).toArray(); const r = {}; for (const tdoc of tdocs) r[tdoc.docId.toString()] = tdoc; return r; } global.Hydro.model.training = { getPids, isDone, isProgress, isOpen, isInvalid, add, edit, del, count, get, getList, getMulti, getMultiStatus, getStatus, enroll, setStatus, getListStatus, };
from plumber import message import unittest class TestMessage(unittest.TestCase): def setUp(self): print("Hello") pass def test_encode(self): msg = message.PlumbMsg( src="test", dst="test", type="text", attrs=dict(), ndata=10, data=b"012345678" ) encoded = message.encode(msg) print("encoded=",encoded) deencoded = message.decode(encoded) print("deencoded=", repr(deencoded)) self.assertEqual(deencoded, msg)
// Package loginv1 provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/deepmap/oapi-codegen version v1.8.3 DO NOT EDIT. package loginv1 import ( externalRef0 "github.com/absurdlab/tiga-sdk/tiga-go-sdk/apiv1/common" ) // AuthenticationCallback defines model for AuthenticationCallback. type AuthenticationCallback struct { // Authentication context class reference. Acr string `json:"acr,omitempty" yaml:"acr,omitempty"` // A list of authentication methods applied. Amr []string `json:"amr,omitempty" yaml:"amr,omitempty"` // Unix timestamp for time of authentication. AuthTime int64 `json:"auth_time,omitempty" yaml:"auth_time,omitempty"` // Identifier of the user session as a result of authentication. Sid string `json:"sid,omitempty" yaml:"sid,omitempty"` // Subject identifier of the authenticated user. Sub string `json:"sub,omitempty" yaml:"sub,omitempty"` } // AuthenticationRequest defines model for AuthenticationRequest. type AuthenticationRequest struct { // Optional array of requested ACR values for the authentication. AcrValues []string `json:"acr_values,omitempty" yaml:"acr_values,omitempty"` // ClientInfo contains public client information that can be used to visually identity the client. Client externalRef0.ClientInfo `json:"client,omitempty" yaml:"client,omitempty"` Links externalRef0.Links `json:"links,omitempty" yaml:"links,omitempty"` // Optional login hint parameter to pass on to the identity provider. LoginHint string `json:"login_hint,omitempty" yaml:"login_hint,omitempty"` // Optional max_age parameter. MaxAge *int64 `json:"max_age,omitempty" yaml:"max_age,omitempty"` // Optional array containing prompt parameters. Prompts []string `json:"prompts,omitempty" yaml:"prompts,omitempty"` // Optional subject identifier to request authentication for. SubHint string `json:"sub_hint,omitempty" yaml:"sub_hint,omitempty"` // Optional list of preferred UI locales. UiLocales []string `json:"ui_locales,omitempty" yaml:"ui_locales,omitempty"` } // SessionId defines model for sessionId. type SessionId string // ErrorResponse defines model for ErrorResponse. type ErrorResponse externalRef0.ErrorResponse // CallbackAuthenticationFailureJSONBody defines parameters for CallbackAuthenticationFailure. type CallbackAuthenticationFailureJSONBody externalRef0.ErrorCallback // CallbackAuthenticationSuccessJSONBody defines parameters for CallbackAuthenticationSuccess. type CallbackAuthenticationSuccessJSONBody AuthenticationCallback // CallbackAuthenticationFailureJSONRequestBody defines body for CallbackAuthenticationFailure for application/json ContentType. type CallbackAuthenticationFailureJSONRequestBody CallbackAuthenticationFailureJSONBody // CallbackAuthenticationSuccessJSONRequestBody defines body for CallbackAuthenticationSuccess for application/json ContentType. type CallbackAuthenticationSuccessJSONRequestBody CallbackAuthenticationSuccessJSONBody
<reponame>ddabble/Risky-Risk<filename>core/src/no/ntnu/idi/tdt4240/observer/TroopObserver.java package no.ntnu.idi.tdt4240.observer; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import no.ntnu.idi.tdt4240.model.data.Territory; import no.ntnu.idi.tdt4240.util.TerritoryMap; public interface TroopObserver { void create(OrthographicCamera camera, TerritoryMap territoryMap, Texture circleTexture, Texture circleSelectTexture); void onMapRenderingChanged(); void onSelectTerritory(Territory territory); void onTerritoryChangeNumTroops(Territory territory); }
import * as d3 from "d3" import { EntityData, EntityKind } from '@framework/Reflection' import * as Finder from '@framework/Finder' import { Point, Rectangle, calculatePoint, wrap, forceBoundingBox } from '../Utils' export interface TableInfo extends ITableInfo { typeName: string; mlistTables: MListTableInfo[]; } export interface MListTableInfo extends ITableInfo { } export interface ITableInfo extends d3.SimulationNodeDatum, Rectangle { tableName: string; niceName: string; columns: number; sql: number | null; rows: number | null; total_size_kb: number | null; rows_history: number | null; total_size_kb_history: number | null; entityKind: EntityKind; entityData: EntityData; entityBaseType: EntityBaseType; namespace: string; nx: number; ny: number; width: number; height: number; lineHeight: number; extra: { [key: string]: any }; } export type EntityBaseType = "EnumEntity" | "Symbol" | "SemiSymbol" | "Entity" | "MList" | "Part"; export interface IRelationInfo extends d3.SimulationLinkDatum<ITableInfo> { isMList?: boolean; repetitions: number; sourcePoint: Point; targetPoint: Point; } export interface RelationInfo extends IRelationInfo { fromTable: string; toTable: string; nullable: boolean; lite: boolean; } export interface MListRelationInfo extends IRelationInfo { } export interface ColorProviderInfo { name: string; niceName: string; } export interface SchemaMapInfo { tables: TableInfo[]; relations: RelationInfo[]; providers: ColorProviderInfo[]; allNodes: ITableInfo[]; /*after*/ allLinks: IRelationInfo[]; /*after*/ } export interface ClientColorProvider { name: string; getFill: (t: ITableInfo) => string; getStroke?: (t: ITableInfo) => string; getTooltip: (t: ITableInfo) => string; getMask?: (t: ITableInfo) => string | undefined; defs?: JSX.Element[]; } export class SchemaMapD3 { nodes!: ITableInfo[]; links!: IRelationInfo[]; simulation: d3.Simulation<ITableInfo, IRelationInfo>; fanIn: { [key: string]: IRelationInfo[] }; selectedTable: ITableInfo | undefined; link: d3.Selection<SVGPathElement, IRelationInfo, any, any>; nodeGroup: d3.Selection<SVGGElement, ITableInfo, any, any>; node: d3.Selection<SVGRectElement, ITableInfo, any, any>; label: d3.Selection<SVGTextElement, ITableInfo, any, any>; titles: d3.Selection<SVGTitleElement, ITableInfo, any, any>; constructor( public svgElement: SVGElement, public providers: { [name: string]: ClientColorProvider }, public map: SchemaMapInfo, public filter: string, public color: string, public width: number, public height: number) { this.simulation = d3.forceSimulation<ITableInfo, IRelationInfo>() .force("bounding", forceBoundingBox(width, height)) .force("repulsion", d3.forceManyBody().strength(-120)) .force("collide", d3.forceCollide(30)); this.fanIn = map.relations.groupToObject(a => a.toTable); this.regenerate(); const svg = d3.select(svgElement) .attr("width", width) .attr("height", height); this.link = svg.append<SVGGElement>("svg:g").attr("class", "links").selectAll(".link") .data(map.allLinks) .enter().append<SVGPathElement>("path") .attr("class", "link") .style("stroke-dasharray", d => (d as RelationInfo).lite ? "2, 2" : null) .style("stroke", "black") .attr("marker-end", d => "url(#" + (d.isMList ? "mlist_arrow" : (<RelationInfo>d).lite ? "lite_arrow" : "normal_arrow") + ")"); this.selectedLinks(); const nodesG = svg.append<SVGGElement>("svg:g").attr("class", "nodes"); const drag = d3.drag<SVGGElement, ITableInfo>() .on("start", d => { if (!d3.event.active) this.simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; }) .on("drag", d => { d.fx = d3.event.x; d.fy = d3.event.y; }) .on("end", d => { this.simulation.alphaTarget(0); }); this.nodeGroup = nodesG.selectAll(".nodeGroup") .data(map.allNodes) .enter() .append<SVGGElement>("svg:g").attr("class", "nodeGroup") .style("cursor", d => (d as TableInfo).typeName && Finder.isFindable((d as TableInfo).typeName, true) ? "pointer" : null) .on("click", d => { this.selectedTable = this.selectedTable == d ? undefined : d; this.selectedLinks(); this.selectedNode(); const event = d3.event; if (event.defaultPrevented) return; if ((<any>event).ctrlKey && (d as TableInfo).typeName) { window.open(Finder.findOptionsPath({ queryName: (d as TableInfo).typeName })); d3.event.preventDefault(); } }) .on("dblclick", d => { d.fx = null; d.fy = null; this.simulation.alpha(0.3).restart(); }) .call(drag); this.node = this.nodeGroup.append<SVGRectElement>("rect") .attr("class", d => "node " + d.entityBaseType) .attr("rx", n => n.entityBaseType == "Entity" ? 7 : n.entityBaseType == "Part" ? 4 : n.entityBaseType == "SemiSymbol" ? 5 : n.entityBaseType == "Symbol" ? 4 : n.entityBaseType == "EnumEntity" ? 3 : 0); const margin = 3; this.label = this.nodeGroup.append<SVGTextElement>("text") .attr("class", d => "node " + d.entityBaseType) .style("cursor", d => (d as TableInfo).typeName ? "pointer" : null) .text(d => d.niceName) .each(function (d) { const text = this as SVGTextElement; wrap(text, 60); const b = text.getBBox(); d.width = b.width + margin * 2; d.height = b.height + margin * 2; }); this.node.attr("width", d => d.width) .attr("height", d => d.height); this.selectedNode(); this.showHideNodes(); this.label.attr("transform", d => "translate(" + d.width / 2 + ", 0)"); this.titles = this.label.append<SVGTitleElement>('svg:title'); this.drawColor(); this.simulation.on("tick", this.onTick); } regenerate() { const parts = this.filter.match(/[+-]?((\w+)|\*)/g); function isMatch(str: string): boolean { if (!parts) return true; for (let i = parts.length - 1; i >= 0; i--) { const p = parts[i]; const pair = p.startsWith("+") ? { isPositive: true, token: p.after("+") } : p.startsWith("-") ? { isPositive: false, token: p.after("-") } : { isPositive: true, token: p }; if (pair.token == "*" || str.toLowerCase().contains(pair.token.toLowerCase())) return pair.isPositive; } return false; }; this.nodes = this.map.allNodes.filter((n, i) => this.filter == undefined || isMatch(n.namespace.toLowerCase() + "|" + n.tableName.toLowerCase() + "|" + n.niceName.toLowerCase())); this.links = this.map.allLinks.filter(l => this.nodes.contains(<ITableInfo>l.source) && this.nodes.contains(<ITableInfo>l.target)); const numNodes = this.nodes.length; let distance = numNodes < 10 ? 110 : numNodes < 20 ? 80 : numNodes < 30 ? 65 : numNodes < 50 ? 50 : numNodes < 100 ? 35 : numNodes < 200 ? 30 : 25; this.simulation .force("link", d3.forceLink<ITableInfo, IRelationInfo>(this.links) .distance(d => d.isMList ? distance * 0.7 : (d as RelationInfo).lite ? distance * 1.6 : distance * 1.2) .strength(d => 0.7 * (d.isMList ? 1 : this.getOpacity((<RelationInfo>d).toTable))) ) .nodes(this.nodes) .alpha(1) .restart(); } selectedLinks() { const selectedTable = this.selectedTable; this.link .style("stroke-width", d => d.source == selectedTable || d.target == selectedTable ? 1.5 : d.isMList ? 1.5 : 1) .style("opacity", d => d.source == selectedTable || d.target == selectedTable ? 1 : d.isMList ? 0.8 : Math.max(.1, this.getOpacity((<RelationInfo>d).toTable))); } selectedNode() { this.label.style("font-weight", d => d == this.selectedTable ? "bold" : null); } showHideNodes() { this.nodeGroup.style("display", n => this.nodes.indexOf(n) == -1 ? "none" : "inline"); this.link.style("display", r => this.links.indexOf(r) == -1 ? "none" : "inline"); } static opacities = [1, .9, .8, .7, .6, .5, .4, .3, .25, .2, .15, .1, .07, .05, .03, .02]; getOpacity(toTable: string) { const length = this.fanIn[toTable].filter(l => this.nodes.indexOf(<ITableInfo>l.source) != -1).length; const min = Math.min(length, SchemaMapD3.opacities.length - 1); return SchemaMapD3.opacities[min]; } setFilter(newFilter: string) { this.filter = newFilter; this.regenerate(); this.selectedLinks(); this.showHideNodes(); } setColor(newColor: string) { this.color = newColor; this.drawColor(); } drawColor() { const cp = this.providers[this.color]; this.node.style("fill", cp.getFill) .style("stroke", cp.getStroke || cp.getFill) .style("mask", a => cp.getMask && cp.getMask(a) || null); this.titles.text(t => cp.getTooltip(t) + " (" + t.entityBaseType + ")"); } stop() { this.simulation.stop(); } onTick = () => { const visibleLink = this.link.filter(f => this.links.indexOf(f) != -1); visibleLink.each(rel => { rel.sourcePoint = calculatePoint(rel.source as ITableInfo, rel.target as ITableInfo); rel.targetPoint = calculatePoint(rel.target as ITableInfo, rel.source as ITableInfo); }); visibleLink.attr("d", l => this.getPathExpression(l)); this.nodeGroup.filter(d => this.nodes.indexOf(d) != -1) .attr("transform", d => "translate(" + (d.x! - d.width / 2) + ", " + (d.y! - d.height / 2) + ")"); } getPathExpression(l: IRelationInfo) { const s = l.sourcePoint; const t = l.targetPoint; if (l.source == l.target) { const dx = (l.repetitions % 2) * 2 - 1; const dy = ((l.repetitions + 1) % 2) * 2 - 1; const source = l.source as ITableInfo; const c = calculatePoint(source as ITableInfo, { x: source.x! + dx * (source.width / 2), y: source.y! + dy * (source.height / 2), }); return `M${c.x} ${c.y} C ${c.x! + 50 * dx} ${c.y} ${c.x} ${c.y! + 50 * dy} ${c.x} ${c.y}`; } else { let p = this.getPointRepetitions(s, t, l.repetitions); return `M${s.x} ${s.y} Q ${p.x} ${p.y} ${t.x} ${t.y}`; } } getPointRepetitions(s: Point, t: Point, repetitions: number): Point { const m: Point = { x: (s.x! + t.x!) / 2, y: (s.y! + t.y!) / 2 }; const d: Point = { x: (s.x! - t.x!), y: (s.y! - t.y!) }; let h = Math.sqrt(d.x! * d.x! + d.y! * d.y!); if (h == 0) h = 1; //0, 10, -10, 20, -20, 30, -30 const repPixels = Math.floor(repetitions + 1 / 2) * ((repetitions % 2) * 2 - 1); const p: Point = { x: m.x! + (d.y! / h) * 20 * repPixels, y: m.y! - (d.x! / h) * 20 * repPixels }; return p; } }